biner
Version:
Declarative binary data encoder / decoder.
53 lines • 1.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("./util");
const symbols = require("./internal/symbols");
const meta_1 = require("./internal/meta");
const bs_1 = require("./bs");
function encode(obj, type, target) {
const meta = new meta_1.Metadata();
target = target || new bs_1.BinaryStream();
encodeCommon(obj, target, type, meta);
meta_1.Metadata.clean(meta);
return [target, meta.bytes];
}
exports.encode = encode;
function encodeCommon(object, wstream, typeOrSchema, context) {
if (util_1.isType(typeOrSchema)) {
const bytes = typeOrSchema.encode.call(context, object, wstream);
context[symbols.bytes] += bytes;
}
else {
encodeSchema(object, wstream, typeOrSchema, context);
}
}
exports.encodeCommon = encodeCommon;
function encodeSchema(object, wstream, schema, context) {
assertSchema(schema);
if (context.node === undefined) {
context.node = object;
context.current = object;
}
else {
context.current = object;
}
const keys = Object.keys(schema);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
const type = schema[key];
const value = object[key];
if (!util_1.isEncodeType(type)) {
encodeSchema(value, wstream, type, context);
context.current = object;
continue;
}
const bytes = type.encode.call(context, value, wstream);
context[symbols.bytes] += bytes;
}
}
function assertSchema(schema) {
if (!util_1.isUserType(schema)) {
throw new TypeError('Argument `schema` should be a plain object.');
}
}
//# sourceMappingURL=encode.js.map