UNPKG

jspurefix

Version:
99 lines 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StringDuplex = exports.StringDuplexTraitsHelper = exports.StringDuplexTraits = void 0; const fix_duplex_1 = require("./fix-duplex"); const stream_1 = require("stream"); var StringDuplexTraits; (function (StringDuplexTraits) { StringDuplexTraits[StringDuplexTraits["None"] = 0] = "None"; StringDuplexTraits[StringDuplexTraits["Hunked"] = 1] = "Hunked"; StringDuplexTraits[StringDuplexTraits["Terminate"] = 2] = "Terminate"; StringDuplexTraits[StringDuplexTraits["All"] = 3] = "All"; })(StringDuplexTraits || (exports.StringDuplexTraits = StringDuplexTraits = {})); class StringDuplexTraitsHelper { static isTerminate(traits) { return (traits & StringDuplexTraits.Terminate) === StringDuplexTraits.Terminate; } static isHunked(traits) { return (traits & StringDuplexTraits.Hunked) === StringDuplexTraits.Hunked; } } exports.StringDuplexTraitsHelper = StringDuplexTraitsHelper; class StrHandler extends stream_1.Readable { constructor(txt, traits) { super(); this.txt = txt; this.traits = traits; this.pos = 0; this.remaining = txt.length; } isTerminate() { return StringDuplexTraitsHelper.isTerminate(this.traits); } isHunked() { return StringDuplexTraitsHelper.isHunked(this.traits); } sendHunk(slice) { this.push(slice); this.pos += slice.length; this.remaining -= slice.length; this.remaining = Math.max(0, this.remaining); if (this.isTerminate() && this.remaining === 0) { this.push(null); } } _read(n) { const len = this.txt.length; const pos = this.pos; const toSend = Math.min(n, len - pos); const slice = this.txt.slice(pos, pos + toSend); this.sendHunk(slice); } } class HunkedStrHandler extends StrHandler { constructor(txt, traits) { super(txt, traits); this.txt = txt; this.traits = traits; this.iteration = 0; } _read(n) { this.iteration++; const want = (this.iteration % 10) + 1; const chunk = Math.min(this.remaining, want); const snippet = this.txt.slice(this.pos, this.pos + chunk); this.sendHunk(snippet); } } class StringDuplex extends fix_duplex_1.FixDuplex { constructor(text = '', traits = StringDuplexTraits.Terminate) { super(); this.text = text; this.traits = traits; this.readable = StringDuplexTraitsHelper.isHunked(traits) ? new HunkedStrHandler(text, traits) : new StrHandler(text, traits); this.writable = StringDuplex.makeWritable(); } static makeWritable() { const Writable = require('stream').Writable; const writer = { write: (data, _, done) => { try { receiver.emit('data', data); done(); } catch (e) { done(e); } } }; const receiver = new Writable(writer); return receiver; } end() { this.readable.push(null); } } exports.StringDuplex = StringDuplex; //# sourceMappingURL=string-duplex.js.map