biner
Version:
Declarative binary data encoder / decoder.
98 lines • 3.14 kB
JavaScript
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const bs_1 = require("./bs");
const array_1 = require("./types/array");
const buffer_1 = require("./types/buffer");
const bool_1 = require("./types/bool");
const reserved_1 = require("./types/reserved");
const string_1 = require("./types/string");
const numbers_1 = require("./types/numbers");
const when_1 = require("./types/when");
const select_1 = require("./types/select");
const encode_1 = require("./encode");
exports.encode = encode_1.encode;
const decode_1 = require("./decode");
exports.decode = decode_1.decode;
const encoding_length_1 = require("./encoding-length");
exports.encodingLength = encoding_length_1.encodingLength;
const transaction_1 = require("./transaction");
const errors_1 = require("./errors");
const types = Object.assign({}, numbers_1.numbers, { array: array_1.array,
bool: bool_1.bool,
buffer: buffer_1.buffer,
reserved: reserved_1.reserved,
string: string_1.string,
when: when_1.when,
select: select_1.select });
exports.types = types;
function createEncodeStream(schema) {
return new bs_1.BinaryStream({
readableObjectMode: false,
writableObjectMode: true,
transform: createTransformEncode(schema),
});
}
exports.createEncodeStream = createEncodeStream;
function createDecodeStream(bufOrSchema) {
let schema = undefined;
const isBuffer = Buffer.isBuffer(bufOrSchema);
if (bufOrSchema && !isBuffer) {
schema = bufOrSchema;
}
const stream = new bs_1.BinaryStream({
transform: createTransformDecode(schema),
readableObjectMode: true,
writableObjectMode: false,
});
if (isBuffer) {
stream.append(bufOrSchema);
}
return stream;
}
exports.createDecodeStream = createDecodeStream;
function createTransformEncode(schema) {
return function transformEncode(chunk, encoding, cb) {
try {
encode_1.encode(chunk, schema, this);
const buf = this.slice();
this.consume(buf.length);
cb(null, buf);
}
catch (error) {
cb(error);
}
};
}
function createTransformDecode(schema) {
return function (chunk, encoding, cb) {
this.append(chunk);
try {
while (this.length > 0) {
const transaction = new transaction_1.Transaction(this);
const data = decode_1.decode(transaction, schema);
transaction.commit();
this.push(data);
}
cb();
}
catch (error) {
if (error instanceof errors_1.NotEnoughDataError) {
cb();
}
else {
cb(error);
}
}
};
}
__export(require("./errors"));
__export(require("./transaction"));
__export(require("./bl"));
__export(require("./ll"));
__export(require("./bs"));
exports.createEncode = createEncodeStream;
exports.createDecode = createDecodeStream;
//# sourceMappingURL=index.js.map