Skip to content

Commit

Permalink
feat: ✨ add float methods
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardDorian committed Apr 6, 2022
1 parent fdd081e commit 86ed029
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Encode and decode:
- UUID
- Byte
- Boolean
- Float

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

/**
* Write a float to the buffer
* @param value The value to write (number)
* @example
* ```javascript
* const buf = new BufWrapper();
* buf.writeFloat(12.34);
* console.log(buf.buffer); // <Buffer 41 45 70 a4>
* ```
*/
public writeFloat(value: number): void {
const buf = Buffer.alloc(4);
buf.writeFloatBE(value);
this.buffer = Buffer.concat([this.buffer, buf]);
}

/**
* Read a float from the buffer
* @returns The float read from the buffer
* @example
* ```javascript
* const buffer = Buffer.from([ 0x41, 0x45, 0x70, 0xa4 ]);
* const buf = new BufWrapper(buffer);
* const decoded = buf.readFloat();
* console.log(decoded); // 12.34000015258789
* ```
*/
public readFloat(): number {
const value = this.buffer.readFloatBE(this.offset);
this.offset += 4;
return value;
}
}
26 changes: 26 additions & 0 deletions test/float.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('Float', () => {
it('Write 1', () => {
const buf = new BufWrapper();
buf.writeFloat(12.34);
assert.equal(buf.buffer.toString('hex'), '414570a4');
});

it('Write 2', () => {
const buf = new BufWrapper();
buf.writeFloat(43.21);
assert.equal(buf.buffer.toString('hex'), '422cd70a');
});

it('Read 1', () => {
const buf = new BufWrapper(Buffer.from([0x41, 0x45, 0x70, 0xa4]));
assert.equal(Math.round(buf.readFloat() * 100) / 100, 12.34);
});

it('Read 2', () => {
const buf = new BufWrapper(Buffer.from([0x42, 0x2c, 0xd7, 0x0a]));
assert.equal(Math.round(buf.readFloat() * 100) / 100, 43.21);
});
});

0 comments on commit 86ed029

Please sign in to comment.