Implement smart buffer

This commit is contained in:
Jack Hadrill
2022-02-02 01:58:55 +00:00
parent a93bfc182f
commit 7d1a0991e4
12 changed files with 1717 additions and 152 deletions

View File

@@ -1,16 +1,35 @@
import { BufferReader } from '../buffer-reader'
import { MAX_DATA_LENGTH } from '../common'
import { SmartBuffer } from '../smart-buffer'
export class IncomingPacket extends BufferReader {
messageType: number
senderId: number
length: number
data: Buffer
export class IncomingPacket extends SmartBuffer {
fields: {
messageType: number
senderId: number
length: number
data: Uint8Array
}
constructor (data: Buffer) {
constructor (data: ArrayBuffer) {
super()
this.messageType = this.readUInt16()
this.senderId = this.readUInt32()
this.length = this.readUInt16()
this.data = this.readBuffer(this.length)
this.data = new Uint8Array(data)
this.fields = {
messageType: this.readUInt16(),
senderId: this.readUInt32(),
length: this.readUInt16(),
data: this.readBytes(this.length)
}
}
}
export class OutgoingPacket extends SmartBuffer {
constructor (messageType: number, data: Uint8Array = new Uint8Array(0)) {
super()
if (data.length > MAX_DATA_LENGTH) {
throw RangeError(`Specified data of length ${data.length} exceeds max data length ${MAX_DATA_LENGTH}.`)
}
this.writeUInt16(messageType)
this.writeUInt16(data.length)
this.writeBytes(data)
}
}