Last active
July 28, 2023 14:43
-
-
Save realsba/725fd395a26ac195da737dabf0a97194 to your computer and use it in GitHub Desktop.
JS implementation of BinaryStream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class BinaryStream { | |
_offset = 0; | |
_dataview = null; | |
_uint8Array = null; | |
constructor(buffer) { | |
this._dataview = new DataView(buffer); | |
this._uint8Array = new Uint8Array(buffer); | |
} | |
get buffer() { | |
return this._dataview.buffer; | |
} | |
readUInt8() { | |
return this._dataview.getUint8(this._offset++); | |
}; | |
readUInt16() { | |
let value = this._dataview.getUint16(this._offset); | |
this._offset += 2; | |
return value; | |
}; | |
readUInt32() { | |
let value = this._dataview.getUint32(this._offset); | |
this._offset += 4; | |
return value; | |
}; | |
readFloat() { | |
let value = this._dataview.getFloat32(this._offset); | |
this._offset += 4; | |
return value; | |
}; | |
readString() { | |
let decoder = new TextDecoder(); | |
let length = this.readUInt16(); | |
let value = decoder.decode(this._dataview.buffer.slice(this._offset, this._offset + length)); | |
this._offset += length; | |
return value; | |
}; | |
writeUInt8(value) { | |
this._dataview.setUint8(this._offset++, value); | |
}; | |
writeUInt16(value) { | |
this._dataview.setUint16(this._offset, value); | |
this._offset += 2; | |
}; | |
writeUInt32(value) { | |
this._dataview.setUint32(this._offset, value); | |
this._offset += 4; | |
}; | |
writeFloat(value) { | |
this._dataview.setFloat32(this._offset, value); | |
this._offset += 4; | |
}; | |
writeString(value) { | |
let encoder = new TextEncoder(); | |
value = encoder.encode(value); | |
this.writeUInt16(value.length); | |
this._uint8Array.set(value, this._offset); | |
this._offset += value.length; | |
}; | |
} |
belichuk
commented
Jul 28, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment