@ankhzet/goo
Version:
Elegoo .goo file format reader/writer
91 lines (90 loc) • 3.42 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { assert } from './utils.js';
export class BinaryReader {
constructor(readable) {
this.buffers = {};
this.readable = readable;
}
buffer(size) {
let got = this.buffers[size];
if (!got) {
got = Buffer.alloc(size);
this.buffers[size] = got;
}
return got;
}
assert(data, message) {
return __awaiter(this, void 0, void 0, function* () {
const { buffer, bytesRead } = yield this.binary(data.length);
assert((bytesRead === data.length) && !buffer.compare(data), message);
});
}
skip(count) {
return __awaiter(this, void 0, void 0, function* () {
return this.readable.read(this.buffer(count), 0, count).then(({ bytesRead }) => bytesRead);
});
}
binary(count) {
return __awaiter(this, void 0, void 0, function* () {
return this.readable.read(this.buffer(count), 0, count, null);
});
}
bool() {
return __awaiter(this, void 0, void 0, function* () {
return this.binary(1).then(({ buffer }) => !!buffer.readUint8());
});
}
u8() {
return __awaiter(this, void 0, void 0, function* () {
return this.binary(1).then(({ buffer }) => buffer.readUint8());
});
}
u16() {
return __awaiter(this, void 0, void 0, function* () {
return this.binary(2).then(({ buffer }) => buffer.readUint16BE());
});
}
u24() {
return __awaiter(this, void 0, void 0, function* () {
return this.binary(3).then(({ buffer }) => {
const b16 = buffer.readUint16BE();
const b8 = buffer.readUint8(2);
return (b16 << 8) | b8;
});
});
}
u32() {
return __awaiter(this, void 0, void 0, function* () {
return this.binary(4).then(({ buffer }) => buffer.readUint32BE());
});
}
f32() {
return __awaiter(this, void 0, void 0, function* () {
return this.binary(4).then(({ buffer }) => buffer.readFloatBE());
});
}
string(length) {
return __awaiter(this, void 0, void 0, function* () {
return this.binary(length).then(({ buffer }) => {
const terminatorIndex = buffer.indexOf(0);
return buffer.toString('utf8', 0, terminatorIndex >= 0 ? terminatorIndex : length);
});
});
}
struct(target, map) {
return __awaiter(this, void 0, void 0, function* () {
for (const [key, reader] of Object.entries(map)) {
target[key] = yield reader();
}
return target;
});
}
}