@andrew_l/tl-pack
Version:
Another implementation of binary serialization.
73 lines (69 loc) • 1.95 kB
JavaScript
'use strict';
const node_stream = require('node:stream');
const BinaryReader = require('./shared/tl-pack.5CF-VZgL.cjs');
require('pako');
require('@andrew_l/toolkit');
class TLEncode extends node_stream.Transform {
writer;
count;
constructor(options) {
const opts = options || {};
opts.streamOptions = {
writableObjectMode: true,
...opts.streamOptions || {}
};
super(opts.streamOptions);
const writer = new BinaryReader.BinaryWriter(options);
const customFlush = opts.streamOptions.flush;
const VECTOR_TYPES = new Uint8Array(2);
VECTOR_TYPES[0] = BinaryReader.CORE_TYPES.VectorDynamic;
VECTOR_TYPES[1] = BinaryReader.CORE_TYPES.None;
this.push(VECTOR_TYPES.subarray(0, 1));
this._flush = (callback) => {
this.push(VECTOR_TYPES.subarray(1, 2));
if (customFlush) {
customFlush.call(this, callback);
} else {
callback();
}
};
this.writer = writer;
this.count = 0;
}
_transform(chunk, encoding, callback) {
const buff = this.writer.encode(chunk);
this.push(buff);
this.count++;
callback();
}
}
class TLDecode extends node_stream.Transform {
reader;
incompleteBuffer;
constructor(options) {
if (!options) options = {};
options.objectMode = true;
super(options);
this.incompleteBuffer = null;
this.reader = new BinaryReader.BinaryReader(new Uint8Array(8192));
}
_transform(chunk, encoding, callback) {
if (this.incompleteBuffer) {
chunk = Buffer.concat([this.incompleteBuffer, chunk]);
this.incompleteBuffer = null;
}
try {
const value = this.reader.decode(chunk);
return callback(null, value);
} catch (err) {
if (err?.incomplete) {
this.incompleteBuffer = chunk;
return callback();
}
return callback(err);
}
}
}
exports.TLDecode = TLDecode;
exports.TLEncode = TLEncode;
//# sourceMappingURL=stream.cjs.map