biner
Version:
Declarative binary data encoder / decoder.
105 lines • 3.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../util");
const errors_1 = require("../errors");
const bs_1 = require("../bs");
function buffer(length) {
const isnum = util_1.isNumber(length);
const istype = util_1.isType(length);
const isfunc = util_1.isFunction(length);
const isnull = util_1.isNull(length);
if (!isnum && !istype && !isfunc && !isnull) {
throw new TypeError('Unknown type of argument #1.');
}
return {
encode,
decode,
encodingLength,
};
function encode(buf, wstream) {
checkBuffer(buf);
let bytes = 0;
const context = this;
if (isnum) {
checkLength(length, buf.length);
}
if (util_1.isType(length)) {
const b = length.encode.call(context, buf.length, wstream);
bytes += b;
}
if (util_1.isFunction(length)) {
const expectedLength = length(context);
checkLengthType(expectedLength);
checkLength(expectedLength, buf.length);
}
wstream.writeBuffer(Buffer.isBuffer(buf) ? buf : buf.buffer);
bytes += buf.length;
if (isnull) {
wstream.writeUInt8(0);
bytes += 1;
}
return bytes;
}
function decode(rstream) {
let size = 0;
let bytes = 0;
let count;
const context = this;
if (util_1.isNumber(length)) {
size = length;
}
else if (util_1.isType(length)) {
[size, count] = length.decode.call(context, rstream);
bytes += count;
checkLengthType(size);
}
else if (util_1.isFunction(length)) {
size = length(context);
checkLengthType(size);
}
else if (isnull) {
size = rstream.indexOf(0);
if (size === -1) {
throw new errors_1.NotEnoughDataError(rstream.length + 1, rstream.length);
}
}
const buf = rstream.readBuffer(size);
bytes += size;
if (isnull) {
bytes += 1;
rstream.consume(1);
}
return [buf, bytes];
}
function encodingLength(buf) {
checkBuffer(buf);
let size = 0;
if (util_1.isNumber(length)) {
return length;
}
if (util_1.isNull(length)) {
size = 1;
}
else if (util_1.isType(length)) {
size = length.encodingLength && length.encodingLength(buf.length);
}
return size + buf.length;
}
}
exports.buffer = buffer;
function checkBuffer(buf) {
if (!Buffer.isBuffer(buf) && !(buf instanceof bs_1.BinaryStream)) {
throw new TypeError('Argument 1 should be a Buffer or a BinaryStream.');
}
}
function checkLength(requiredSize, havingSize) {
if (requiredSize !== havingSize) {
throw new Error(`Buffer required length ${requiredSize} instead of ${havingSize}`);
}
}
function checkLengthType(length) {
if (typeof length !== 'number') {
throw new TypeError('Length of a buffer should be a number.');
}
}
//# sourceMappingURL=buffer.js.map