Created
September 18, 2023 08:31
-
-
Save sisou/cc85337814b5e42386ddf46a2e9ceee8 to your computer and use it in GitHub Desktop.
Simple JS Buffer implementation to easily read and write Uint8Arrays
This file contains hidden or 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 Buffer extends Uint8Array { | |
/** | |
* @param {number} length | |
*/ | |
constructor(length) { | |
super(length); | |
this._cursor = 0; | |
} | |
/** | |
* @param {number} length | |
* @returns {Uint8Array} | |
*/ | |
read(length) { | |
if (this._cursor + length > this.length) { | |
throw new Error(`Buffer overflow: ${this._cursor} + ${length} > ${this.length}`); | |
} | |
const result = this.slice(this._cursor, this._cursor + length); | |
this._cursor += length; | |
return result; | |
} | |
/** | |
* @returns {number} | |
*/ | |
readUint8() { | |
return this.read(1)[0]; | |
} | |
/** | |
* @param {ArrayLike<number>} data | |
* @returns {number} | |
*/ | |
write(data) { | |
if (this._cursor + data.length > this.length) { | |
throw new Error(`Buffer overflow: ${this._cursor} + ${data.length} > ${this.length}`); | |
} | |
this.set(data, this._cursor); | |
return this._cursor += data.length; | |
} | |
/** | |
* @param {number} byte | |
* @returns {number} | |
*/ | |
writeUint8(byte) { | |
return this.write([byte]); | |
} | |
resetCursor() { | |
this._cursor = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment