109 lines
2.5 KiB
TypeScript
109 lines
2.5 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// binary messages and saves, written and read a number at a time. little-endian, which is what both use
|
|
export class Writer {
|
|
#bytes = new Uint8Array(16 * 1024);
|
|
#view = new DataView(this.#bytes.buffer);
|
|
#length = 0;
|
|
|
|
#reserve(size: number) {
|
|
if (this.#length + size <= this.#bytes.length) return;
|
|
const bytes = new Uint8Array(Math.max(this.#bytes.length * 2, this.#length + size));
|
|
bytes.set(this.#bytes);
|
|
this.#bytes = bytes;
|
|
this.#view = new DataView(bytes.buffer);
|
|
}
|
|
|
|
u8(value: number) {
|
|
this.#reserve(1);
|
|
this.#bytes[this.#length++] = value;
|
|
}
|
|
|
|
u16(value: number) {
|
|
this.#reserve(2);
|
|
this.#view.setUint16(this.#length, value, true);
|
|
this.#length += 2;
|
|
}
|
|
|
|
i16(value: number) {
|
|
this.#reserve(2);
|
|
this.#view.setInt16(this.#length, value, true);
|
|
this.#length += 2;
|
|
}
|
|
|
|
u32(value: number) {
|
|
this.#reserve(4);
|
|
this.#view.setUint32(this.#length, value, true);
|
|
this.#length += 4;
|
|
}
|
|
|
|
// a u8 length, then the text as utf-8
|
|
string(text: string) {
|
|
const bytes = new TextEncoder().encode(text);
|
|
if (bytes.length > 255) throw new Error(`${text} is too long`);
|
|
this.u8(bytes.length);
|
|
this.#reserve(bytes.length);
|
|
this.#bytes.set(bytes, this.#length);
|
|
this.#length += bytes.length;
|
|
}
|
|
|
|
bytes() {
|
|
return this.#bytes.subarray(0, this.#length);
|
|
}
|
|
}
|
|
|
|
// throws when there's less left than what's read
|
|
export class Reader {
|
|
#bytes: Uint8Array;
|
|
#view: DataView;
|
|
#offset = 0;
|
|
// only old saves are big-endian
|
|
#little: boolean;
|
|
|
|
constructor(bytes: Uint8Array, little_endian = true) {
|
|
this.#bytes = bytes;
|
|
this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
this.#little = little_endian;
|
|
}
|
|
|
|
get done() {
|
|
return this.#offset === this.#bytes.length;
|
|
}
|
|
|
|
#take(size: number) {
|
|
if (this.#offset + size > this.#bytes.length) throw new Error("Too short");
|
|
const offset = this.#offset;
|
|
this.#offset += size;
|
|
return offset;
|
|
}
|
|
|
|
u8() {
|
|
return this.#bytes[this.#take(1)];
|
|
}
|
|
|
|
u16() {
|
|
return this.#view.getUint16(this.#take(2), this.#little);
|
|
}
|
|
|
|
i16() {
|
|
return this.#view.getInt16(this.#take(2), this.#little);
|
|
}
|
|
|
|
u32() {
|
|
return this.#view.getUint32(this.#take(4), this.#little);
|
|
}
|
|
|
|
string() {
|
|
const length = this.u8();
|
|
const offset = this.#take(length);
|
|
return new TextDecoder().decode(this.#bytes.subarray(offset, offset + length));
|
|
}
|
|
|
|
// the next size bytes, not copied
|
|
take(size: number) {
|
|
const offset = this.#take(size);
|
|
return this.#bytes.subarray(offset, offset + size);
|
|
}
|
|
}
|