Skip to content

Commit

Permalink
feat: ✨ add booleans
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardDorian committed Apr 5, 2022
1 parent 2de7784 commit fdd081e
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ Encode and decode:
- Array of strings
- Array of ints
- UUID
- Byte
- Boolean

⚠️ They are all signed and big endian (As Java does)

Expand Down
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.1",
"version": "1.2.2",
"description": "Encode and decode data using buffers",
"main": "dist/index.js",
"scripts": {
Expand Down
31 changes: 31 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,4 +297,35 @@ export default class BufWrapper {
this.offset += length;
return value;
}

/**
* Write a boolean to the buffer
* @param value The value to write (boolean)
* @example
* ```javascript
* const buf = new BufWrapper();
* buf.writeBoolean(true);
* console.log(buf.buffer); // <Buffer 01>
* ```
*/
public writeBoolean(value: boolean): void {
this.buffer = Buffer.concat([this.buffer, Buffer.from([value ? 1 : 0])]);
}

/**
* Read a boolean from the buffer
* @returns The boolean read from the buffer
* @example
* ```javascript
* const buffer = Buffer.from([ 0x01 ]);
* const buf = new BufWrapper(buffer);
* const decoded = buf.readBoolean();
* console.log(decoded); // true
* ```
*/
public readBoolean(): boolean {
const value = this.buffer.readUInt8(this.offset) === 1;
this.offset += 1;
return value;
}
}
26 changes: 26 additions & 0 deletions test/boolean.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { assert } = require('chai');
const BufWrapper = require('../dist').default;

describe('Boolean', () => {
it('Write 1', () => {
const buf = new BufWrapper();
buf.writeBoolean(true);
assert.equal(buf.buffer.toString('hex'), '01');
});

it('Write 2', () => {
const buf = new BufWrapper();
buf.writeBoolean(false);
assert.equal(buf.buffer.toString('hex'), '00');
});

it('Read 1', () => {
const buf = new BufWrapper(Buffer.from([0x01]));
assert.equal(buf.readBoolean(), true);
});

it('Read 2', () => {
const buf = new BufWrapper(Buffer.from([0x00]));
assert.equal(buf.readBoolean(), false);
});
});

0 comments on commit fdd081e

Please sign in to comment.