Skip to content

Commit afbf5c1

Browse files
committed
[Implement] Buffer.readUInt8
1 parent c3a162d commit afbf5c1

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

assembly/buffer/index.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,14 @@ export class Buffer extends Uint8Array {
2222
result.dataLength = size;
2323
return result;
2424
}
25+
26+
readInt8(offset: i32 = 0): i8 {
27+
if(<u32>offset >= this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE);
28+
return load<i8>(this.dataStart + usize(offset));
29+
}
30+
31+
readUInt8(offset: i32 = 0): u8 {
32+
if(<u32>offset > this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE);
33+
return load<u8>(this.dataStart + usize(offset));
34+
}
2535
}

assembly/node.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,7 @@ declare class Buffer extends Uint8Array {
33
static alloc(size: i32): Buffer;
44
/** This method allocates a new Buffer of indicated size. This is unsafe because the data is not zeroed. */
55
static allocUnsafe(size: i32): Buffer;
6+
/** Reads a signed integer at the designated offset. */
7+
readInt8(offset?: i32): i8;
8+
readUInt8(offset?: i32): u8;
69
}

tests/buffer.spec.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,35 @@ describe("buffer", () => {
4242
// TODO: expectFn(() => { Buffer.allocUnsafe(-1); }).toThrow();
4343
// TODO: expectFn(() => { Buffer.allocUnsafe(BLOCK_MAXSIZE + 1); }).toThrow();
4444
});
45+
46+
test("#readInt8", () => {
47+
let buff = new Buffer(10);
48+
buff[0] = 5;
49+
buff[9] = 255;
50+
expect<i8>(buff.readInt8(0)).toBe(5);
51+
expect<i8>(buff.readInt8()).toBe(5);
52+
// Testing offset, and casting between u8 and i8.
53+
expect<i8>(buff.readInt8(9)).toBe(-1);
54+
// TODO:
55+
// expectFn(() => {
56+
// let newBuff = new Buffer(1);
57+
// newBuff.readInt8(5);
58+
// }).toThrow();
59+
});
60+
61+
test("#readUInt8", () => {
62+
let buff = new Buffer(10);
63+
buff[0] = -2;
64+
buff[9] = 47;
65+
// Testing casting between u8 and i8.
66+
expect<u8>(buff.readUInt8(0)).toBe(254);
67+
expect<u8>(buff.readUInt8()).toBe(254);
68+
// Testing offset
69+
expect<u8>(buff.readUInt8(9)).toBe(47);
70+
// TODO:
71+
// expectFn(() => {
72+
// let newBuff = new Buffer(1);
73+
// newBuff.readUInt8(5);
74+
// }).toThrow();
75+
});
4576
});

0 commit comments

Comments
 (0)