-
Notifications
You must be signed in to change notification settings - Fork 0
/
nibbleArray.ts
35 lines (31 loc) · 863 Bytes
/
nibbleArray.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
export default class NibbleArray {
private array:Uint8Array;
public constructor(size:number|ArrayBuffer|Uint8Array) {
if (size instanceof ArrayBuffer) {
this.array = new Uint8Array(size);
} else if (size instanceof Uint8Array) {
this.array = new Uint8Array(size);
} else {
this.array = new Uint8Array(size >> 1);
}
}
public get(index:number) {
const arrayIndex = index >> 1;
if ((index & 1) === 0) {
return this.array[arrayIndex] & 0xf;
} else {
return this.array[arrayIndex] >> 4 & 0xf;
}
}
public set(index:number, value:number) {
const arrayIndex = index >> 1;
if ((index & 1) === 0) {
this.array[arrayIndex] = this.array[arrayIndex] & 0xf0 | value & 0xf;
} else {
this.array[arrayIndex] = this.array[arrayIndex] & 0xf | (value & 0xf) << 4;
}
}
public toBuffer() {
return Buffer.from(this.array);
}
}