biner
Version:
Declarative binary data encoder / decoder.
65 lines • 2.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../util");
const symbols = require("../internal/symbols");
const decode_1 = require("../decode");
const encode_1 = require("../encode");
const encoding_length_1 = require("../encoding-length");
const meta_1 = require("../internal/meta");
function when(condition, type) {
if (!util_1.isType(type) && !util_1.isUserType(type)) {
throw new TypeError('Argument #2 should be a valid type.');
}
const result = {
encode,
decode,
encodingLength,
[symbols.skip]: false,
};
return result;
function encode(value, wstream) {
const context = meta_1.Metadata.clone(this);
let bytes = 0;
const status = util_1.isFunction(condition)
? Boolean(condition(context))
: Boolean(condition);
result[symbols.skip] = !status;
if (!status) {
meta_1.Metadata.clean(context);
return bytes;
}
encode_1.encodeCommon(value, wstream, type, context);
bytes = context.bytes;
meta_1.Metadata.clean(context);
return bytes;
}
function decode(rstream) {
const context = meta_1.Metadata.clone(this);
let bytes = 0;
const status = util_1.isFunction(condition)
? Boolean(condition(context))
: Boolean(condition);
result[symbols.skip] = !status;
if (!status) {
meta_1.Metadata.clean(context);
return [undefined, bytes];
}
const value = decode_1.decodeCommon(rstream, type, context);
bytes = context.bytes;
meta_1.Metadata.clean(context);
return [value, bytes];
}
function encodingLength(value) {
const context = meta_1.Metadata.clone(this);
const status = util_1.isFunction(condition)
? Boolean(condition(context))
: Boolean(condition);
if (status) {
encoding_length_1.encodingLengthCommon(value, type, context);
}
meta_1.Metadata.clean(context);
return context.bytes;
}
}
exports.when = when;
//# sourceMappingURL=when.js.map