Diffinery

homeflare/celldpublic

celld/crates/celld/js/text_encoding_streams.js
54 lines · 1.6 KBRaw History
1// TextEncoderStream / TextDecoderStream. TextDecoderStream keeps decoder
2// state across chunks so split
3// multi-byte sequences are decoded correctly, then flushes at end-of-stream.
4globalThis.TextEncoderStream = class TextEncoderStream
5 extends TransformStream {
6 constructor() {
7 const enc = new TextEncoder();
8 let pending = '';
9 super({
10 transform(chunk, controller) {
11 let s = pending + String(chunk);
12 pending = '';
13 if (s.length > 0) {
14 const last = s.charCodeAt(s.length - 1);
15 if (last >= 0xD800 && last <= 0xDBFF) {
16 pending = s[s.length - 1];
17 s = s.slice(0, -1);
18 }
19 }
20 if (s.length === 0) return;
21 controller.enqueue(enc.encode(s));
22 },
23 flush(controller) {
24 if (pending) controller.enqueue(enc.encode(pending));
25 },
26 });
27 }
28 get encoding() { return 'utf-8'; }
29};
30
31globalThis.TextDecoderStream = class TextDecoderStream
32 extends TransformStream {
33 #dec;
34 constructor(label = 'utf-8', options = {}) {
35 const dec = new TextDecoder(label, options);
36 super({
37 transform(chunk, controller) {
38 if (!(chunk instanceof ArrayBuffer)
39 && !ArrayBuffer.isView(chunk))
40 throw new TypeError("Chunk must be BufferSource");
41 const s = dec.decode(chunk, { stream: true });
42 if (s) controller.enqueue(s);
43 },
44 flush(controller) {
45 const s = dec.decode();
46 if (s) controller.enqueue(s);
47 },
48 });
49 this.#dec = dec;
50 }
51 get encoding() { return this.#dec.encoding; }
52 get fatal() { return this.#dec.fatal; }
53 get ignoreBOM() { return this.#dec.ignoreBOM; }
54};