Skip to content

Commit

Permalink
feat: ✨ add bytes methods
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardDorian committed Apr 4, 2022
1 parent 3e02aa5 commit 2de7784
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
32 changes: 32 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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); // <Buffer 01 02 03>
* ```
*/
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); // <Buffer 01 02 03>
* ```
*/
public readBytes(length: number): Buffer {
const value = this.buffer.slice(this.offset, this.offset + length);
this.offset += length;
return value;
}
}
40 changes: 40 additions & 0 deletions test/bytes.test.js
Original file line number Diff line number Diff line change
@@ -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');
});
});

0 comments on commit 2de7784

Please sign in to comment.