buffer.ts•1.54 kB
export class ReadStream {
index = 0;
private dataView: DataView;
private textDecoder = new TextDecoder('ascii');
constructor(public buffer: ArrayBuffer) {
this.dataView = new DataView(buffer);
}
seek(size: number) {
this.index += size;
}
read(size: number) {
return this.buffer.slice(this.index, this.index + size);
}
consume(size: number) {
const subarray = this.read(size);
this.seek(size);
return subarray;
}
private increment(size: number) {
return (this.index += size) - size;
}
byte(size: number) {
return this.consume(size);
}
ascii(size: number) {
return this.textDecoder.decode(this.consume(size));
}
int8() {
return this.dataView.getInt8(this.increment(1));
}
int16() {
return this.dataView.getInt16(this.increment(2), true);
}
int32() {
return this.dataView.getInt32(this.increment(4), true);
}
int64() {
return this.dataView.getBigInt64(this.increment(8), true);
}
uint8() {
return this.dataView.getUint8(this.increment(1));
}
uint16() {
return this.dataView.getUint16(this.increment(2), true);
}
uint32() {
return this.dataView.getUint32(this.increment(4), true);
}
uint64() {
return this.dataView.getBigUint64(this.increment(8), true);
}
float32() {
return this.dataView.getFloat32(this.increment(4), true);
}
float64() {
return this.dataView.getFloat64(this.increment(8), true);
}
boolean() {
return this.dataView.getUint8(this.increment(1)) === 1;
}
}