UNPKG

@andrew_l/tl-pack

Version:

Another implementation of binary serialization.

70 lines (67 loc) 1.87 kB
import { Transform } from 'node:stream'; import { B as BinaryWriter, C as CORE_TYPES, a as BinaryReader } from './shared/tl-pack.B8uBXdlJ.mjs'; import 'pako'; import '@andrew_l/toolkit'; class TLEncode extends Transform { writer; count; constructor(options) { const opts = options || {}; opts.streamOptions = { writableObjectMode: true, ...opts.streamOptions || {} }; super(opts.streamOptions); const writer = new BinaryWriter(options); const customFlush = opts.streamOptions.flush; const VECTOR_TYPES = new Uint8Array(2); VECTOR_TYPES[0] = CORE_TYPES.VectorDynamic; VECTOR_TYPES[1] = 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 Transform { reader; incompleteBuffer; constructor(options) { if (!options) options = {}; options.objectMode = true; super(options); this.incompleteBuffer = null; this.reader = new 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); } } } export { TLDecode, TLEncode }; //# sourceMappingURL=stream.mjs.map