UNPKG

@ankhzet/goo

Version:

Elegoo .goo file format reader/writer

81 lines (80 loc) 2.25 kB
export class BinaryWriter { constructor(chunk) { this.chunk = chunk; this.position = 0; this.buffer = Buffer.alloc(chunk); } get space() { return this.chunk - this.position; } *flush() { if (!this.position) { return; } yield this.buffer.subarray(0, this.position); this.position = 0; this.buffer = Buffer.alloc(this.chunk); } *binary(data) { const buf = Buffer.from(data); let rest = buf.length; let offset = 0; while (rest > 0) { const amount = Math.min(this.chunk - this.position, rest); buf.copy(this.buffer, this.position, offset, amount); this.position += amount; offset += amount; rest -= amount; if (this.chunk - this.position <= 0) { yield* this.flush(); } } } *bool(value) { if (this.space < 1) { yield* this.flush(); } this.buffer.writeUint8(+value, this.position); this.position += 1; } *u8(value) { if (this.space < 1) { yield* this.flush(); } this.buffer.writeUint8(value & 0xFF, this.position); this.position += 1; } *u16(value) { if (this.space < 2) { yield* this.flush(); } this.buffer.writeUint16BE(value & 0xFFFF, this.position); this.position += 2; } *u24(value) { if (this.space < 3) { yield* this.flush(); } this.buffer.writeUInt16BE((value >> 8) & 0xFFFF, this.position); this.buffer.writeUInt8(value & 0xFF, this.position + 2); this.position += 3; } *u32(value) { if (this.space < 4) { yield* this.flush(); } this.buffer.writeUInt32BE(value & 0xFFFFFFFF, this.position); this.position += 4; } *f32(value) { if (this.space < 4) { yield* this.flush(); } this.buffer.writeFloatBE(value, this.position); this.position += 4; } *string(data, length) { yield* this.flush(); yield Buffer.alloc(length, data.padEnd(length, '\u0000')); } }