@geckos.io/typed-array-buffer-schema
Version:
A Schema based Object to Buffer converter
45 lines • 1.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lib = void 0;
const deep_sort_object_1 = require("./deep-sort-object");
const schema_1 = require("./schema");
class Lib {
static newHash(name, _struct) {
// https://stackoverflow.com/a/7616484/12656855
const strToHash = (s) => {
let hash = 0;
for (let i = 0; i < s.length; i++) {
const chr = s.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
hash *= 254785; // times a random number
return Math.abs(hash).toString(32).slice(2, 6);
};
let hash = strToHash(JSON.stringify(_struct) + name);
if (hash.length !== 4)
throw new Error('Hash has not length of 4');
return `#${hash}`;
}
static schema(name, _struct) {
_struct = (0, deep_sort_object_1.deepSortObject)(_struct);
const id = Lib.newHash(name, _struct);
const s = new schema_1.Schema(id, name, _struct);
this._schemas.set(id, s);
return s;
}
}
exports.Lib = Lib;
Lib._schemas = new Map();
Lib.getIdFromBuffer = (buffer) => {
const dataView = new DataView(buffer);
let id = '';
for (let i = 0; i < 5; i++) {
const uInt8 = dataView.getUint8(i);
id += String.fromCharCode(uInt8);
}
return id;
};
Lib.getIdFromSchema = (schema) => schema.id;
Lib.getIdFromModel = (model) => model.schema.id;
//# sourceMappingURL=lib.js.map