Diffinery

homeflare/celldpublic

celld/crates/celld/js/text_encoding.js
280 lines · 11.8 KBRaw History
1// TextEncoder + TextDecoder (WHATWG Encoding).
2// Extracted module from the bootstrap.js IIFE.
3//
4// TextEncoder always emits UTF-8 (per spec). TextDecoder
5// decodes nothing itself: every label, utf-8 and utf-16
6// included, goes to encoding_rs on the host via the
7// $$textDecoder* ops, one call per decode() with native
8// streaming state per decoder. This file resolves the
9// label and owns the decoder's lifetime.
10//
11// Previous utf-8 and utf-16 hand-written JS decoders kept a
12// host call off a small `request.text()`, but measurement did
13// not support that design: the host was faster at every size
14// down to 16 bytes,
15// and what a JS decode cost depended on the decodes that
16// ran before it. A cell that decoded a few hundred small
17// or malformed bodies first spent 48ms per MiB on a bulk
18// decode, against 5ms for the same binary that decoded
19// one large body first. The order was the only
20// difference, the effect was sticky, and the ratio was
21// the ratio between V8's interpreter and its optimizing
22// tier. The mechanism was not traced further, so no claim
23// is made about which feedback caused it — but the
24// traffic that provoked it was ordinary, and no shape of
25// the JS decoder resisted it. Two decoders for one
26// encoding also owe a byte-for-byte equivalence proof,
27// and that debt had already shipped one bug: a utf-16
28// buffer ending in an unpaired lead surrogate and an odd
29// byte yielded two U+FFFD in JS and one on the host.
30(function () {
31 const _tdLabel = $$textDecoderLabel;
32 const _tdNew = $$textDecoderNew;
33 const _tdDecode = $$textDecoderDecode;
34 const _tdDecodeOnce = $$textDecoderDecodeOnce;
35 const _tdFree = $$textDecoderFree;
36 // Frees native decoders abandoned mid-stream. Ids
37 // are never reused, so a late free is a no-op.
38 // Created on the first stream, not at boot.
39 let _tdRegistry;
40 const _tdTrack = (target, id) => {
41 if (_tdRegistry === undefined) {
42 _tdRegistry =
43 typeof FinalizationRegistry === 'function'
44 ? new FinalizationRegistry(_tdFree)
45 : null;
46 }
47 _tdRegistry?.register(target, id);
48 };
49 globalThis.TextEncoder = class TextEncoder {
50 get encoding() { return 'utf-8'; }
51 encode(s = '') {
52 s = String(s);
53 const buf = new Uint8Array(s.length * 4);
54 let w = 0;
55 for (let i = 0; i < s.length; ) {
56 let c = s.charCodeAt(i);
57 if (c >= 0xD800 && c <= 0xDBFF &&
58 i + 1 < s.length) {
59 const trail = s.charCodeAt(i + 1);
60 if (trail >= 0xDC00 &&
61 trail <= 0xDFFF) {
62 c = ((c - 0xD800) << 10) +
63 (trail - 0xDC00) + 0x10000;
64 } else { c = 0xFFFD; }
65 } else if (c >= 0xD800 && c <= 0xDFFF) {
66 c = 0xFFFD;
67 }
68 if (c < 0x80) {
69 buf[w++] = c;
70 } else if (c < 0x800) {
71 buf[w++] = 0xc0 | (c >> 6);
72 buf[w++] = 0x80 | (c & 0x3f);
73 } else if (c < 0x10000) {
74 buf[w++] = 0xe0 | (c >> 12);
75 buf[w++] = 0x80 | ((c>>6) & 0x3f);
76 buf[w++] = 0x80 | (c & 0x3f);
77 } else {
78 buf[w++] = 0xf0 | (c >> 18);
79 buf[w++] = 0x80|((c>>12) & 0x3f);
80 buf[w++] = 0x80|((c>>6) & 0x3f);
81 buf[w++] = 0x80 | (c & 0x3f);
82 }
83 i += c > 0xffff ? 2 : 1;
84 }
85 // `slice`, not `subarray`: the scratch buffer is 4x the input
86 // length, and a subarray would hand the caller a view onto it.
87 // `encode(s).buffer` is a common idiom -- into crypto.subtle,
88 // into a Blob -- and with a shared buffer it carries up to 3x
89 // the bytes of trailing garbage.
90 return buf.slice(0, w);
91 }
92 encodeInto(source, destination) {
93 if (!(destination instanceof Uint8Array))
94 throw new TypeError(
95 'encodeInto requires Uint8Array');
96 source = String(source);
97 let read = 0, written = 0;
98 for (let i = 0; i < source.length; ) {
99 let c = source.charCodeAt(i);
100 // Handle surrogates
101 if (c >= 0xD800 && c <= 0xDBFF &&
102 i + 1 < source.length) {
103 const trail =
104 source.charCodeAt(i + 1);
105 if (trail >= 0xDC00 &&
106 trail <= 0xDFFF) {
107 c = ((c - 0xD800) << 10) +
108 (trail - 0xDC00) + 0x10000;
109 } else {
110 c = 0xFFFD; // lone surrogate
111 }
112 } else if (c >= 0xD800 && c <= 0xDFFF) {
113 c = 0xFFFD; // lone surrogate
114 }
115 let bytes;
116 if (c < 0x80) bytes = 1;
117 else if (c < 0x800) bytes = 2;
118 else if (c < 0x10000) bytes = 3;
119 else bytes = 4;
120 if (written + bytes > destination.length)
121 break;
122 if (bytes === 1) {
123 destination[written++] = c;
124 } else if (bytes === 2) {
125 destination[written++] =
126 0xc0 | (c >> 6);
127 destination[written++] =
128 0x80 | (c & 0x3f);
129 } else if (bytes === 3) {
130 destination[written++] =
131 0xe0 | (c >> 12);
132 destination[written++] =
133 0x80 | ((c >> 6) & 0x3f);
134 destination[written++] =
135 0x80 | (c & 0x3f);
136 } else {
137 destination[written++] =
138 0xf0 | (c >> 18);
139 destination[written++] =
140 0x80 | ((c >> 12) & 0x3f);
141 destination[written++] =
142 0x80 | ((c >> 6) & 0x3f);
143 destination[written++] =
144 0x80 | (c & 0x3f);
145 }
146 i += c > 0xffff ? 2 : 1;
147 read = i;
148 }
149 return { read, written };
150 }
151 };
152 globalThis.TextDecoder = class TextDecoder {
153 #encoding;
154 #fatal;
155 #ignoreBOM;
156 // Live native decoder id while a stream is in
157 // flight; undefined otherwise.
158 #nativeId;
159 constructor(label = 'utf-8', options = {}) {
160 // Per WHATWG encoding: strip ASCII whitespace
161 // only (not Unicode — \v, NBSP, etc. stay).
162 label = String(label)
163 .replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, '')
164 .toLowerCase();
165 // The WHATWG label set for utf-8 and utf-16, resolved here to
166 // keep a host call out of `new TextDecoder()` — which every
167 // `request.text()` makes. A miss (e.g. 'ansi_x3.4-1968',
168 // which the standard maps to windows-1252 rather than utf-8)
169 // resolves through the host's encoding_rs label table
170 // instead. Both answers are encoding_rs labels, so the
171 // decode itself does not care which way the name arrived.
172 const aliases = {
173 'utf-8': 'utf-8', 'utf8': 'utf-8',
174 'unicode-1-1-utf-8': 'utf-8',
175 'unicode11utf8': 'utf-8',
176 'unicode20utf8': 'utf-8',
177 'x-unicode20utf8': 'utf-8',
178 'utf-16le': 'utf-16le',
179 'utf-16': 'utf-16le',
180 'ucs-2': 'utf-16le',
181 'unicode': 'utf-16le',
182 'unicodefeff': 'utf-16le',
183 'iso-10646-ucs-2': 'utf-16le',
184 'csunicode': 'utf-16le',
185 'utf-16be': 'utf-16be',
186 'unicodefffe': 'utf-16be',
187 };
188 let enc = aliases[label];
189 if (!enc) {
190 // undefined covers unknown labels and the replacement
191 // encoding — both RangeError per spec. A resolved name
192 // is canonical lowercase, and the alias lookup then
193 // normalizes the utf names to the spelling above.
194 const name = _tdLabel(label);
195 if (name === undefined) throw new RangeError(
196 `The encoding label` +
197 ` '${label}' is invalid.`
198 );
199 enc = aliases[name] ?? name;
200 }
201 this.#encoding = enc;
202 this.#fatal = !!options.fatal;
203 this.#ignoreBOM = !!options.ignoreBOM;
204 }
205 get encoding() { return this.#encoding; }
206 get fatal() { return this.#fatal; }
207 get ignoreBOM() { return this.#ignoreBOM; }
208 decode(input, options = {}) {
209 const stream = !!options.stream;
210 let b;
211 if (input == null) {
212 b = new Uint8Array(0);
213 } else if (input instanceof ArrayBuffer) {
214 b = new Uint8Array(input);
215 } else if (ArrayBuffer.isView(input)) {
216 // BufferSource (TypedArray / DataView).
217 // Slice the underlying buffer at the
218 // view's offset / length so we honour
219 // sub-views.
220 b = new Uint8Array(
221 input.buffer,
222 input.byteOffset,
223 input.byteLength,
224 );
225 } else {
226 // Per Web IDL: `decode(input)` accepts
227 // [AllowShared] BufferSource. Anything
228 // else is a type-coercion error. Pre-fix
229 // the fallback `new Uint8Array(input, 0,
230 // input.length)` interpreted a number as
231 // a length-N allocation of zero bytes —
232 // `.decode(42)` returned 42 NUL chars,
233 // `.decode("hello")` returned "" (no
234 // .length on a string maps to a 0-length
235 // buffer view), both spec-violating.
236 throw new TypeError(
237 "TextDecoder.decode: input must be"
238 + " a BufferSource",
239 );
240 }
241 return this._decodeNative(b, stream);
242 }
243 // One op per decode(), for every label. Streaming state (a split
244 // multibyte sequence, a BOM, ISO-2022-JP mode) lives in the
245 // native decoder; a fatal error frees it, matching Workerd — the
246 // next decode starts clean.
247 _decodeNative(b, stream) {
248 let id = this.#nativeId;
249 // A complete buffer with no stream around it
250 // needs no decoder that outlives the call, so
251 // it takes the one-shot op and never reaches
252 // the host's decoder table.
253 if (id === undefined && !stream) {
254 return _tdDecodeOnce(
255 this.#encoding, b, this.#fatal,
256 this.#ignoreBOM);
257 }
258 if (id === undefined) {
259 id = _tdNew(this.#encoding, this.#ignoreBOM);
260 this.#nativeId = id;
261 _tdTrack(this, id);
262 } else if (!stream) {
263 this.#nativeId = undefined;
264 }
265 try {
266 return _tdDecode(id, b, this.#fatal, !stream);
267 } catch (e) {
268 this.#nativeId = undefined;
269 throw e;
270 }
271 }
272 };
273 // Web IDL toStringTag.
274 Object.defineProperty(globalThis.TextEncoder.prototype,
275 Symbol.toStringTag,
276 { value: 'TextEncoder', configurable: true });
277 Object.defineProperty(globalThis.TextDecoder.prototype,
278 Symbol.toStringTag,
279 { value: 'TextDecoder', configurable: true });
280})();