Initial import
This commit is contained in:
81
src/parser.ts
Normal file
81
src/parser.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { equalBytes } from "@noble/ciphers/utils.js";
|
||||
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
|
||||
|
||||
export {
|
||||
bytesToHex,
|
||||
hexToBytes,
|
||||
equalBytes
|
||||
};
|
||||
|
||||
export const base64ToBytes = (base64: string): Uint8Array => {
|
||||
const binaryString = atob(base64);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export class BufferReader {
|
||||
private buffer: Uint8Array;
|
||||
private offset: number;
|
||||
|
||||
constructor(buffer: Uint8Array) {
|
||||
this.buffer = buffer;
|
||||
this.offset = 0;
|
||||
}
|
||||
|
||||
public readByte(): number {
|
||||
return this.buffer[this.offset++];
|
||||
}
|
||||
|
||||
public readBytes(length?: number): Uint8Array {
|
||||
if (length === undefined) {
|
||||
length = this.buffer.length - this.offset;
|
||||
}
|
||||
const bytes = this.buffer.slice(this.offset, this.offset + length);
|
||||
this.offset += length;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public hasMore(): boolean {
|
||||
return this.offset < this.buffer.length;
|
||||
}
|
||||
|
||||
public remainingBytes(): number {
|
||||
return this.buffer.length - this.offset;
|
||||
}
|
||||
|
||||
public peekByte(): number {
|
||||
return this.buffer[this.offset];
|
||||
}
|
||||
|
||||
public readUint16LE(): number {
|
||||
const value = this.buffer[this.offset] | (this.buffer[this.offset + 1] << 8);
|
||||
this.offset += 2;
|
||||
return value;
|
||||
}
|
||||
|
||||
public readUint32LE(): number {
|
||||
const value = this.buffer[this.offset] | (this.buffer[this.offset + 1] << 8) | (this.buffer[this.offset + 2] << 16) | (this.buffer[this.offset + 3] << 24);
|
||||
this.offset += 4;
|
||||
return value;
|
||||
}
|
||||
|
||||
public readInt16LE(): number {
|
||||
const value = this.buffer[this.offset] | (this.buffer[this.offset + 1] << 8);
|
||||
this.offset += 2;
|
||||
return value < 0x8000 ? value : value - 0x10000;
|
||||
}
|
||||
|
||||
public readInt32LE(): number {
|
||||
const value = this.buffer[this.offset] | (this.buffer[this.offset + 1] << 8) | (this.buffer[this.offset + 2] << 16) | (this.buffer[this.offset + 3] << 24);
|
||||
this.offset += 4;
|
||||
return value < 0x80000000 ? value : value - 0x100000000;
|
||||
}
|
||||
|
||||
public readTimestamp(): Date {
|
||||
const timestamp = this.readUint32LE();
|
||||
return new Date(timestamp * 1000);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user