-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathshim.ts
94 lines (92 loc) · 2.56 KB
/
shim.ts
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
DataView.prototype.add = function (offset) {
return new DataView(this.buffer, offset + this.byteOffset);
};
DataView.prototype.writeU8 = function (val) {
return this.setUint8(0, val);
};
DataView.prototype.writeU16 = function (val) {
return this.setUint16(0, val);
};
DataView.prototype.writeU32 = function (val) {
return this.setUint32(0, val);
};
DataView.prototype.writeU64 = function (val) {
return this.setBigUint64(0, val);
};
DataView.prototype.readU8 = function () {
return this.getUint8(0);
};
DataView.prototype.readU16 = function () {
return this.getUint16(0);
};
DataView.prototype.readU16LE = function () {
return this.getUint16(0, true);
};
DataView.prototype.readU32 = function () {
return this.getUint32(0);
};
DataView.prototype.readU32LE = function () {
return this.getUint32(0, true);
};
DataView.prototype.readU64 = function () {
return this.getBigUint64(0);
};
const isU8Array = (x: Uint8Array | number[]): x is Uint8Array => {
return x instanceof Uint8Array;
};
DataView.prototype.writeByteArray = function (arr) {
const len = isU8Array(arr) ? arr.byteLength : arr.length;
for (let i = 0; i < len; i++) {
this.setUint8(i, arr[i]);
}
};
DataView.prototype.readByteArray = function (len) {
let ret = new DataView(new ArrayBuffer(len));
for (let i = 0; i < len; i++) {
ret.setUint8(i, this.getUint8(i));
}
return ret;
};
DataView.prototype.readString = function (len) {
const ba = this.readByteArray(len);
const s = String.fromCharCode.apply(null, new Uint8Array(ba.buffer));
const nullByte = s.indexOf("\0");
if (nullByte !== -1) return s.substring(0, nullByte);
return s;
};
DataView.prototype.writeString = function (str) {
const bytes = [...str].map((_, i) => str.charCodeAt(i));
return this.writeByteArray(bytes);
};
DataView.prototype.startsWith = function (arr) {
if (this.byteLength < arr.length) {
return false;
}
for (let i = 0; i < arr.length; i++) {
if (this.add(i).readU8() != arr[i]) {
return false;
}
}
return true;
};
declare global {
interface DataView {
add(offset: number): DataView;
readByteArray(len: number): DataView;
writeString(str: string): void;
readString(len: number): string;
readU16(): number;
readU16LE(): number;
readU32(): number;
readU32LE(): number;
readU64(): bigint;
readU8(): number;
writeByteArray(arr: Uint8Array | number[]): void;
writeU16(n: number): void;
writeU32(n: number): void;
writeU64(n: bigint): void;
writeU8(n: number): void;
startsWith(arr: number[]): boolean;
}
}
export default global;