diff --git a/assembly/buffer/index.ts b/assembly/buffer/index.ts index 19a28b2..c73f012 100644 --- a/assembly/buffer/index.ts +++ b/assembly/buffer/index.ts @@ -23,6 +23,11 @@ export class Buffer extends Uint8Array { return result; } + readUInt8(offset: i32 = 0): u8 { + if(offset > this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + usize(offset)); + } + writeUInt8(value: u8, offset: i32 = 0): i32 { if(offset > this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE); store(this.dataStart + offset, value); diff --git a/assembly/node.d.ts b/assembly/node.d.ts index 1fc97e4..895ea93 100644 --- a/assembly/node.d.ts +++ b/assembly/node.d.ts @@ -3,6 +3,8 @@ 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 an unsigned integer at the designated offset. */ + readUInt8(offset?: i32): u8; /** Writes an inputted u8 value to the buffer, at the desired offset. */ writeUInt8(value:u8, offset?:i32): i32; /** Writes an inputted value to the buffer, at the desired offset. */ diff --git a/tests/buffer.spec.ts b/tests/buffer.spec.ts index 89dfbba..9ba33fe 100644 --- a/tests/buffer.spec.ts +++ b/tests/buffer.spec.ts @@ -43,6 +43,22 @@ describe("buffer", () => { // TODO: expectFn(() => { Buffer.allocUnsafe(BLOCK_MAXSIZE + 1); }).toThrow(); }); + test("#readUInt8", () => { + let buff = new Buffer(10); + buff[0] = -2; + buff[9] = 47; + // Testing casting between u8 and i8. + expect(buff.readUInt8(0)).toBe(254); + expect(buff.readUInt8()).toBe(254); + // Testing offset + expect(buff.readUInt8(9)).toBe(47); + // TODO: + // expectFn(() => { + // let newBuff = new Buffer(1); + // newBuff.readUInt8(5); + // }).toThrow(); + }); + test("#writeUInt8", () => { let buff = new Buffer(5); expect(buff.writeUInt8(4)).toBe(1); @@ -72,5 +88,5 @@ describe("buffer", () => { // let newBuff = new Buffer(1); // newBuff.readInt8(5); // }).toThrow(); - }) + }); });