mc-beta-server/nibbleArray.ts

35 lines
855 B
TypeScript
Raw Normal View History

2023-04-11 07:47:56 +01:00
export 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 {
2023-11-02 08:31:43 +00:00
this.array = new Uint8Array(size >> 1);
2023-04-11 07:47:56 +01:00
}
}
public get(index:number) {
2023-11-02 08:31:43 +00:00
const arrayIndex = index >> 1;
if ((index & 1) === 0) {
return this.array[arrayIndex] & 0xf;
2023-04-11 07:47:56 +01:00
} else {
2023-11-02 08:31:43 +00:00
return this.array[arrayIndex] >> 4 & 0xf;
2023-04-11 07:47:56 +01:00
}
}
public set(index:number, value:number) {
2023-11-02 08:31:43 +00:00
const arrayIndex = index >> 1;
if ((index & 1) === 0) {
this.array[arrayIndex] = this.array[arrayIndex] & 0xf0 | value & 0xf;
2023-04-11 07:47:56 +01:00
} else {
2023-11-02 08:31:43 +00:00
this.array[arrayIndex] = this.array[arrayIndex] & 0xf | (value & 0xf) << 4;
2023-04-11 07:47:56 +01:00
}
}
public toBuffer() {
return Buffer.from(this.array);
}
}