From 86ed02968a3c18d62aff1f2dd1c1d2062e795f30 Mon Sep 17 00:00:00 2001 From: RichardDorian Date: Wed, 6 Apr 2022 09:02:09 +0200 Subject: [PATCH] feat: :sparkles: add float methods --- README.md | 1 + package.json | 2 +- src/index.ts | 33 +++++++++++++++++++++++++++++++++ test/float.test.js | 26 ++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 test/float.test.js diff --git a/README.md b/README.md index 9433ef0..1d8d691 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ Encode and decode: - UUID - Byte - Boolean +- Float ⚠️ They are all signed and big endian (As Java does) diff --git a/package.json b/package.json index 4969ebe..3a28fc9 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/index.ts b/src/index.ts index 6542f71..a4de7ac 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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); // + * ``` + */ + 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; + } } diff --git a/test/float.test.js b/test/float.test.js new file mode 100644 index 0000000..26e9fc9 --- /dev/null +++ b/test/float.test.js @@ -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); + }); +});