From 2de7784d2c19e37fcb8636d700015f4b7b7f4d7d Mon Sep 17 00:00:00 2001 From: RichardDorian Date: Mon, 4 Apr 2022 22:07:34 +0200 Subject: [PATCH] feat: :sparkles: add bytes methods --- package.json | 2 +- src/index.ts | 32 ++++++++++++++++++++++++++++++++ test/bytes.test.js | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 test/bytes.test.js diff --git a/package.json b/package.json index 34629bd..29298f3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@minecraft-js/bufwrapper", - "version": "1.2.0", + "version": "1.2.1", "description": "Encode and decode data using buffers", "main": "dist/index.js", "scripts": { diff --git a/src/index.ts b/src/index.ts index fca0306..71652bc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -265,4 +265,36 @@ export default class BufWrapper { value.substr(20) : value; } + + /** + * Write raw bytes to the buffer + * @param value The value to write (a buffer or an array of bytes) + * @example + * ```javascript + * const buf = new BufWrapper(); + * buf.writeBytes([ 0x01, 0x02, 0x03 ]); + * console.log(buf.buffer); // + * ``` + */ + public writeBytes(value: Buffer | number[]): void { + this.buffer = Buffer.concat([this.buffer, Buffer.from(value)]); + } + + /** + * Read raw bytes from the buffer + * @param length The number of bytes to read + * @returns The bytes read from the buffer + * @example + * ```javascript + * const buffer = Buffer.from([ 0x01, 0x02, 0x03 ]); + * const buf = new BufWrapper(buffer); + * const decoded = buf.readBytes(3); + * console.log(decoded); // + * ``` + */ + public readBytes(length: number): Buffer { + const value = this.buffer.slice(this.offset, this.offset + length); + this.offset += length; + return value; + } } diff --git a/test/bytes.test.js b/test/bytes.test.js new file mode 100644 index 0000000..6e369f7 --- /dev/null +++ b/test/bytes.test.js @@ -0,0 +1,40 @@ +const { assert } = require('chai'); +const BufWrapper = require('../dist').default; + +describe('Bytes', () => { + it('Write 1', () => { + const buf = new BufWrapper(); + buf.writeBytes([ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, + 0x0d, 0x0e, 0x0f, 0x10, + ]); + assert.equal( + buf.buffer.toString('hex'), + '0102030405060708090a0b0c0d0e0f10' + ); + }); + + it('Write 2', () => { + const buf = new BufWrapper(); + buf.writeBytes(Buffer.from([0x01, 0x02, 0x03])); + assert.equal(buf.buffer.toString('hex'), '010203'); + }); + + it('Read 1', () => { + const buf = new BufWrapper( + Buffer.from([ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, + 0x0d, 0x0e, 0x0f, 0x10, + ]) + ); + assert.equal( + buf.readBytes(16).toString('hex'), + '0102030405060708090a0b0c0d0e0f10' + ); + }); + + it('Read 2', () => { + const buf = new BufWrapper(Buffer.from([0x01, 0x02, 0x03])); + assert.equal(buf.readBytes(3).toString('hex'), '010203'); + }); +});