moeralib
Version:
Library to interact with Moera decentralized social network
87 lines (86 loc) • 2.26 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FingerprintWriter = void 0;
class FingerprintWriter {
constructor() {
this.data = [];
}
appendNull() {
this.data.push(0xff);
}
appendString(str) {
if (str == null) {
this.appendNull();
return;
}
const buf = Buffer.from(str);
this.appendNumber(buf.length);
this.data.push(...buf.values());
}
appendBoolean(b) {
this.data.push(b ? 1 : 0);
}
appendNumber(l) {
let len;
if (l < 0xfc) {
len = 1;
}
else if (l <= 0xffff) {
this.data.push(0xfc);
len = 2;
}
else if (l <= 0xffffffff) {
this.data.push(0xfd);
len = 4;
}
else {
this.data.push(0xfe);
len = 8;
}
for (let i = 0; i < len; i++) {
this.data.push(l & 0xff);
l = l >> 8;
}
}
appendBytes(b) {
this.appendNumber(b.length);
this.data.push(...b.values());
}
appendFingerprint(fingerprint, schema) {
for (const field of schema) {
this.append(fingerprint[field[0]], field[1]);
}
}
appendList(list, type) {
const writer = new FingerprintWriter();
list.forEach(value => writer.append(value, type));
this.appendBytes(writer.toBytes());
}
append(value, type) {
if (value == null) {
this.appendNull();
}
else if (Array.isArray(type)) {
this.appendFingerprint(value, type);
}
else if (type.endsWith("[]")) {
this.appendList(value, type.substring(0, type.length - 2));
}
else if (type === "string") {
this.appendString(value);
}
else if (type === "boolean") {
this.appendBoolean(value);
}
else if (type === "number") {
this.appendNumber(value);
}
else if (type === "bytes") {
this.appendBytes(value);
}
}
toBytes() {
return Buffer.from(this.data);
}
}
exports.FingerprintWriter = FingerprintWriter;