-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathindex.ts
More file actions
61 lines (52 loc) · 1.92 KB
/
index.ts
File metadata and controls
61 lines (52 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { BLOCK_MAXSIZE } from "rt/common";
import { E_INVALIDLENGTH, E_INDEXOUTOFRANGE } from "util/error";
import { Uint8Array } from "typedarray";
export class Buffer extends Uint8Array {
constructor(size: i32) {
super(size);
}
public static alloc(size: i32): Buffer {
return new Buffer(size);
}
@unsafe public static allocUnsafe(size: i32): Buffer {
// Node throws an error if size is less than 0
if (u32(size) > BLOCK_MAXSIZE) throw new RangeError(E_INVALIDLENGTH);
let buffer = __alloc(size, idof<ArrayBuffer>());
// This retains the pointer to the result Buffer.
let result = changetype<Buffer>(__alloc(offsetof<Buffer>(), idof<Buffer>()));
result.data = changetype<ArrayBuffer>(buffer);
result.dataStart = changetype<usize>(buffer);
result.dataLength = size;
return result;
}
public static compare(a: Buffer, b: Buffer): i32 {
let compareLength = min<i32>(a.length, b.length);
let result = memory.compare(a.dataStart, b.dataStart, compareLength);
if (result == 0) {
return a.length - b.length;
} else {
return result;
}
};
public static isBuffer<T>(value: T): bool {
return value instanceof Buffer;
}
readUInt8(offset: i32 = 0): u8 {
if(<u32>offset >= this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE);
return load<u8>(this.dataStart + usize(offset));
}
writeUInt8(value: u8, offset: i32 = 0): i32 {
if(<u32>offset >= this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE);
store<u8>(this.dataStart + offset, value);
return offset + 1;
}
writeInt8(value: i8, offset: i32 = 0): i32 {
if(<u32>offset >= this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE);
store<i8>(this.dataStart + offset, value);
return offset + 1;
}
readInt8(offset: i32 = 0): i8 {
if(<u32>offset >= this.dataLength) throw new RangeError(E_INDEXOUTOFRANGE);
return load<i8>(this.dataStart + usize(offset));
}
}