diff --git a/assembly/buffer/index.ts b/assembly/buffer/index.ts index 66866bf..b42edf7 100644 --- a/assembly/buffer/index.ts +++ b/assembly/buffer/index.ts @@ -22,4 +22,9 @@ export class Buffer extends Uint8Array { result.dataLength = size; return result; } + + readInt8(offset: i32 = 0): i8 { + if(offset >= this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + usize(offset)); + } } diff --git a/assembly/node.d.ts b/assembly/node.d.ts index 80075a8..52f1eba 100644 --- a/assembly/node.d.ts +++ b/assembly/node.d.ts @@ -3,4 +3,6 @@ declare class Buffer extends Uint8Array { static alloc(size: i32): Buffer; /** This method allocates a new Buffer of indicated size. This is unsafe because the data is not zeroed. */ static allocUnsafe(size: i32): Buffer; + /** Reads a signed integer at the designated offset. */ + readInt8(offset?: i32): i8; } diff --git a/tests/buffer.spec.ts b/tests/buffer.spec.ts index 1596845..d202073 100644 --- a/tests/buffer.spec.ts +++ b/tests/buffer.spec.ts @@ -42,4 +42,19 @@ describe("buffer", () => { // TODO: expectFn(() => { Buffer.allocUnsafe(-1); }).toThrow(); // TODO: expectFn(() => { Buffer.allocUnsafe(BLOCK_MAXSIZE + 1); }).toThrow(); }); + + test("#readInt8", () => { + let buff = new Buffer(10); + buff[0] = 5; + buff[9] = 255; + expect(buff.readInt8(0)).toBe(5); + expect(buff.readInt8()).toBe(5); + // Testing offset, and casting between u8 and i8. + expect(buff.readInt8(9)).toBe(-1); + // TODO: + // expectFn(() => { + // let newBuff = new Buffer(1); + // newBuff.readInt8(5); + // }).toThrow(); + }) });