libretrodb
Version:
A small reader for RetroArch databases
75 lines (74 loc) • 2.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileHandler = exports.SEEK_MODE = void 0;
const fs_1 = require("fs");
/*
Note: the file is fully read in memory (on open) because it's really faster
than reading small piece on the hard-drive (and the db file is not that heavy)
At first, it was read on demand, and, for a 7MB file, it took 33s versus 2s like this,
on a Macbook with SSD.
*/
var SEEK_MODE;
(function (SEEK_MODE) {
SEEK_MODE[SEEK_MODE["SEEK_SET"] = 0] = "SEEK_SET";
SEEK_MODE[SEEK_MODE["SEEK_CUR"] = 1] = "SEEK_CUR";
SEEK_MODE[SEEK_MODE["SEEK_END"] = 2] = "SEEK_END";
})(SEEK_MODE = exports.SEEK_MODE || (exports.SEEK_MODE = {}));
class FileHandler {
constructor(path) {
this.path = path;
this.pos = 0;
this.buffer = null;
}
async load() {
this.buffer = await fs_1.promises.readFile(this.path);
}
free() {
this.buffer = null;
}
seek(pos, whence = SEEK_MODE.SEEK_CUR) {
if (!this.buffer) {
throw new Error('null buffer');
}
if (whence === SEEK_MODE.SEEK_CUR) {
this.pos += pos;
}
else if (whence === SEEK_MODE.SEEK_SET) {
this.pos = pos;
}
else {
this.pos = this.buffer.length - pos;
}
this.pos = Math.max(0, this.pos);
this.pos = Math.min(this.pos, this.buffer.length);
}
tell() {
return this.pos;
}
read(len) {
const pos = this.pos;
if (!this.buffer) {
throw new Error('null buffer');
}
if (pos + len > this.buffer.length) {
throw new Error(`fail to read ${len} bytes (missing ${pos + len - this.buffer.length})`);
}
this.pos += len;
return this.buffer.slice(pos, pos + len);
}
readUInt64() {
return this.read(8).readBigUInt64BE();
}
readUInt(len = 1) {
const buffer = this.read(len);
return len < 7 ? buffer.readUIntBE(0, len) : Number(buffer.readBigUInt64BE());
}
readInt(len = 1) {
const buffer = this.read(len);
return len < 7 ? buffer.readIntBE(0, len) : Number(buffer.readBigInt64BE());
}
readString(len = 1) {
return this.read(len).toString();
}
}
exports.FileHandler = FileHandler;