Skip to main content

nodejs/stdlib/
typedarray.rs

1//! JavaScript typed arrays (`Uint8Array`/`Int8Array`/…/`Float64Array`),
2//! `ArrayBuffer`, `WeakRef`, and `TextEncoder`/`TextDecoder`.
3//!
4//! A typed array is a plain object tagged `@@native = "TypedArray"` carrying its
5//! kind (`@@kind`), a window (`@@buffer`/`byteOffset`/`length`) onto the bytes
6//! its `ArrayBuffer` owns, and the
7//! enumerable `length`/`byteLength`/`BYTES_PER_ELEMENT` data properties JS code
8//! reads directly. Element indexing (`ta[i]` get/set) is special-cased in
9//! `builtins::get_property`/`set_property` via `elem_get`/`elem_set` here, which
10//! also apply each kind's coercion (integer wrap / clamp / float).
11//!
12//! `WeakRef` holds a *strong* reference (`deref()` always returns the target) —
13//! node-js has no GC of JS objects, so this is observably correct for the
14//! express dependency tree (object-inspect/qs/side-channel only ever `deref()`).
15
16use crate::host::{fmt_number, with_host, JsObj};
17use fusevm::Value;
18use indexmap::IndexMap;
19
20pub const STATIC_METHODS: &[&str] = &["from", "of", "isView"];
21
22/// `Uint8Array`'s statics — the shared three plus the base64/hex pair, which no
23/// other view has.
24pub const UINT8_STATIC_METHODS: &[&str] = &["from", "of", "isView", "fromBase64", "fromHex"];
25
26/// The four base64/hex methods `Uint8Array.prototype` owns on its own.
27/// In the engine's own order, which `Object.getOwnPropertyNames` reports.
28pub const UINT8_PROTOTYPE_METHODS: &[&str] = &["toBase64", "setFromBase64", "toHex", "setFromHex"];
29
30/// The statics `<kind>` advertises.
31pub fn static_methods(kind: &str) -> &'static [&'static str] {
32    if kind == "Uint8Array" {
33        UINT8_STATIC_METHODS
34    } else {
35        STATIC_METHODS
36    }
37}
38
39/// The methods installed on the real `Uint8Array.prototype` object (as
40/// `@proto:Uint8Array:<m>` thunks), so `Uint8Array.prototype.slice.call(x)`
41/// keeps working now that the prototype is an object rather than a `Builtin`
42/// namespace whose every property read synthesized a thunk.
43pub const PROTOTYPE_METHODS: &[&str] = &[
44    "at",
45    "copyWithin",
46    "entries",
47    "every",
48    "fill",
49    "filter",
50    "find",
51    "findIndex",
52    "findLast",
53    "findLastIndex",
54    "forEach",
55    "includes",
56    "indexOf",
57    "join",
58    "keys",
59    "lastIndexOf",
60    "map",
61    "reduce",
62    "reduceRight",
63    "reverse",
64    "set",
65    "slice",
66    "some",
67    "sort",
68    "subarray",
69    "toReversed",
70    "toSorted",
71    "toString",
72    "values",
73    "with",
74];
75
76/// The eleven element kinds plus the two buffer types.
77pub fn is_ctor(name: &str) -> bool {
78    ELEMENT_KINDS.contains(&name) || matches!(name, "ArrayBuffer" | "DataView")
79}
80
81/// The element kinds, each of which gets its own real prototype object whose
82/// parent is the shared `%TypedArray%.prototype`. `Uint8Array` leads because
83/// `Buffer.prototype` chains onto it.
84///
85/// `BigInt64Array`/`BigUint64Array` are here too, and they are not
86/// interchangeable with the rest: their elements are BigInts, so a Number
87/// written into one is a `TypeError` and a `Number`-kind view will not accept
88/// one either (`coerce_val`).
89pub const ELEMENT_KINDS: &[&str] = &[
90    "Uint8Array",
91    "Int8Array",
92    "Uint8ClampedArray",
93    "Int16Array",
94    "Uint16Array",
95    "Int32Array",
96    "Uint32Array",
97    "Float32Array",
98    "Float64Array",
99    // The 64-bit views store BigInt elements rather than Numbers.
100    "BigInt64Array",
101    "BigUint64Array",
102];
103
104/// Bytes per element for a typed-array kind.
105pub fn bytes_per_element(kind: &str) -> usize {
106    match kind {
107        "Int8Array" | "Uint8Array" | "Uint8ClampedArray" => 1,
108        "Int16Array" | "Uint16Array" => 2,
109        "Int32Array" | "Uint32Array" | "Float32Array" => 4,
110        "Float64Array" | "BigInt64Array" | "BigUint64Array" => 8,
111        _ => 1,
112    }
113}
114
115/// Coerce a JS number into the value stored for `kind` (integer wrap, unsigned
116/// clamp, or float), mirroring the `ToInt8`/`ToUint8Clamp`/… abstract ops.
117fn coerce(kind: &str, n: f64) -> f64 {
118    // `ToInt8` … `ToUint32` (7.1.6-7.1.11) all reduce `n` modulo 2^32 first, and
119    // a non-finite number is 0 — `n as i64` saturates instead, which made
120    // `new Int8Array([Infinity])` hold -1 and `new Uint8Array([Infinity])` 255.
121    let wrapped = if n.is_finite() {
122        n.trunc().rem_euclid(4_294_967_296.0) as u32
123    } else {
124        0
125    };
126    match kind {
127        "Int8Array" => (wrapped as u8 as i8) as f64,
128        "Uint8Array" => (wrapped as u8) as f64,
129        "Uint8ClampedArray" => {
130            if n.is_nan() {
131                0.0
132            } else {
133                // ToUint8Clamp rounds a tie to the EVEN neighbour: 2.5 is 2, 3.5 is 4.
134                n.clamp(0.0, 255.0).round_ties_even()
135            }
136        }
137        "Int16Array" => (wrapped as u16 as i16) as f64,
138        "Uint16Array" => (wrapped as u16) as f64,
139        "Int32Array" => (wrapped as i32) as f64,
140        "Uint32Array" => wrapped as f64,
141        "Float32Array" => n as f32 as f64,
142        _ => n, // Float64Array
143    }
144}
145
146/// Whether `kind` stores BigInt elements rather than Numbers. The two 64-bit
147/// views are the only ones: their elements do not fit an `f64` without loss, so
148/// the whole element pipeline carries `Value` rather than `f64`.
149pub fn is_bigint_kind(kind: &str) -> bool {
150    matches!(kind, "BigInt64Array" | "BigUint64Array")
151}
152
153/// Coerce a JS value into the element `kind` stores. The numeric kinds go
154/// through the `ToInt8`/`ToUint8Clamp`/… abstract ops as before; the 64-bit ones
155/// wrap through `ToBigInt64`/`ToBigUint64` and keep a BigInt.
156fn coerce_val(kind: &str, v: &Value) -> Result<Value, String> {
157    if !is_bigint_kind(kind) {
158        return Ok(Value::Float(coerce(kind, crate::host::to_number_value(v)?)));
159    }
160    // 7.1.15/7.1.16 route through `ToBigInt`, which is not "must already be a
161    // BigInt": a boolean, a string and any object that converts to one are all
162    // accepted (`a[0] = '12'` stores `12n`), and only a Number is refused. The
163    // check here was the identity test, so it rejected every one of those and
164    // reported the same wrong text — node names the value it could not convert.
165    let big = crate::builtins::to_bigint(v)?;
166    Ok(with_host(|h| h.new_bigint(wrap_bigint(kind, big))))
167}
168
169/// `ToBigInt64` / `ToBigUint64` — wrap modulo 2^64 into the signed or unsigned
170/// 64-bit range, which is what a 64-bit view stores.
171fn wrap_bigint(kind: &str, b: num_bigint::BigInt) -> num_bigint::BigInt {
172    use num_traits::cast::ToPrimitive;
173    let modulus = num_bigint::BigInt::from(1u128 << 64);
174    let mut m = b % &modulus;
175    if m.sign() == num_bigint::Sign::Minus {
176        m += &modulus;
177    }
178    // `m` is now in [0, 2^64); reinterpret it for the view's signedness.
179    let raw = m.to_u64().unwrap_or(0);
180    if kind == "BigInt64Array" {
181        num_bigint::BigInt::from(raw as i64)
182    } else {
183        num_bigint::BigInt::from(raw)
184    }
185}
186
187/// An element's BigInt, for ordering a 64-bit view. Zero for anything else,
188/// which the numeric kinds never ask for.
189fn bigint_of(v: &Value) -> num_bigint::BigInt {
190    with_host(|h| match h.get(v) {
191        Some(JsObj::BigInt(b)) => b.clone(),
192        _ => num_bigint::BigInt::from(0),
193    })
194}
195
196/// `indexOf`/`lastIndexOf`/`includes` element comparison. 23.2.3.x compare the
197/// search element with the STORED one and do not coerce it, so a string never
198/// matches a numeric element and a Number never matches a BigInt one.
199///
200/// `includes` differs from `indexOf` only in treating `NaN` as present
201/// (SameValueZero vs strict equality), which `nan_matches` selects: node reports
202/// `new Float64Array([NaN]).includes(NaN)` as true and `.indexOf(NaN)` as -1.
203fn same_element(stored: &Value, needle: &Value, nan_matches: bool) -> bool {
204    if nan_matches {
205        if let (Value::Float(a), Value::Float(b)) = (stored, needle) {
206            if a.is_nan() && b.is_nan() {
207                return true;
208            }
209        }
210    }
211    with_host(|h| h.strict_eq(stored, needle))
212}
213
214/// The zero element of `kind` — what a freshly allocated view is filled with.
215fn zero_of(kind: &str) -> Value {
216    if is_bigint_kind(kind) {
217        with_host(|h| h.new_bigint(num_bigint::BigInt::from(0)))
218    } else {
219        Value::Float(0.0)
220    }
221}
222
223/// An element as an `f64`, for the numeric-kind comparisons (`sort`'s default
224/// order, `indexOf`). A BigInt element answers its nearest `f64`, which is only
225/// ever used where the kind is numeric.
226fn num(v: &Value) -> f64 {
227    with_host(|h| h.to_number(v))
228}
229
230/// The element values of a typed array / Buffer as stored — `Value`, not `f64`,
231/// so a 64-bit view keeps its BigInts. `elems_of` is the numeric view of the
232/// same data and stays, because `Buffer` reads bytes through it.
233pub fn elem_values(v: &Value) -> Vec<Value> {
234    let Some(tag) = super::native_tag(v) else {
235        return Vec::new();
236    };
237    if tag == "TypedArray" {
238        let kind = kind_of(v);
239        let bpe = bytes_per_element(&kind);
240        return (0..view_len(v))
241            .map(|i| {
242                view_bytes(v, i * bpe, bpe)
243                    .map(|b| decode(&kind, &b))
244                    .unwrap_or(Value::Undef)
245            })
246            .collect();
247    }
248    if tag != "Buffer" {
249        return Vec::new();
250    }
251    with_host(|h| match h.get(v) {
252        Some(JsObj::Object(p)) => super::buffer::window_bytes_h(h, p)
253            .into_iter()
254            .map(|b| Value::Float(b as f64))
255            .collect(),
256        _ => Vec::new(),
257    })
258}
259
260/// Build a typed array of `kind` from already-coerced element values.
261fn make(kind: &str, elems: Vec<Value>) -> Value {
262    let bpe = bytes_per_element(kind);
263    let len = elems.len();
264    let buf = new_array_buffer(len * bpe);
265    let view = make_view(kind, &buf, 0, len);
266    for (i, e) in elems.iter().enumerate() {
267        write_view_bytes(&view, i * bpe, &encode(kind, e));
268    }
269    view
270}
271
272/// A typed array of `kind` over `buf`, `len` elements from `byte_off`.
273fn make_view(kind: &str, buf: &Value, byte_off: usize, len: usize) -> Value {
274    with_host(|h| {
275        let bpe = bytes_per_element(kind);
276        let mut m = IndexMap::new();
277        m.insert("@@native".into(), h.new_str("TypedArray"));
278        m.insert("@@kind".into(), h.new_str(kind));
279        m.insert("@@buffer".into(), buf.clone());
280        // `ta.buffer` is a non-enumerable accessor in node; a hidden own slot
281        // reads identically and keeps it out of `Object.keys` and `inspect`.
282        m.insert("buffer".into(), buf.clone());
283        m.insert("length".into(), Value::Float(len as f64));
284        m.insert("byteLength".into(), Value::Float((len * bpe) as f64));
285        // Every view reports where it starts in its backing store. A `Buffer`
286        // already carried this; a typed array did not, so `u8.byteOffset` read
287        // `undefined` where a Buffer read 0. Nothing here can produce a
288        // non-zero offset yet — see the note on `.buffer` below.
289        m.insert("byteOffset".into(), Value::Float(byte_off as f64));
290        m.insert("BYTES_PER_ELEMENT".into(), Value::Float(bpe as f64));
291        let obj = h.new_object(m);
292        // Link the instance to the real `Uint8Array.prototype` object so its
293        // inherited methods resolve through the chain, exactly as a `Buffer`
294        // already did. Without this a typed array was a bare tagged object and
295        // `new Uint8Array([1]).every` was not even a function — the methods
296        // existed on the prototype but nothing pointed at it.
297        h.ensure_native_protos();
298        if let Some(p) = h.native_proto(kind) {
299            h.set_proto(&obj, p);
300        }
301        // View metadata is real but non-enumerable, as it is for a Buffer.
302        for k in [
303            "buffer",
304            "length",
305            "byteLength",
306            "byteOffset",
307            "BYTES_PER_ELEMENT",
308        ] {
309            h.hide_prop(&obj, k);
310        }
311        obj
312    })
313}
314
315/// ToIntegerOrInfinity (7.1.5): truncation, with NaN as 0.
316fn integer_or_infinity(n: f64) -> f64 {
317    if n.is_nan() {
318        0.0
319    } else {
320        n.trunc() + 0.0
321    }
322}
323
324/// ToIndex (7.1.22): `None` for a negative or above-2^53-1 integer.
325fn to_index(n: f64) -> Option<usize> {
326    let i = integer_or_infinity(n);
327    (0.0..=9_007_199_254_740_991.0)
328        .contains(&i)
329        .then_some(i as usize)
330}
331
332/// Whether a constructor argument is a primitive rather than an Object.
333fn is_primitive(v: &Value) -> bool {
334    match v {
335        Value::Obj(_) => with_host(|h| {
336            matches!(
337                h.get(v),
338                Some(JsObj::Str(_))
339                    | Some(JsObj::Null)
340                    | Some(JsObj::BigInt(_))
341                    | Some(JsObj::Symbol { .. })
342            )
343        }),
344        _ => true,
345    }
346}
347
348/// `new Uint8Array(...)` etc. `ArrayBuffer` is a byte container with only a
349/// `byteLength`.
350pub fn construct(kind: &str, args: &[Value]) -> Result<Value, String> {
351    if kind == "ArrayBuffer" {
352        let n = to_index(super::arg_num(args, 0))
353            .ok_or_else(|| crate::host::range_error("Invalid array buffer length"))?;
354        // `maxByteLength` is read (and validated) before the buffer exists.
355        let max = match args.get(1) {
356            Some(opts) => {
357                crate::builtins::get_property(opts, "maxByteLength").unwrap_or(Value::Undef)
358            }
359            None => Value::Undef,
360        };
361        let max_len = match max {
362            Value::Undef => None,
363            _ => match to_index(with_host(|h| h.to_number(&max))) {
364                Some(m) if m >= n => Some(m),
365                _ => return Err(crate::host::range_error("Invalid array buffer max length")),
366            },
367        };
368        let ab = new_array_buffer(n);
369        // `new ArrayBuffer(n, { maxByteLength })` is a RESIZABLE buffer, which
370        // reports `resizable` and `maxByteLength` and accepts `resize`.
371        if let Some(m) = max_len {
372            with_host(|h| {
373                if let Some(JsObj::Object(p)) = h.get_mut(&ab) {
374                    p.insert("@@maxByteLength".into(), Value::Float(m as f64));
375                    p.insert("maxByteLength".into(), Value::Float(m as f64));
376                    p.insert("resizable".into(), Value::Bool(true));
377                }
378                h.hide_prop(&ab, "maxByteLength");
379                h.hide_prop(&ab, "resizable");
380            });
381        }
382        return Ok(ab);
383    }
384    // `new Uint8Array(buffer[, byteOffset[, length]])` — a VIEW onto an existing
385    // buffer rather than a fresh copy. This is the form that makes two views
386    // alias, and it did not exist: the argument fell through to the iterable
387    // branch and produced an empty array.
388    if let Some(first) = args.first() {
389        if super::native_tag(first).as_deref() == Some("ArrayBuffer") {
390            // A DETACHED buffer has no bytes to view.
391            if is_detached(first) {
392                return Err(crate::host::type_error(
393                    "Cannot perform Construct on a detached ArrayBuffer",
394                ));
395            }
396            // InitializeTypedArrayFromArrayBuffer (23.2.5.1.3), in its order,
397            // with V8's messages: they name the offending number as given.
398            let bpe = bytes_per_element(kind);
399            let total = buffer_byte_length(first);
400            let off_n = super::arg_num(args, 1);
401            let off = to_index(off_n).ok_or_else(|| {
402                crate::host::range_error(&format!(
403                    "Start offset {} is outside the bounds of the buffer",
404                    fmt_number(off_n)
405                ))
406            })?;
407            if off % bpe != 0 {
408                return Err(crate::host::range_error(&format!(
409                    "start offset of {kind} should be a multiple of {bpe}"
410                )));
411            }
412            let len = match args.get(2) {
413                Some(Value::Undef) | None => {
414                    if total % bpe != 0 {
415                        return Err(crate::host::range_error(&format!(
416                            "byte length of {kind} should be a multiple of {bpe}"
417                        )));
418                    }
419                    if off > total {
420                        return Err(crate::host::range_error(&format!(
421                            "Start offset {off} is outside the bounds of the buffer"
422                        )));
423                    }
424                    (total - off) / bpe
425                }
426                Some(_) => {
427                    let len_n = super::arg_num(args, 2);
428                    let bad = || {
429                        crate::host::range_error(&format!(
430                            "Invalid typed array length: {}",
431                            fmt_number(len_n)
432                        ))
433                    };
434                    let len = to_index(len_n).ok_or_else(bad)?;
435                    if off + len * bpe > total {
436                        return Err(bad());
437                    }
438                    len
439                }
440            };
441            return Ok(make_view(kind, first, off, len));
442        }
443    }
444    let elems = build_elems(kind, args)?;
445    Ok(make(kind, elems))
446}
447
448/// The methods a `DataView` instance exposes.
449pub const DATAVIEW_METHODS: &[&str] = &[
450    "getInt8",
451    "getUint8",
452    "getInt16",
453    "getUint16",
454    "getInt32",
455    "getUint32",
456    "getFloat32",
457    "getFloat64",
458    "getBigInt64",
459    "getBigUint64",
460    "setInt8",
461    "setUint8",
462    "setInt16",
463    "setUint16",
464    "setInt32",
465    "setUint32",
466    "setFloat32",
467    "setFloat64",
468    "setBigInt64",
469    "setBigUint64",
470];
471
472/// `new DataView(buffer[, byteOffset[, byteLength]])`.
473pub fn construct_dataview(args: &[Value]) -> Result<Value, String> {
474    let buf = args.first().cloned().unwrap_or(Value::Undef);
475    if super::native_tag(&buf).as_deref() != Some("ArrayBuffer") {
476        return Err(crate::host::type_error(
477            "First argument to DataView constructor must be an ArrayBuffer",
478        ));
479    }
480    // 25.3.2.1, with V8's messages, which name the offending value after
481    // ToIntegerOrInfinity (`-1.5` reports as `-1`).
482    let total = buffer_byte_length(&buf);
483    let off_n = super::arg_num(args, 1);
484    let outside = |n: f64| {
485        crate::host::range_error(&format!(
486            "Start offset {} is outside the bounds of the buffer",
487            fmt_number(integer_or_infinity(n))
488        ))
489    };
490    let off = to_index(off_n).ok_or_else(|| outside(off_n))?;
491    if off > total {
492        return Err(outside(off_n));
493    }
494    let bad_len = |n: f64| {
495        crate::host::range_error(&format!(
496            "Invalid DataView length {}",
497            fmt_number(integer_or_infinity(n))
498        ))
499    };
500    let len = match args.get(2) {
501        Some(Value::Undef) | None => total - off,
502        Some(_) => {
503            let len_n = super::arg_num(args, 2);
504            let len = to_index(len_n).ok_or_else(|| bad_len(len_n))?;
505            if off + len > total {
506                return Err(bad_len(len_n));
507            }
508            len
509        }
510    };
511    Ok(with_host(|h| {
512        let mut m = IndexMap::new();
513        m.insert("@@native".into(), h.new_str("DataView"));
514        m.insert("@@buffer".into(), buf.clone());
515        m.insert("buffer".into(), buf.clone());
516        m.insert("byteOffset".into(), Value::Float(off as f64));
517        m.insert("byteLength".into(), Value::Float(len as f64));
518        let obj = h.new_object(m);
519        for k in ["buffer", "byteOffset", "byteLength"] {
520            h.hide_prop(&obj, k);
521        }
522        h.ensure_native_protos();
523        if let Some(p) = h.ensure_ctor_proto("DataView") {
524            h.set_proto(&obj, p);
525        }
526        obj
527    }))
528}
529
530/// `dv.getUint16(off[, littleEndian])` and its siblings. A `DataView` defaults
531/// to BIG-endian, unlike a typed array, which is the whole reason it exists.
532pub fn dataview_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
533    if view_detached(recv) {
534        return Err(detached_error("DataView.prototype", method, false));
535    }
536    let Some(spec) = method.get(3..) else {
537        return Err(crate::host::type_error(&format!(
538            "{method} is not a function"
539        )));
540    };
541    let width = match spec {
542        "Int8" | "Uint8" => 1,
543        "Int16" | "Uint16" => 2,
544        "Int32" | "Uint32" | "Float32" => 4,
545        "Float64" | "BigInt64" | "BigUint64" => 8,
546        _ => {
547            return Err(crate::host::type_error(&format!(
548                "{method} is not a function"
549            )))
550        }
551    };
552    let is_get = method.starts_with("get");
553    // `ToIndex(requestIndex)` (25.3.1.1 step 3): NaN is 0 and a fraction
554    // truncates toward zero, so `dv.getUint8(1.9)` reads index 1. A NEGATIVE
555    // index was being clamped to 0 — `dv.getUint8(-2)` quietly read the first
556    // byte where node reports the out-of-bounds RangeError.
557    let requested = super::arg_num(args, 0);
558    let requested = if requested.is_nan() {
559        0.0
560    } else {
561        requested.trunc()
562    };
563    let span = with_host(|h| match h.get(recv) {
564        Some(JsObj::Object(p)) => p.get("byteLength").map(|l| h.to_number(l)).unwrap_or(0.0),
565        _ => 0.0,
566    });
567    if requested < 0.0 || requested + width as f64 > span {
568        return Err(crate::host::range_error(
569            "Offset is outside the bounds of the DataView",
570        ));
571    }
572    let at = requested as usize;
573    // The endianness flag is the LAST argument, and it is the second for a
574    // getter but the third for a setter.
575    let le = with_host(|h| {
576        h.truthy(
577            args.get(if is_get { 1 } else { 2 })
578                .unwrap_or(&Value::Undef),
579        )
580    });
581    if is_get {
582        let mut b = view_bytes(recv, at, width).unwrap_or_else(|| vec![0; width]);
583        if !le {
584            b.reverse();
585        }
586        return Ok(match spec {
587            "Int8" => Value::Float(b[0] as i8 as f64),
588            "Uint8" => Value::Float(b[0] as f64),
589            "Int16" => Value::Float(i16::from_le_bytes([b[0], b[1]]) as f64),
590            "Uint16" => Value::Float(u16::from_le_bytes([b[0], b[1]]) as f64),
591            "Int32" => Value::Float(i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
592            "Uint32" => Value::Float(u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
593            "Float32" => Value::Float(f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
594            "Float64" => Value::Float(f64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]))),
595            "BigInt64" => {
596                let raw = i64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
597                with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
598            }
599            _ => {
600                let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
601                with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
602            }
603        });
604    }
605    let val = args.get(1).cloned().unwrap_or(Value::Undef);
606    let mut b = match spec {
607        "BigInt64" | "BigUint64" => {
608            use num_traits::cast::ToPrimitive;
609            // `setBigInt64`/`setBigUint64` take `ToBigInt(value)` (25.3.4.x via
610            // `SetViewValue` step 5), the same conversion an element write does.
611            let big = crate::builtins::to_bigint(&val)?;
612            let raw = if spec == "BigInt64" {
613                big.to_i64().unwrap_or(0) as u64
614            } else {
615                big.to_u64().unwrap_or(0)
616            };
617            raw.to_le_bytes().to_vec()
618        }
619        _ => {
620            let n = with_host(|h| h.to_number(&val));
621            match spec {
622                "Int8" | "Uint8" => vec![n as i64 as u8],
623                "Int16" | "Uint16" => (n as i64 as u16).to_le_bytes().to_vec(),
624                "Int32" | "Uint32" => (n as i64 as u32).to_le_bytes().to_vec(),
625                "Float32" => (n as f32).to_le_bytes().to_vec(),
626                _ => n.to_le_bytes().to_vec(),
627            }
628        }
629    };
630    if !le {
631        b.reverse();
632    }
633    write_view_bytes(recv, at, &b);
634    Ok(Value::Undef)
635}
636
637/// `ab.resize(n)` on a resizable buffer — grows with zeros or truncates,
638/// in place, so every view over it sees the new size.
639pub fn buffer_resize(ab: &Value, args: &[Value]) -> Result<Value, String> {
640    let max = with_host(|h| match h.get(ab) {
641        Some(JsObj::Object(p)) => p.get("@@maxByteLength").map(|m| h.to_number(m) as usize),
642        _ => None,
643    })
644    .ok_or_else(|| {
645        crate::host::type_error(
646            "ArrayBuffer.prototype.resize called on a non-resizable ArrayBuffer",
647        )
648    })?;
649    let n = super::arg_num(args, 0).max(0.0) as usize;
650    if n > max {
651        return Err(crate::host::range_error("Invalid array buffer length"));
652    }
653    let store = store_of(ab);
654    with_host(|h| {
655        if let Some(a) = store {
656            if let Some(JsObj::Array(items)) = h.get_mut(&a) {
657                items.resize(n, Value::Float(0.0));
658            }
659        }
660        if let Some(JsObj::Object(p)) = h.get_mut(ab) {
661            p.insert("byteLength".into(), Value::Float(n as f64));
662        }
663    });
664    Ok(Value::Undef)
665}
666
667/// Overwrite an `ArrayBuffer`'s bytes wholesale, for a producer that computed
668/// them outside the heap.
669pub fn write_buffer_bytes(ab: &Value, bytes: &[u8]) {
670    let Some(store) = store_of(ab) else { return };
671    with_host(|h| {
672        if let Some(JsObj::Array(items)) = h.get_mut(&store) {
673            *items = bytes.iter().map(|b| Value::Float(*b as f64)).collect();
674        }
675        if let Some(JsObj::Object(p)) = h.get_mut(ab) {
676            p.insert("byteLength".into(), Value::Float(bytes.len() as f64));
677        }
678    });
679}
680
681/// The heap array an `ArrayBuffer` keeps its bytes in, so another view can
682/// share it rather than copy.
683pub fn buffer_store(ab: &Value) -> Option<Value> {
684    store_of(ab)
685}
686
687/// A COPY of an `ArrayBuffer`'s bytes, for the callers that only read.
688pub fn buffer_bytes_snapshot(ab: &Value) -> Option<Vec<u8>> {
689    let store = store_of(ab)?;
690    with_host(|h| match h.get(&store) {
691        Some(JsObj::Array(items)) => {
692            Some(items.iter().map(|x| h.to_number(x) as i64 as u8).collect())
693        }
694        _ => None,
695    })
696}
697
698/// An `ArrayBuffer`'s byte length, from its own store.
699pub fn buffer_byte_length(ab: &Value) -> usize {
700    with_host(|h| match h.get(ab) {
701        Some(JsObj::Object(p)) => match p.get("@@bytes").and_then(|a| h.get(a)) {
702            Some(JsObj::Array(items)) => items.len(),
703            _ => 0,
704        },
705        _ => 0,
706    })
707}
708
709/// `ArrayBuffer.prototype.slice(begin[, end])` — a COPY of the byte range, as a
710/// new buffer. Writes to it are not seen by views over the original.
711pub fn buffer_slice(ab: &Value, args: &[Value]) -> Value {
712    let total = buffer_byte_length(ab) as i64;
713    let idx = |v: Option<&Value>, dflt: i64| -> usize {
714        let n = match v {
715            None | Some(Value::Undef) => dflt,
716            Some(x) => with_host(|h| h.to_number(x)) as i64,
717        };
718        (if n < 0 { total + n } else { n }).clamp(0, total) as usize
719    };
720    let start = idx(args.first(), 0);
721    let end = idx(args.get(1), total).max(start);
722    let out = new_array_buffer(end - start);
723    let src = with_host(|h| match h.get(ab) {
724        Some(JsObj::Object(p)) => match p.get("@@bytes").and_then(|a| h.get(a)) {
725            Some(JsObj::Array(items)) => items[start..end].to_vec(),
726            _ => Vec::new(),
727        },
728        _ => Vec::new(),
729    });
730    with_host(|h| {
731        if let Some(JsObj::Object(p)) = h.get(&out) {
732            if let Some(arr) = p.get("@@bytes").cloned() {
733                if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
734                    *items = src;
735                }
736            }
737        }
738    });
739    out
740}
741
742/// Element vector for a typed-array construction from its first argument:
743/// a number → that many zeroed slots; an array/iterable/typed-array → its coerced
744/// values; otherwise → empty.
745fn build_elems(kind: &str, args: &[Value]) -> Result<Vec<Value>, String> {
746    match args.first() {
747        None | Some(Value::Undef) => Ok(Vec::new()),
748        // A non-Object first argument is a LENGTH (23.2.5.1 step 6), taken
749        // through ToIndex: `new Uint8Array('2')` is two zeros and a negative
750        // or unsafe length is a RangeError, not an empty array.
751        Some(v) if is_primitive(v) => {
752            let n_raw = super::arg_num(args, 0);
753            let n = to_index(n_raw).ok_or_else(|| {
754                crate::host::range_error(&format!(
755                    "Invalid typed array length: {}",
756                    fmt_number(n_raw)
757                ))
758            })?;
759            Ok(vec![zero_of(kind); n])
760        }
761        Some(v) => {
762            // Another typed array / Buffer → copy its elements; anything else
763            // iterable → coerce each entry.
764            let items = match super::native_tag(v).as_deref() {
765                Some("TypedArray") | Some("Buffer") => elem_values(v),
766                // 23.2.5.1.2: an object with an `@@iterator` is iterated; any
767                // other is an ARRAY-LIKE, read as `length` then each index.
768                _ if crate::builtins::get_property(v, "@@iterator")
769                    .map_or(true, |m| !matches!(m, Value::Undef)) =>
770                {
771                    crate::host::iter_all(v).unwrap_or_default()
772                }
773                _ => {
774                    let len = crate::builtins::get_property(v, "length")?;
775                    let n = with_host(|h| h.to_number(&len));
776                    let n = if n.is_finite() && n > 0.0 {
777                        n as usize
778                    } else {
779                        0
780                    };
781                    (0..n)
782                        .map(|i| crate::builtins::get_property(v, &i.to_string()))
783                        .collect::<Result<Vec<_>, _>>()?
784                }
785            };
786            items.iter().map(|x| coerce_val(kind, x)).collect()
787        }
788    }
789}
790
791// ── Uint8Array base64/hex (the "Uint8Array to/from base64" proposal) ──────────
792
793/// How much of a trailing partial base64 chunk `fromBase64`/`setFromBase64`
794/// accept. The default is `loose`, which is why an UNPADDED string decodes.
795#[derive(Clone, Copy, PartialEq)]
796enum LastChunk {
797    Loose,
798    Strict,
799    StopBeforePartial,
800}
801
802/// Read the `{ alphabet, lastChunkHandling }` options object. Both reject an
803/// unknown value with node's `invalid option <v>`, and a non-object that is not
804/// `undefined` is `invalid_argument` — not the usual "must be an object".
805fn base64_options(opt: Option<&Value>) -> Result<(bool, LastChunk), String> {
806    let Some(o) = opt.filter(|v| !matches!(v, Value::Undef)) else {
807        return Ok((false, LastChunk::Loose));
808    };
809    if !with_host(|h| matches!(h.get(o), Some(JsObj::Object(_)))) {
810        return Err(crate::host::type_error("invalid_argument"));
811    }
812    let read = |k: &str| {
813        with_host(|h| match h.get(o) {
814            Some(JsObj::Object(p)) => p.get(k).filter(|v| !matches!(v, Value::Undef)).cloned(),
815            _ => None,
816        })
817    };
818    let url = match read("alphabet") {
819        None => false,
820        Some(v) => match with_host(|h| h.str_of(&v)).as_str() {
821            "base64" => false,
822            "base64url" => true,
823            other => return Err(crate::host::type_error(&format!("invalid option {other}"))),
824        },
825    };
826    let last = match read("lastChunkHandling") {
827        None => LastChunk::Loose,
828        Some(v) => match with_host(|h| h.str_of(&v)).as_str() {
829            "loose" => LastChunk::Loose,
830            "strict" => LastChunk::Strict,
831            "stop-before-partial" => LastChunk::StopBeforePartial,
832            other => return Err(crate::host::type_error(&format!("invalid option {other}"))),
833        },
834    };
835    Ok((url, last))
836}
837
838const B64_BAD: &str =
839    "SyntaxError: Found a character that cannot be part of a valid base64 string.";
840const B64_SINGLE: &str =
841    "SyntaxError: The base64 input terminates with a single character, excluding padding (=).";
842
843/// Decode base64 STRICTLY, reporting how many characters were consumed.
844///
845/// The lenient decoder behind `atob` cannot serve here: this has to reject a
846/// stray `=`, a wrong pad count and a character outside the selected alphabet,
847/// and `stop-before-partial` needs the consumed count rather than just the
848/// bytes. ASCII whitespace is skipped, which node also allows.
849fn decode_base64_strict(s: &str, url: bool, last: LastChunk) -> Result<(Vec<u8>, usize), String> {
850    let value = |c: char| -> Option<u32> {
851        let table = if url {
852            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
853        } else {
854            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
855        };
856        table.find(c).map(|i| i as u32)
857    };
858    let chars: Vec<char> = s.chars().collect();
859    let mut out = Vec::new();
860    let mut chunk: Vec<u32> = Vec::new();
861    let mut consumed = 0usize;
862    let mut i = 0usize;
863    while i < chars.len() {
864        let c = chars[i];
865        if c.is_ascii_whitespace() {
866            i += 1;
867            continue;
868        }
869        if c == '=' {
870            // Padding closes the chunk, and only a 2- or 3-character chunk may
871            // be padded: `QQ=` and `AA===` are both errors.
872            let pads = chars[i..].iter().filter(|c| **c == '=').count();
873            let rest_ok = chars[i..]
874                .iter()
875                .all(|c| *c == '=' || c.is_ascii_whitespace());
876            let want = 4 - chunk.len();
877            if !rest_ok || chunk.len() < 2 || pads != want {
878                return Err(B64_BAD.into());
879            }
880            out.extend(flush_base64_chunk(&chunk));
881            return Ok((out, chars.len()));
882        }
883        let Some(v) = value(c) else {
884            return Err(B64_BAD.into());
885        };
886        chunk.push(v);
887        i += 1;
888        if chunk.len() == 4 {
889            out.extend(flush_base64_chunk(&chunk));
890            chunk.clear();
891            consumed = i;
892        }
893    }
894    match chunk.len() {
895        0 => Ok((out, consumed)),
896        // A single leftover character encodes nothing at all.
897        1 if last != LastChunk::StopBeforePartial => Err(B64_SINGLE.into()),
898        _ if last == LastChunk::StopBeforePartial => Ok((out, consumed)),
899        1 => Ok((out, consumed)),
900        _ if last == LastChunk::Strict => Err(B64_SINGLE.into()),
901        _ => {
902            out.extend(flush_base64_chunk(&chunk));
903            Ok((out, chars.len()))
904        }
905    }
906}
907
908/// The 1-3 bytes a base64 chunk of 2, 3 or 4 sextets encodes.
909fn flush_base64_chunk(chunk: &[u32]) -> Vec<u8> {
910    let mut acc = 0u32;
911    for v in chunk {
912        acc = (acc << 6) | v;
913    }
914    let bytes = chunk.len() - 1;
915    acc <<= 6 * (4 - chunk.len());
916    let all = [(acc >> 16) as u8, (acc >> 8) as u8, acc as u8];
917    all[..bytes].to_vec()
918}
919
920const HEX_BAD: &str = "SyntaxError: Input string must contain hex characters in even length";
921
922/// Decode hex STRICTLY. Node reports the same message for an odd length and for
923/// a non-hex character, so `"gg"` and `"0"` fail identically.
924fn decode_hex_strict(s: &str) -> Result<Vec<u8>, String> {
925    let chars: Vec<char> = s.chars().collect();
926    if chars.len() % 2 != 0 || !chars.iter().all(|c| c.is_ascii_hexdigit()) {
927        return Err(HEX_BAD.into());
928    }
929    Ok(chars
930        .chunks(2)
931        .map(|p| {
932            let hi = p[0].to_digit(16).expect("checked");
933            let lo = p[1].to_digit(16).expect("checked");
934            (hi * 16 + lo) as u8
935        })
936        .collect())
937}
938
939/// The string argument these six all take, rejecting anything else the way node
940/// does rather than coercing it.
941fn base64_input(args: &[Value]) -> Result<String, String> {
942    let v = args.first().cloned().unwrap_or(Value::Undef);
943    let is_str = matches!(v, Value::Str(_))
944        || with_host(|h| matches!(h.get(&v), Some(crate::host::JsObj::Str(_))));
945    if !is_str {
946        return Err(crate::host::type_error("input argument must be a string"));
947    }
948    Ok(with_host(|h| h.str_of(&v)))
949}
950
951/// `Uint8Array.fromBase64` / `Uint8Array.fromHex`.
952fn from_base64_static(method: &str, args: &[Value]) -> Result<Value, String> {
953    let s = base64_input(args)?;
954    let bytes = if method == "fromHex" {
955        decode_hex_strict(&s)?
956    } else {
957        let (url, last) = base64_options(args.get(1))?;
958        decode_base64_strict(&s, url, last)?.0
959    };
960    Ok(make(
961        "Uint8Array",
962        bytes.iter().map(|b| Value::Float(*b as f64)).collect(),
963    ))
964}
965
966/// `Uint8Array.from(iterable[, mapFn])` / `Uint8Array.of(...items)`, and the
967/// base64/hex statics.
968pub fn static_call(kind: &str, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
969    // The base64/hex statics are on `Uint8Array` ONLY — no other view has them.
970    if matches!(method, "fromBase64" | "fromHex") {
971        if kind != "Uint8Array" {
972            return None;
973        }
974        return Some(from_base64_static(method, args));
975    }
976    Some(match method {
977        "of" => args
978            .iter()
979            .map(|x| coerce_val(kind, x))
980            .collect::<Result<Vec<Value>, String>>()
981            .map(|e| make(kind, e)),
982        "from" => from(kind, args),
983        // `ArrayBuffer.isView(x)` — true for a typed array or a Buffer (which is
984        // a Uint8Array view), false for the backing ArrayBuffer itself.
985        "isView" => Ok(Value::Bool(with_host(|h| {
986            matches!(
987                h.get(&args.first().cloned().unwrap_or(Value::Undef)),
988                Some(crate::host::JsObj::Object(p))
989                    if matches!(
990                        p.get("@@native").map(|t| h.str_of(t)).as_deref(),
991                        Some("TypedArray") | Some("Buffer") | Some("DataView")
992                    )
993            )
994        }))),
995        _ => return None,
996    })
997}
998
999fn from(kind: &str, args: &[Value]) -> Result<Value, String> {
1000    let src = args.first().cloned().unwrap_or(Value::Undef);
1001    let map_fn = args
1002        .get(1)
1003        .cloned()
1004        .filter(|f| with_host(|h| crate::host::is_callable(h, f)));
1005    // A source that is not iterable is read as an array-like (23.2.2.1
1006    // step 7): `Int8Array.from({length: 3, 1: 5})` is `[0, 5, 0]`.
1007    let items = if let Some(e) = elems_of(&src) {
1008        e.into_iter().map(Value::Float).collect()
1009    } else {
1010        crate::host::iter_all(&src).unwrap_or_else(|_| crate::builtins::array_like_items(&src))
1011    };
1012    let mut out = Vec::with_capacity(items.len());
1013    for (i, it) in items.into_iter().enumerate() {
1014        let mapped = match &map_fn {
1015            Some(f) => crate::host::invoke(f, vec![it, Value::Float(i as f64)], None)?,
1016            None => it,
1017        };
1018        out.push(coerce_val(kind, &mapped)?);
1019    }
1020    Ok(make(kind, out))
1021}
1022
1023/// The element values of a typed array / Buffer (`None` for anything else).
1024pub fn elems_of(v: &Value) -> Option<Vec<f64>> {
1025    let tag = super::native_tag(v)?;
1026    if !matches!(tag.as_str(), "TypedArray" | "Buffer") {
1027        return None;
1028    }
1029    let vals = elem_values(v);
1030    Some(with_host(|h| vals.iter().map(|x| h.to_number(x)).collect()))
1031}
1032
1033/// The number of elements `v` exposes as integer-index own properties, for a
1034/// typed array (its view length) or a `Buffer` (`@@bytes`); `None` otherwise.
1035///
1036/// Both index-membership questions — `obj.hasOwnProperty(i)` and `i in obj` —
1037/// must answer from this one place. They used to disagree: `hasOwnProperty`
1038/// carried a hand-rolled arm that understood `@@bytes` only, so it was right for
1039/// a Buffer and wrong for every other typed array, while the `in` operator knew
1040/// about neither and reported false for every valid index of both.
1041pub fn index_len(v: &Value) -> Option<usize> {
1042    match super::native_tag(v)?.as_str() {
1043        "TypedArray" => Some(view_len(v)),
1044        "Buffer" => with_host(|h| match h.get(v) {
1045            Some(JsObj::Object(p)) => Some(super::buffer::window_h(h, p).1),
1046            _ => None,
1047        }),
1048        _ => None,
1049    }
1050}
1051
1052/// Whether `key` is an in-range integer index of the typed array / Buffer `v`.
1053/// `None` when `v` is neither, so callers can fall through to their own logic.
1054pub fn has_index(v: &Value, key: &str) -> Option<bool> {
1055    let len = index_len(v)?;
1056    Some(key.parse::<usize>().map(|i| i < len).unwrap_or(false))
1057}
1058
1059/// The `@@kind` of a typed-array receiver (defaults to `Uint8Array`).
1060pub fn kind_of(recv: &Value) -> String {
1061    with_host(|h| match h.get(recv) {
1062        Some(JsObj::Object(p)) => p
1063            .get("@@kind")
1064            .map(|v| h.str_of(v))
1065            .unwrap_or_else(|| "Uint8Array".into()),
1066        _ => "Uint8Array".into(),
1067    })
1068}
1069
1070// ── backing store ────────────────────────────────────────────────────────────
1071//
1072// Every view — typed array or `DataView` — reads and writes THROUGH an
1073// `ArrayBuffer`, which owns the only copy of the bytes as a hidden `@@bytes`
1074// heap array. That is what makes two views over one buffer see each other's
1075// writes: `new Uint32Array(ab)[0]` reflects a byte written through
1076// `new Uint8Array(ab)`. Before this an `ArrayBuffer` carried nothing but a
1077// `byteLength` and each view owned a private element vector, so nothing was
1078// ever shared and `DataView` did not exist at all.
1079
1080/// Allocate an `ArrayBuffer` of `n` zeroed bytes.
1081pub fn new_array_buffer(n: usize) -> Value {
1082    let arr = with_host(|h| h.new_array(vec![Value::Float(0.0); n]));
1083    array_buffer_over(arr)
1084}
1085
1086/// An `ArrayBuffer` whose bytes ARE the heap array `arr` — shared, not copied.
1087/// A `Buffer` built from its own bytes keeps its store this way, so its
1088/// `.buffer` and every view made over that are one memory.
1089pub fn array_buffer_over(arr: Value) -> Value {
1090    with_host(|h| {
1091        let n = match h.get(&arr) {
1092            Some(JsObj::Array(items)) => items.len(),
1093            _ => 0,
1094        };
1095        let mut m = IndexMap::new();
1096        m.insert("@@native".into(), h.new_str("ArrayBuffer"));
1097        m.insert("@@bytes".into(), arr);
1098        m.insert("byteLength".into(), Value::Float(n as f64));
1099        // `detached` is a prototype accessor in the spec; kept as a hidden own
1100        // property here so it reads back without appearing in `Object.keys` or
1101        // `console.log`, the same way `byteLength` is.
1102        m.insert("detached".into(), Value::Bool(false));
1103        // A FIXED buffer still reports both, as `false` and its own length —
1104        // they are prototype accessors in the spec, so they always answer.
1105        m.insert("resizable".into(), Value::Bool(false));
1106        m.insert("maxByteLength".into(), Value::Float(n as f64));
1107        let obj = h.new_object(m);
1108        for k in ["byteLength", "detached", "resizable", "maxByteLength"] {
1109            h.hide_prop(&obj, k);
1110        }
1111        // `ensure_ctor_proto` builds the prototype WITH a `constructor` slot, so
1112        // `ab.constructor.name` reports `ArrayBuffer` rather than `Object`.
1113        if let Some(p) = h.ensure_ctor_proto("ArrayBuffer") {
1114            h.set_proto(&obj, p);
1115        }
1116        obj
1117    })
1118}
1119
1120/// Whether `ab` was marked UNTRANSFERABLE (`internal/buffer`'s
1121/// `markAsUntransferable`), as the Buffer pool is: `transfer()` and a
1122/// `structuredClone` transfer list both refuse it.
1123pub fn is_untransferable(ab: &Value) -> bool {
1124    with_host(|h| matches!(h.get(ab), Some(JsObj::Object(p)) if p.contains_key("@@untransferable")))
1125}
1126
1127/// Mark `ab` untransferable (see [`is_untransferable`]).
1128pub fn mark_untransferable(ab: &Value) {
1129    with_host(|h| {
1130        if let Some(JsObj::Object(p)) = h.get_mut(ab) {
1131            p.insert("@@untransferable".into(), Value::Bool(true));
1132        }
1133    });
1134}
1135
1136/// Whether `ab` has been DETACHED — its bytes handed to another buffer by
1137/// `transfer`, or given away by `structuredClone`'s `transfer` option.
1138///
1139/// A detached buffer is not an empty one: reading a view over it answers
1140/// `undefined` and its `length` is 0, but every METHOD on that view throws.
1141pub fn is_detached(ab: &Value) -> bool {
1142    with_host(|h| match h.get(ab) {
1143        Some(JsObj::Object(p)) => p.get("detached").map(|v| h.truthy(v)).unwrap_or(false),
1144        _ => false,
1145    })
1146}
1147
1148/// Whether `v` is a view whose backing buffer has been detached.
1149pub fn view_detached(v: &Value) -> bool {
1150    with_host(|h| view_detached_h(h, v))
1151}
1152
1153/// `view_detached` for a caller that already holds the host borrow — the
1154/// iteration entry point runs under one, and re-entering aborts the process.
1155pub fn view_detached_h(h: &crate::host::JsHost, v: &Value) -> bool {
1156    let buf = match h.get(v) {
1157        Some(JsObj::Object(p)) => p.get("@@buffer").cloned(),
1158        _ => None,
1159    };
1160    match buf.and_then(|b| match h.get(&b) {
1161        Some(JsObj::Object(p)) => p.get("detached").cloned(),
1162        _ => None,
1163    }) {
1164        Some(d) => h.truthy(&d),
1165        None => false,
1166    }
1167}
1168
1169/// Detach `ab`: drop its bytes and mark it, so every later read reports zero
1170/// length and every method over it throws.
1171pub fn detach_buffer(ab: &Value) {
1172    detach(ab)
1173}
1174
1175fn detach(ab: &Value) {
1176    let store = store_of(ab);
1177    with_host(|h| {
1178        // Emptied IN PLACE: a `Buffer` holds the store array itself, so a
1179        // replacement array would leave it reading the old bytes.
1180        if let Some(JsObj::Array(items)) = store.as_ref().and_then(|s| h.get_mut(s)) {
1181            items.clear();
1182        }
1183        if let Some(JsObj::Object(p)) = h.get_mut(ab) {
1184            p.insert("byteLength".into(), Value::Float(0.0));
1185            p.insert("detached".into(), Value::Bool(true));
1186        }
1187        h.hide_prop(ab, "byteLength");
1188        h.hide_prop(ab, "detached");
1189    });
1190}
1191
1192/// `ArrayBuffer.prototype.transfer([newLength])` and `transferToFixedLength`.
1193///
1194/// A fresh buffer takes the bytes — truncated or zero-padded to `newLength` —
1195/// and the receiver is detached. The two differ only in whether the result may
1196/// still grow.
1197pub fn buffer_transfer(ab: &Value, args: &[Value], fixed: bool) -> Result<Value, String> {
1198    let method = if fixed {
1199        "transferToFixedLength"
1200    } else {
1201        "transfer"
1202    };
1203    if is_detached(ab) {
1204        return Err(crate::host::type_error(&format!(
1205            "Cannot perform ArrayBuffer.prototype.{method} on a detached ArrayBuffer"
1206        )));
1207    }
1208    if is_untransferable(ab) {
1209        return Err(crate::host::type_error(
1210            "ArrayBuffer is not detachable and could not be cloned.",
1211        ));
1212    }
1213    let old = byte_len_of(ab);
1214    let new_len = match args.first().filter(|v| !matches!(v, Value::Undef)) {
1215        Some(v) => with_host(|h| h.to_number(v)).max(0.0) as usize,
1216        None => old,
1217    };
1218    let mut bytes = view_bytes_of_buffer(ab, old);
1219    bytes.resize(new_len, 0);
1220    let out = new_array_buffer(new_len);
1221    write_buffer_bytes(&out, &bytes);
1222    if !fixed {
1223        // `transfer` keeps the source's resizability; `transferToFixedLength`
1224        // never does.
1225        let resizable = with_host(|h| match h.get(ab) {
1226            Some(JsObj::Object(p)) => p.contains_key("@@maxByteLength"),
1227            _ => false,
1228        });
1229        if resizable {
1230            let max = with_host(|h| match h.get(ab) {
1231                Some(JsObj::Object(p)) => p.get("@@maxByteLength").cloned(),
1232                _ => None,
1233            });
1234            if let Some(max) = max {
1235                with_host(|h| {
1236                    if let Some(JsObj::Object(p)) = h.get_mut(&out) {
1237                        p.insert("@@maxByteLength".into(), max);
1238                    }
1239                });
1240            }
1241        }
1242    }
1243    detach(ab);
1244    Ok(out)
1245}
1246
1247/// An ArrayBuffer's `byteLength`.
1248fn byte_len_of(ab: &Value) -> usize {
1249    with_host(|h| match h.get(ab) {
1250        Some(JsObj::Object(p)) => {
1251            p.get("byteLength").map(|l| h.to_number(l)).unwrap_or(0.0) as usize
1252        }
1253        _ => 0,
1254    })
1255}
1256
1257/// An ArrayBuffer's bytes.
1258fn view_bytes_of_buffer(ab: &Value, n: usize) -> Vec<u8> {
1259    let Some(store) = store_of(ab) else {
1260        return Vec::new();
1261    };
1262    with_host(|h| match h.get(&store) {
1263        Some(JsObj::Array(items)) => items
1264            .iter()
1265            .take(n)
1266            .map(|x| h.to_number(x) as i64 as u8)
1267            .collect(),
1268        _ => Vec::new(),
1269    })
1270}
1271
1272/// The TypeError a method over a DETACHED buffer throws. Node names the method
1273/// and distinguishes a view's from a DataView's from the buffer's own.
1274pub fn detached_error(label: &str, method: &str, buffer_only: bool) -> String {
1275    let tail = if buffer_only {
1276        "a detached ArrayBuffer"
1277    } else {
1278        "a detached or out-of-bounds ArrayBuffer"
1279    };
1280    // A symbol-keyed member reports the name of the function it ALIASES, the way
1281    // node does everywhere else (`Set.prototype.keys` reports `values`):
1282    // `[...detachedView]` says `%TypedArray%.prototype.values`, never
1283    // `.@@iterator`, which is this frontend's internal spelling for
1284    // `Symbol.iterator` and not a name any script wrote.
1285    let method = match method {
1286        "@@iterator" => "values",
1287        other => other,
1288    };
1289    crate::host::type_error(&format!("Cannot perform {label}.{method} on {tail}"))
1290}
1291
1292/// The heap array holding an `ArrayBuffer`'s bytes.
1293fn store_of(ab: &Value) -> Option<Value> {
1294    with_host(|h| match h.get(ab) {
1295        Some(JsObj::Object(p)) => p.get("@@bytes").cloned(),
1296        _ => None,
1297    })
1298}
1299
1300/// A view's `(buffer, byteOffset)`.
1301fn view_base(v: &Value) -> Option<(Value, usize)> {
1302    with_host(|h| match h.get(v) {
1303        Some(JsObj::Object(p)) => {
1304            let buf = p.get("@@buffer").cloned()?;
1305            let off = p.get("byteOffset").map(|o| h.to_number(o)).unwrap_or(0.0);
1306            Some((buf, off.max(0.0) as usize))
1307        }
1308        _ => None,
1309    })
1310}
1311
1312/// `n` bytes of `v`'s buffer starting at its `byteOffset + at`.
1313pub fn view_bytes(v: &Value, at: usize, n: usize) -> Option<Vec<u8>> {
1314    let (buf, off) = view_base(v)?;
1315    let store = store_of(&buf)?;
1316    with_host(|h| match h.get(&store) {
1317        Some(JsObj::Array(items)) => {
1318            let start = off + at;
1319            if start + n > items.len() {
1320                return None;
1321            }
1322            Some(
1323                items[start..start + n]
1324                    .iter()
1325                    .map(|x| h.to_number(x) as i64 as u8)
1326                    .collect(),
1327            )
1328        }
1329        _ => None,
1330    })
1331}
1332
1333/// Write `bytes` into `v`'s buffer at its `byteOffset + at`. False when the
1334/// range does not fit.
1335pub fn write_view_bytes(v: &Value, at: usize, bytes: &[u8]) -> bool {
1336    let Some((buf, off)) = view_base(v) else {
1337        return false;
1338    };
1339    let Some(store) = store_of(&buf) else {
1340        return false;
1341    };
1342    with_host(|h| match h.get_mut(&store) {
1343        Some(JsObj::Array(items)) => {
1344            let start = off + at;
1345            if start + bytes.len() > items.len() {
1346                return false;
1347            }
1348            for (i, b) in bytes.iter().enumerate() {
1349                items[start + i] = Value::Float(*b as f64);
1350            }
1351            true
1352        }
1353        _ => false,
1354    })
1355}
1356
1357/// Decode one element of `kind` from its `bytes` (native byte order, which on
1358/// every architecture this runs on is little-endian).
1359fn decode(kind: &str, b: &[u8]) -> Value {
1360    match kind {
1361        "Int8Array" => Value::Float(b[0] as i8 as f64),
1362        "Uint8Array" | "Uint8ClampedArray" => Value::Float(b[0] as f64),
1363        "Int16Array" => Value::Float(i16::from_le_bytes([b[0], b[1]]) as f64),
1364        "Uint16Array" => Value::Float(u16::from_le_bytes([b[0], b[1]]) as f64),
1365        "Int32Array" => Value::Float(i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
1366        "Uint32Array" => Value::Float(u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
1367        "Float32Array" => Value::Float(f32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64),
1368        "BigInt64Array" => {
1369            let raw = i64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1370            with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
1371        }
1372        "BigUint64Array" => {
1373            let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1374            with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
1375        }
1376        _ => Value::Float(f64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]))),
1377    }
1378}
1379
1380/// Encode one already-coerced element of `kind` into its bytes.
1381fn encode(kind: &str, v: &Value) -> Vec<u8> {
1382    if is_bigint_kind(kind) {
1383        use num_traits::cast::ToPrimitive;
1384        let b = bigint_of(v);
1385        let raw = if kind == "BigInt64Array" {
1386            b.to_i64().unwrap_or(0) as u64
1387        } else {
1388            b.to_u64().unwrap_or(0)
1389        };
1390        return raw.to_le_bytes().to_vec();
1391    }
1392    let n = num(v);
1393    match kind {
1394        "Int8Array" => vec![n as i64 as i8 as u8],
1395        "Uint8Array" | "Uint8ClampedArray" => vec![n as i64 as u8],
1396        "Int16Array" => (n as i64 as i16).to_le_bytes().to_vec(),
1397        "Uint16Array" => (n as i64 as u16).to_le_bytes().to_vec(),
1398        "Int32Array" => (n as i64 as i32).to_le_bytes().to_vec(),
1399        "Uint32Array" => (n as i64 as u32).to_le_bytes().to_vec(),
1400        "Float32Array" => (n as f32).to_le_bytes().to_vec(),
1401        _ => n.to_le_bytes().to_vec(),
1402    }
1403}
1404
1405/// The elements of a typed-array view, decoded with a host borrow ALREADY
1406/// held. `host` reads views from inside `&self` methods (inspect, key
1407/// enumeration, iteration) where re-entering through `with_host` would panic on
1408/// the outstanding borrow.
1409pub fn elems_with_host(h: &crate::host::JsHost, v: &Value) -> Vec<Value> {
1410    if let Some(JsObj::Object(p)) = h.get(v) {
1411        if p.contains_key("@@bytes") {
1412            return super::buffer::window_bytes_h(h, p)
1413                .into_iter()
1414                .map(|b| Value::Float(b as f64))
1415                .collect();
1416        }
1417    }
1418    let Some((kind, raws)) = raw_elems(h, v) else {
1419        return Vec::new();
1420    };
1421    // A 64-bit element is a BigInt, which needs an allocation this borrow
1422    // cannot make; `elems_mut_host` is the reader for callers that can.
1423    if is_bigint_kind(&kind) {
1424        return vec![Value::Undef; raws.len()];
1425    }
1426    raws.iter().map(|b| decode(&kind, b)).collect()
1427}
1428
1429/// The raw bytes of every element of a view, with the host borrow already held.
1430/// The shared half of the three readers below.
1431fn raw_elems(h: &crate::host::JsHost, v: &Value) -> Option<(String, Vec<Vec<u8>>)> {
1432    let JsObj::Object(p) = h.get(v)? else {
1433        return None;
1434    };
1435    let kind = p
1436        .get("@@kind")
1437        .map(|k| h.str_of(k))
1438        .unwrap_or_else(|| "Uint8Array".into());
1439    let bpe = bytes_per_element(&kind);
1440    // A view over a DETACHED buffer has no elements. Its own `length` still
1441    // holds the old count, so `util.inspect` showed `Uint8Array(4) [0,0,0,0]`
1442    // over a buffer with no bytes left.
1443    let len = if view_detached_h(h, v) {
1444        0
1445    } else {
1446        p.get("length").map(|l| h.to_number(l)).unwrap_or(0.0) as usize
1447    };
1448    let off = p.get("byteOffset").map(|o| h.to_number(o)).unwrap_or(0.0) as usize;
1449    let store = match p.get("@@buffer").and_then(|b| h.get(b)) {
1450        Some(JsObj::Object(bp)) => bp.get("@@bytes").and_then(|a| h.get(a)),
1451        _ => None,
1452    };
1453    let JsObj::Array(bytes) = store? else {
1454        return None;
1455    };
1456    let out = (0..len)
1457        .map(|i| {
1458            let start = off + i * bpe;
1459            if start + bpe > bytes.len() {
1460                return vec![0u8; bpe];
1461            }
1462            bytes[start..start + bpe]
1463                .iter()
1464                .map(|x| h.to_number(x) as i64 as u8)
1465                .collect()
1466        })
1467        .collect();
1468    Some((kind, out))
1469}
1470
1471/// The elements of a view with a MUTABLE host borrow held, so the two 64-bit
1472/// kinds can allocate their BigInts. This is the complete reader; the `&self`
1473/// one below cannot allocate and so answers `undefined` for those two kinds.
1474pub fn elems_mut_host(h: &mut crate::host::JsHost, v: &Value) -> Vec<Value> {
1475    if let Some(JsObj::Object(p)) = h.get(v) {
1476        if p.contains_key("@@bytes") {
1477            return super::buffer::window_bytes_h(h, p)
1478                .into_iter()
1479                .map(|b| Value::Float(b as f64))
1480                .collect();
1481        }
1482    }
1483    let Some((kind, raws)) = raw_elems(h, v) else {
1484        return Vec::new();
1485    };
1486    raws.iter()
1487        .map(|b| {
1488            if !is_bigint_kind(&kind) {
1489                return decode(&kind, b);
1490            }
1491            let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1492            h.new_bigint(if kind == "BigInt64Array" {
1493                num_bigint::BigInt::from(raw as i64)
1494            } else {
1495                num_bigint::BigInt::from(raw)
1496            })
1497        })
1498        .collect()
1499}
1500
1501/// Every element rendered for display, for `util.inspect` — which holds a
1502/// shared borrow and so cannot allocate the BigInt a 64-bit element would need
1503/// as a `Value`. Elements are always primitives, so a string loses nothing.
1504pub fn elems_display(h: &crate::host::JsHost, v: &Value) -> Vec<String> {
1505    let Some((kind, raws)) = raw_elems(h, v) else {
1506        return Vec::new();
1507    };
1508    raws.iter()
1509        .map(|b| {
1510            if !is_bigint_kind(&kind) {
1511                return h.inspect(&decode(&kind, b));
1512            }
1513            let raw = u64::from_le_bytes(b[..8].try_into().unwrap_or([0; 8]));
1514            if kind == "BigInt64Array" {
1515                format!("{}n", raw as i64)
1516            } else {
1517                format!("{raw}n")
1518            }
1519        })
1520        .collect()
1521}
1522
1523/// The raw bytes a typed array VIEWS — `length * BYTES_PER_ELEMENT` of them
1524/// from its `byteOffset` — as opposed to its element values. A
1525/// `Uint16Array([0x4142])` is the two bytes `42 41`, never the one byte its
1526/// element truncates to. `None` for anything that is not a typed array.
1527pub fn raw_view_bytes(v: &Value) -> Option<Vec<u8>> {
1528    let kind = super::util_types::ta_kind(v)?;
1529    view_bytes(v, 0, view_len(v) * bytes_per_element(&kind))
1530}
1531
1532/// The element count a view exposes, from its own `length` slot.
1533fn view_len(v: &Value) -> usize {
1534    // A view over a DETACHED buffer has length 0 — its own `length` property
1535    // still holds the old count, which is why this cannot just read it.
1536    if view_detached(v) {
1537        return 0;
1538    }
1539    with_host(|h| match h.get(v) {
1540        Some(JsObj::Object(p)) => p.get("length").map(|l| h.to_number(l)).unwrap_or(0.0) as usize,
1541        _ => 0,
1542    })
1543}
1544
1545// ── element indexing (called from builtins::get_property/set_property) ────────
1546
1547/// `ta[i]` read: the element at char/index `i`, or `None` if `i` is out of range
1548/// or not an integer index.
1549pub fn elem_get(recv: &Value, key: &str) -> Option<Value> {
1550    let i: usize = key.parse().ok()?;
1551    if i >= view_len(recv) {
1552        return None;
1553    }
1554    let kind = kind_of(recv);
1555    let bpe = bytes_per_element(&kind);
1556    let bytes = view_bytes(recv, i * bpe, bpe)?;
1557    Some(decode(&kind, &bytes))
1558}
1559
1560/// `ta[i] = v` write (coerced to the kind). Returns true if `i` is a valid index.
1561pub fn elem_set(recv: &Value, key: &str, val: &Value) -> Result<bool, String> {
1562    let Ok(i) = key.parse::<usize>() else {
1563        return Ok(false);
1564    };
1565    let kind = kind_of(recv);
1566    // Coerced through the element type, so writing a Number into a 64-bit view
1567    // throws rather than storing an un-typed element.
1568    let n = coerce_val(&kind, val)?;
1569    if i >= view_len(recv) {
1570        return Ok(false);
1571    }
1572    let bpe = bytes_per_element(&kind);
1573    Ok(write_view_bytes(recv, i * bpe, &encode(&kind, &n)))
1574}
1575
1576/// Build a result of the same "species" as `recv`: a `Buffer` receiver yields a
1577/// `Buffer`, every other typed array yields its own kind. Node picks the result
1578/// type from the receiver's constructor, so `Buffer.from([1]).map(f)` is a
1579/// Buffer and `new Int32Array([1]).map(f)` is an `Int32Array`.
1580fn species(recv: &Value, kind: &str, elems: Vec<Value>) -> Value {
1581    if super::native_tag(recv).as_deref() == Some("Buffer") {
1582        let bytes: Vec<u8> = elems.iter().map(|x| num(x) as i64 as u8).collect();
1583        return super::buffer::from_bytes(&bytes);
1584    }
1585    make(kind, elems)
1586}
1587
1588/// Overwrite `recv`'s elements in place, for the methods that mutate and return
1589/// the receiver (`fill`, `reverse`, `sort`, `copyWithin`). Writes through to
1590/// whichever store backs it — the `ArrayBuffer` for a typed array, `@@bytes` for
1591/// a `Buffer`.
1592fn write_elems(recv: &Value, kind: &str, vals: &[Value]) -> Result<(), String> {
1593    if super::native_tag(recv).as_deref() == Some("TypedArray") {
1594        let bpe = bytes_per_element(kind);
1595        let coerced: Vec<Value> = vals
1596            .iter()
1597            .map(|v| coerce_val(kind, v))
1598            .collect::<Result<_, _>>()?;
1599        for (i, v) in coerced.iter().enumerate() {
1600            write_view_bytes(recv, i * bpe, &encode(kind, v));
1601        }
1602        return Ok(());
1603    }
1604    let field = "@@bytes";
1605    // Coerce OUTSIDE the host borrow: `coerce_val` re-enters the host to read a
1606    // BigInt and to allocate the wrapped one.
1607    let coerced: Vec<Value> = vals
1608        .iter()
1609        .map(|v| coerce_val(kind, v))
1610        .collect::<Result<_, _>>()?;
1611    with_host(|h| {
1612        let (arr, off, len) = match h.get(recv) {
1613            Some(JsObj::Object(p)) => {
1614                let (off, len) = super::buffer::window_h(h, p);
1615                (p.get(field).cloned(), off, len)
1616            }
1617            _ => (None, 0, 0),
1618        };
1619        // Through the Buffer's WINDOW: its store is shared with its
1620        // `ArrayBuffer`, so writing from the store's origin clobbers bytes
1621        // that belong to other views.
1622        if let Some(JsObj::Array(items)) = arr.as_ref().and_then(|a| h.get_mut(a)) {
1623            for (i, v) in coerced.into_iter().enumerate().take(len) {
1624                items[off + i] = v;
1625            }
1626        }
1627    });
1628    Ok(())
1629}
1630
1631/// Order `elems` the way `%TypedArray%.prototype.sort` (23.2.3.29) does, with
1632/// `cmp` as the optional user comparator. Shared with `toSorted` (23.2.3.33),
1633/// which is the same ordering over a copy.
1634fn sort_elements(elems: &mut Vec<Value>, kind: &str, cmp: Option<&Value>) -> Result<(), String> {
1635    let cmp = cmp.cloned().unwrap_or(Value::Undef);
1636    if with_host(|h| crate::host::is_callable(h, &cmp)) {
1637        // A user comparator goes through the same fallible merge sort
1638        // `Array.prototype.sort` uses: O(n log n) rather than the insertion sort
1639        // this was, and a comparator returning NaN keeps the pair's order
1640        // (23.2.4.1 step 3: NaN is +0) instead of swapping, which the `<= 0.0`
1641        // break got wrong.
1642        return crate::builtins::sort_values(elems, Some(&cmp));
1643    }
1644    // A typed array sorts NUMERICALLY by default, unlike `Array` which sorts by
1645    // string. Verified against node v26.7.0: `new Uint8Array([10,9,1]).sort()`
1646    // is `1,9,10` while `[10,9,1].sort()` is `1,10,9`.
1647    // A BigInt element cannot be ordered through an `f64` without collapsing
1648    // values more than 2^53 apart, so the 64-bit views compare the integers
1649    // themselves.
1650    if is_bigint_kind(kind) {
1651        let keys: Vec<num_bigint::BigInt> = elems.iter().map(bigint_of).collect();
1652        let mut idx: Vec<usize> = (0..elems.len()).collect();
1653        idx.sort_by(|a, b| keys[*a].cmp(&keys[*b]));
1654        *elems = idx.into_iter().map(|i| elems[i].clone()).collect();
1655    } else {
1656        // 23.2.4.7 TypedArray SortCompare: NaN sorts last and -0 before +0, which
1657        // is `total_cmp` once NaN is taken out (a NaN comparing `Equal` to
1658        // everything made the whole sort order unspecified).
1659        elems.sort_by(|a, b| match (num(a), num(b)) {
1660            (x, y) if x.is_nan() || y.is_nan() => x.is_nan().cmp(&y.is_nan()),
1661            (x, y) => x.total_cmp(&y),
1662        });
1663    }
1664    Ok(())
1665}
1666
1667/// Resolve a relative index argument against `len` (negative counts from the
1668/// end), clamped into range — the `RelativeIndex` coercion the typed-array
1669/// methods share.
1670fn rel_index(args: &[Value], idx: usize, len: usize, default: usize) -> usize {
1671    if args.len() <= idx {
1672        return default;
1673    }
1674    let n = super::arg_num(args, idx);
1675    if n < 0.0 {
1676        (len as f64 + n).max(0.0) as usize
1677    } else {
1678        (n as usize).min(len)
1679    }
1680}
1681
1682/// Typed-array instance methods.
1683/// `toBase64` / `toHex` / `setFromBase64` / `setFromHex` — the `Uint8Array`
1684/// half of the base64/hex proposal. All four are brand-checked to `Uint8Array`:
1685/// every other view, and an ordinary array, is an incompatible receiver.
1686fn base64_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1687    let kind = kind_of(recv);
1688    if kind != "Uint8Array" {
1689        // Node renders a non-view receiver by its brand and a WRONG view as
1690        // `undefined`, which reads oddly but is what it prints.
1691        // A typed array of the WRONG element kind renders as `undefined` here,
1692        // which reads oddly but is what node prints; every other receiver is
1693        // rendered the way the other brand checks render one, and never reaches
1694        // this arm — the dispatcher's guard catches it first.
1695        return Err(crate::host::type_error(&format!(
1696            "Method Uint8Array.prototype.{method} called on incompatible receiver undefined"
1697        )));
1698    }
1699    let bytes: Vec<u8> = elem_values(recv)
1700        .iter()
1701        .map(|v| with_host(|h| h.to_number(v)) as u8)
1702        .collect();
1703    match method {
1704        "toBase64" => {
1705            let (url, _) = base64_options(args.first())?;
1706            let omit = args
1707                .first()
1708                .filter(|v| !matches!(v, Value::Undef))
1709                .map(|o| {
1710                    with_host(|h| match h.get(o) {
1711                        Some(JsObj::Object(p)) => {
1712                            p.get("omitPadding").map(|v| h.truthy(v)).unwrap_or(false)
1713                        }
1714                        _ => false,
1715                    })
1716                })
1717                .unwrap_or(false);
1718            // The url alphabet only swaps the two characters — it does NOT drop
1719            // the padding, which `to_base64url` does for the `atob` callers.
1720            let mut s = super::to_base64(&bytes);
1721            if url {
1722                s = s.replace('+', "-").replace('/', "_");
1723            }
1724            if omit {
1725                s = s.trim_end_matches('=').to_string();
1726            }
1727            Ok(with_host(|h| h.new_str(s)))
1728        }
1729        "toHex" => Ok(with_host(|h| h.new_str(super::to_hex(&bytes)))),
1730        // `setFrom*` writes as much as FITS and reports how far it got, so a
1731        // short target is not an error — it stops at the last whole chunk.
1732        "setFromBase64" | "setFromHex" => {
1733            let s = base64_input(args)?;
1734            let (decoded, read) = if method == "setFromHex" {
1735                let d = decode_hex_strict(&s)?;
1736                let fits = d.len().min(bytes.len());
1737                (d[..fits].to_vec(), fits * 2)
1738            } else {
1739                let (url, last) = base64_options(args.get(1))?;
1740                // Decode only as much as the target can hold: whole 4-character
1741                // chunks, plus the final partial one when it still fits.
1742                let whole = (bytes.len() / 3) * 4;
1743                let head: String = s.chars().take(whole).collect();
1744                let (mut d, mut consumed) = decode_base64_strict(&head, url, last)?;
1745                if d.len() < bytes.len() {
1746                    let (full, full_read) = decode_base64_strict(&s, url, last)?;
1747                    if full.len() <= bytes.len() {
1748                        d = full;
1749                        consumed = full_read;
1750                    }
1751                }
1752                (d, consumed)
1753            };
1754            write_view_bytes(recv, 0, &decoded);
1755            Ok(with_host(|h| {
1756                let mut m = IndexMap::new();
1757                m.insert("read".to_string(), Value::Float(read as f64));
1758                m.insert("written".to_string(), Value::Float(decoded.len() as f64));
1759                h.new_object(m)
1760            }))
1761        }
1762        _ => unreachable!("caller gates the method name"),
1763    }
1764}
1765
1766pub fn instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1767    // Every method over a DETACHED buffer throws, naming itself. An element
1768    // read and `length` answer zero instead, which is why this is a per-method
1769    // guard rather than a check inside the element accessors.
1770    if view_detached(recv) {
1771        return Err(detached_error("%TypedArray%.prototype", method, false));
1772    }
1773    if matches!(
1774        method,
1775        "toBase64" | "toHex" | "setFromBase64" | "setFromHex"
1776    ) {
1777        return base64_instance_call(recv, method, args);
1778    }
1779    let kind = kind_of(recv);
1780    // Elements travel as `Value`, not `f64`: a 64-bit view's are BigInts, and
1781    // rounding them through a double is exactly the loss those views exist to
1782    // avoid. The numeric kinds still hold `Value::Float`, so nothing about them
1783    // changes.
1784    let elems = elem_values(recv);
1785    // The callback-taking methods share one shape: invoke `cb(value, index,
1786    // receiver)` per element. They are inherited by `Buffer` too, which is why
1787    // they must live here rather than in either concrete type.
1788    // `forEach(fn, thisArg)` and its siblings bind `thisArg` as the callback's
1789    // `this`; it was being dropped, so `this` inside the callback was undefined.
1790    let this_arg = args.get(1).filter(|v| !matches!(v, Value::Undef)).cloned();
1791    let call_cb = |i: usize, v: &Value| -> Result<Value, String> {
1792        crate::host::invoke(
1793            &args.first().cloned().unwrap_or(Value::Undef),
1794            vec![v.clone(), Value::Float(i as f64), recv.clone()],
1795            this_arg.clone(),
1796        )
1797    };
1798    match method {
1799        "every" => {
1800            for (i, v) in elems.iter().enumerate() {
1801                let r = call_cb(i, v)?;
1802                if !with_host(|h| h.truthy(&r)) {
1803                    return Ok(Value::Bool(false));
1804                }
1805            }
1806            Ok(Value::Bool(true))
1807        }
1808        "some" => {
1809            for (i, v) in elems.iter().enumerate() {
1810                let r = call_cb(i, v)?;
1811                if with_host(|h| h.truthy(&r)) {
1812                    return Ok(Value::Bool(true));
1813                }
1814            }
1815            Ok(Value::Bool(false))
1816        }
1817        "forEach" => {
1818            for (i, v) in elems.iter().enumerate() {
1819                call_cb(i, v)?;
1820            }
1821            Ok(Value::Undef)
1822        }
1823        "map" => {
1824            let mut out = Vec::with_capacity(elems.len());
1825            for (i, v) in elems.iter().enumerate() {
1826                let r = call_cb(i, v)?;
1827                out.push(coerce_val(&kind, &r)?);
1828            }
1829            Ok(species(recv, &kind, out))
1830        }
1831        "filter" => {
1832            let mut out = Vec::new();
1833            for (i, v) in elems.iter().enumerate() {
1834                let r = call_cb(i, v)?;
1835                if with_host(|h| h.truthy(&r)) {
1836                    out.push(v.clone());
1837                }
1838            }
1839            Ok(species(recv, &kind, out))
1840        }
1841        "find" | "findIndex" | "findLast" | "findLastIndex" => {
1842            let last = method.starts_with("findLast");
1843            let idxs: Vec<usize> = if last {
1844                (0..elems.len()).rev().collect()
1845            } else {
1846                (0..elems.len()).collect()
1847            };
1848            for i in idxs {
1849                let r = call_cb(i, &elems[i])?;
1850                if with_host(|h| h.truthy(&r)) {
1851                    return Ok(if method.ends_with("Index") {
1852                        Value::Float(i as f64)
1853                    } else {
1854                        elems[i].clone()
1855                    });
1856                }
1857            }
1858            Ok(if method.ends_with("Index") {
1859                Value::Float(-1.0)
1860            } else {
1861                Value::Undef
1862            })
1863        }
1864        "reduce" | "reduceRight" => {
1865            let right = method == "reduceRight";
1866            let order: Vec<usize> = if right {
1867                (0..elems.len()).rev().collect()
1868            } else {
1869                (0..elems.len()).collect()
1870            };
1871            let cb = args.first().cloned().unwrap_or(Value::Undef);
1872            let mut it = order.into_iter();
1873            let mut acc = if args.len() >= 2 {
1874                args[1].clone()
1875            } else {
1876                match it.next() {
1877                    Some(i) => elems[i].clone(),
1878                    None => {
1879                        return Err(crate::host::type_error(
1880                            "Reduce of empty array with no initial value",
1881                        ))
1882                    }
1883                }
1884            };
1885            for i in it {
1886                acc = crate::host::invoke(
1887                    &cb,
1888                    vec![acc, elems[i].clone(), Value::Float(i as f64), recv.clone()],
1889                    None,
1890                )?;
1891            }
1892            Ok(acc)
1893        }
1894        "reverse" => {
1895            let mut out = elems.clone();
1896            out.reverse();
1897            write_elems(recv, &kind, &out)?;
1898            Ok(recv.clone())
1899        }
1900        "sort" => {
1901            let mut out = elems.clone();
1902            sort_elements(&mut out, &kind, args.first())?;
1903            write_elems(recv, &kind, &out)?;
1904            Ok(recv.clone())
1905        }
1906        "copyWithin" => {
1907            let len = elems.len();
1908            let target = rel_index(args, 0, len, 0);
1909            let start = rel_index(args, 1, len, 0);
1910            let end = rel_index(args, 2, len, len);
1911            let src: Vec<Value> = elems[start.min(end)..end.max(start)].to_vec();
1912            let mut out = elems.clone();
1913            for (k, v) in src.iter().enumerate() {
1914                if target + k < len {
1915                    out[target + k] = v.clone();
1916                }
1917            }
1918            write_elems(recv, &kind, &out)?;
1919            Ok(recv.clone())
1920        }
1921        "at" => {
1922            let n = super::arg_num(args, 0);
1923            let i = if n < 0.0 { elems.len() as f64 + n } else { n };
1924            if i < 0.0 || i >= elems.len() as f64 {
1925                return Ok(Value::Undef);
1926            }
1927            Ok(elems[i as usize].clone())
1928        }
1929        "lastIndexOf" => {
1930            let needle = args.first().cloned().unwrap_or(Value::Undef);
1931            let from = (args.len() > 1).then(|| super::arg_num(args, 1));
1932            let found = crate::builtins::search_start_last(from, elems.len()).and_then(|start| {
1933                elems[..=start]
1934                    .iter()
1935                    .rposition(|x| same_element(x, &needle, false))
1936            });
1937            Ok(Value::Float(found.map(|p| p as f64).unwrap_or(-1.0)))
1938        }
1939        // `%TypedArray%.prototype[Symbol.iterator]` IS `values` (23.2.3.35), so
1940        // it dispatches here rather than reporting itself missing:
1941        // `Uint8Array.prototype[Symbol.iterator].call(ta)` threw
1942        // `@@iterator is not a function`.
1943        "keys" | "values" | "entries" | "@@iterator" => {
1944            let items: Vec<Value> = with_host(|h| match method {
1945                "keys" => (0..elems.len()).map(|i| Value::Float(i as f64)).collect(),
1946                "values" | "@@iterator" => elems.clone(),
1947                _ => elems
1948                    .iter()
1949                    .enumerate()
1950                    .map(|(i, v)| h.new_array(vec![Value::Float(i as f64), v.clone()]))
1951                    .collect(),
1952            });
1953            Ok(with_host(|h| {
1954                h.alloc_iter(JsObj::Iter {
1955                    items,
1956                    idx: 0,
1957                    array: None,
1958                    brand: Some("Array Iterator"),
1959                })
1960            }))
1961        }
1962        "toString" | "join" => {
1963            let sep = if method == "join" && !args.is_empty() {
1964                super::arg_str(args, 0)
1965            } else {
1966                ",".into()
1967            };
1968            let parts: Vec<String> = with_host(|h| elems.iter().map(|n| h.str_of(n)).collect());
1969            Ok(with_host(|h| h.new_str(parts.join(&sep))))
1970        }
1971        "slice" | "subarray" => {
1972            let len = elems.len();
1973            let norm = |n: f64| -> usize {
1974                if n < 0.0 {
1975                    (len as f64 + n).max(0.0) as usize
1976                } else {
1977                    (n as usize).min(len)
1978                }
1979            };
1980            let s = if args.is_empty() {
1981                0
1982            } else {
1983                norm(super::arg_num(args, 0))
1984            };
1985            let e = if args.len() < 2 {
1986                len
1987            } else {
1988                norm(super::arg_num(args, 1))
1989            };
1990            let (lo, hi) = (s.min(e), e.max(s));
1991            // 23.2.3.30: `subarray` is a VIEW over the same buffer — writes
1992            // through it are seen by the original. `slice` copies (23.2.3.27).
1993            if method == "subarray" && super::native_tag(recv).as_deref() == Some("TypedArray") {
1994                if let Some((buf, off)) = view_base(recv) {
1995                    let bpe = bytes_per_element(&kind);
1996                    return Ok(make_view(&kind, &buf, off + lo * bpe, hi - lo));
1997                }
1998            }
1999            Ok(species(recv, &kind, elems[lo..hi].to_vec()))
2000        }
2001        "indexOf" => {
2002            let needle = args.first().cloned().unwrap_or(Value::Undef);
2003            let start = crate::builtins::search_start(super::arg_num(args, 1), elems.len());
2004            Ok(Value::Float(
2005                elems
2006                    .iter()
2007                    .skip(start)
2008                    .position(|x| same_element(x, &needle, false))
2009                    .map(|p| (p + start) as f64)
2010                    .unwrap_or(-1.0),
2011            ))
2012        }
2013        "includes" => {
2014            let needle = args.first().cloned().unwrap_or(Value::Undef);
2015            let start = crate::builtins::search_start(super::arg_num(args, 1), elems.len());
2016            Ok(Value::Bool(
2017                elems
2018                    .iter()
2019                    .skip(start)
2020                    .any(|x| same_element(x, &needle, true)),
2021            ))
2022        }
2023        // 23.2.3.9: `fill` writes THROUGH the view and answers the receiver. It
2024        // was building a fresh array instead, so the write was invisible —
2025        // `u.fill(9)` left `u` untouched, `u.fill(9) === u` was false, and a
2026        // second view onto the same `ArrayBuffer` saw none of it. The `start`
2027        // and `end` arguments were dropped too, so `fill(9, 1, 2)` overwrote the
2028        // whole array rather than one element.
2029        "fill" => {
2030            let len = elems.len();
2031            let v = coerce_val(&kind, args.first().unwrap_or(&Value::Undef))?;
2032            let start = rel_index(args, 1, len, 0);
2033            let end = rel_index(args, 2, len, len);
2034            let mut out = elems.clone();
2035            for slot in out.iter_mut().take(end).skip(start) {
2036                *slot = v.clone();
2037            }
2038            write_elems(recv, &kind, &out)?;
2039            Ok(recv.clone())
2040        }
2041        // The change-by-copy trio (23.2.3.32-34). Each answers a NEW view of the
2042        // receiver's own element kind — `TypedArrayCreateSameType`, not the
2043        // species path — so a `Buffer` receiver yields a `Uint8Array`, which is
2044        // what node reports.
2045        "toReversed" | "toSorted" => {
2046            let mut out = elems.clone();
2047            if method == "toReversed" {
2048                out.reverse();
2049            } else {
2050                sort_elements(&mut out, &kind, args.first())?;
2051            }
2052            Ok(make(&kind, out))
2053        }
2054        "with" => {
2055            let len = elems.len();
2056            let n = super::arg_num(args, 0);
2057            let i = if n < 0.0 { len as f64 + n } else { n };
2058            if !(0.0..len as f64).contains(&i) {
2059                return Err("RangeError: Invalid typed array index".into());
2060            }
2061            let mut out = elems.clone();
2062            out[i as usize] = coerce_val(&kind, args.get(1).unwrap_or(&Value::Undef))?;
2063            Ok(make(&kind, out))
2064        }
2065        "set" => {
2066            // `ta.set(src[, offset])` — write `src`'s values in place.
2067            let src = set_source(args.first());
2068            // 23.2.3.26: a negative offset, or a source that runs past the
2069            // end, is a RangeError. Neither may write a partial prefix.
2070            let off = super::arg_num(args, 1);
2071            let off = if off.is_nan() { 0.0 } else { off.trunc() };
2072            if off < 0.0 || off + src.len() as f64 > view_len(recv) as f64 {
2073                return Err(crate::host::range_error("offset is out of bounds"));
2074            }
2075            let off = off as usize;
2076            // Coerced outside the host borrow: a 64-bit element allocates.
2077            let src: Vec<Value> = src
2078                .iter()
2079                .map(|v| coerce_val(&kind, v))
2080                .collect::<Result<_, _>>()?;
2081            let bpe = bytes_per_element(&kind);
2082            let len = view_len(recv);
2083            for (k, v) in src.into_iter().enumerate() {
2084                if off + k < len {
2085                    write_view_bytes(recv, (off + k) * bpe, &encode(&kind, &v));
2086                }
2087            }
2088            Ok(Value::Undef)
2089        }
2090        _ => Err(crate::host::type_error(&format!(
2091            "{method} is not a function"
2092        ))),
2093    }
2094}
2095
2096/// The values `ta.set(source)` writes, before element coercion: a typed array's
2097/// (or Buffer's) elements, else the source's iterated or array-like items. A
2098/// `Buffer` receiver shares this — it read a non-Buffer source as zero bytes.
2099pub fn set_source(arg: Option<&Value>) -> Vec<Value> {
2100    let arg = arg.cloned().unwrap_or(Value::Undef);
2101    match super::native_tag(&arg).as_deref() {
2102        Some("TypedArray") | Some("Buffer") => elem_values(&arg),
2103        _ => {
2104            crate::host::iter_all(&arg).unwrap_or_else(|_| crate::builtins::array_like_items(&arg))
2105        }
2106    }
2107}
2108
2109/// [`set_source`] coerced to `Uint8` elements, for a `Buffer` receiver.
2110pub fn set_source_bytes(arg: Option<&Value>) -> Result<Vec<u8>, String> {
2111    set_source(arg)
2112        .iter()
2113        .map(|v| coerce_val("Uint8Array", v).map(|e| with_host(|h| h.to_number(&e)) as u8))
2114        .collect()
2115}
2116
2117// ── WeakRef (strong-ref approximation) ────────────────────────────────────────
2118
2119pub fn construct_weakref(args: &[Value]) -> Result<Value, String> {
2120    let target = args.first().cloned().unwrap_or(Value::Undef);
2121    Ok(with_host(|h| {
2122        let mut m = IndexMap::new();
2123        m.insert("@@native".into(), h.new_str("WeakRef"));
2124        m.insert("@@target".into(), target);
2125        h.new_object(m)
2126    }))
2127}
2128
2129pub fn weakref_call(recv: &Value, method: &str) -> Result<Value, String> {
2130    match method {
2131        "deref" => Ok(with_host(|h| match h.get(recv) {
2132            Some(JsObj::Object(p)) => p.get("@@target").cloned().unwrap_or(Value::Undef),
2133            _ => Value::Undef,
2134        })),
2135        _ => Err(crate::host::type_error(&format!(
2136            "{method} is not a function"
2137        ))),
2138    }
2139}
2140
2141// ── FinalizationRegistry (no-GC approximation) ────────────────────────────────
2142//
2143// This VM holds every value strongly (see `WeakRef` above), so a registered
2144// target is never reclaimed and the cleanup callback never fires. The ECMAScript
2145// spec permits an implementation to never call cleanup callbacks, so this is a
2146// conformant approximation: the constructor and `register`/`unregister` enforce
2147// their type checks and `unregister`'s bookkeeping exactly, only the (optional)
2148// callback invocation is absent. Registered unregister-tokens are tracked in a
2149// hidden `@@fr_tokens` array so `unregister` returns the correct boolean.
2150
2151/// Whether `v` is an Object (a valid `register` target / unregister token) — a
2152/// heap value that is not one of the primitive-wrapper heap variants.
2153fn is_object_value(v: &Value) -> bool {
2154    matches!(v, Value::Obj(_))
2155        && with_host(|h| {
2156            !matches!(
2157                h.get(v),
2158                Some(JsObj::Str(_))
2159                    | Some(JsObj::Symbol { .. })
2160                    | Some(JsObj::BigInt(_))
2161                    | Some(JsObj::Null)
2162            )
2163        })
2164}
2165
2166pub fn construct_finalization_registry(args: &[Value]) -> Result<Value, String> {
2167    let cb = args.first().cloned().unwrap_or(Value::Undef);
2168    if !with_host(|h| crate::host::is_callable(h, &cb)) {
2169        return Err(crate::host::type_error(
2170            "FinalizationRegistry: cleanup must be callable",
2171        ));
2172    }
2173    Ok(with_host(|h| {
2174        let tokens = h.new_array(Vec::new());
2175        let mut m = IndexMap::new();
2176        m.insert("@@native".into(), h.new_str("FinalizationRegistry"));
2177        m.insert("@@fr_cb".into(), cb);
2178        m.insert("@@fr_tokens".into(), tokens);
2179        h.new_object(m)
2180    }))
2181}
2182
2183pub fn finalization_registry_call(
2184    recv: &Value,
2185    method: &str,
2186    args: &[Value],
2187) -> Result<Value, String> {
2188    match method {
2189        "register" => {
2190            let target = args.first().cloned().unwrap_or(Value::Undef);
2191            let held = args.get(1).cloned().unwrap_or(Value::Undef);
2192            let token = args.get(2).cloned().unwrap_or(Value::Undef);
2193            if !is_object_value(&target) {
2194                // V8's wording is `invalid target`; the "must be an object"
2195                // phrasing was this file's own, not any engine's.
2196                return Err(crate::host::type_error(
2197                    "FinalizationRegistry.prototype.register: invalid target",
2198                ));
2199            }
2200            if with_host(|h| h.strict_eq(&target, &held)) {
2201                return Err(crate::host::type_error(
2202                    "FinalizationRegistry.prototype.register: target and holdings must not be same",
2203                ));
2204            }
2205            // A supplied unregister token must be an object; record it so a later
2206            // `unregister` can find (and drop) this registration.
2207            if !matches!(token, Value::Undef) {
2208                if !is_object_value(&token) {
2209                    return Err(crate::host::type_error(&format!(
2210                        "Invalid unregisterToken ('{}')",
2211                        with_host(|h| h.str_of(&token))
2212                    )));
2213                }
2214                with_host(|h| {
2215                    let toks = registry_tokens(h, recv);
2216                    if let Some(JsObj::Array(items)) = h.get_mut(&toks) {
2217                        items.push(token);
2218                    }
2219                });
2220            }
2221            Ok(Value::Undef)
2222        }
2223        "unregister" => {
2224            let token = args.first().cloned().unwrap_or(Value::Undef);
2225            if !is_object_value(&token) {
2226                // V8 names the token and does not mention the method.
2227                return Err(crate::host::type_error(&format!(
2228                    "Invalid unregisterToken ('{}')",
2229                    with_host(|h| h.str_of(&token))
2230                )));
2231            }
2232            Ok(Value::Bool(with_host(|h| {
2233                let toks = registry_tokens(h, recv);
2234                let kept: Vec<Value> = match h.get(&toks) {
2235                    Some(JsObj::Array(items)) => items
2236                        .iter()
2237                        .filter(|t| !h.strict_eq(t, &token))
2238                        .cloned()
2239                        .collect(),
2240                    _ => Vec::new(),
2241                };
2242                let removed = match h.get(&toks) {
2243                    Some(JsObj::Array(items)) => items.len() != kept.len(),
2244                    _ => false,
2245                };
2246                if let Some(JsObj::Array(items)) = h.get_mut(&toks) {
2247                    *items = kept;
2248                }
2249                removed
2250            })))
2251        }
2252        _ => Err(crate::host::type_error(&format!(
2253            "{method} is not a function"
2254        ))),
2255    }
2256}
2257
2258/// The hidden `@@fr_tokens` array backing a `FinalizationRegistry`.
2259fn registry_tokens(h: &crate::host::JsHost, recv: &Value) -> Value {
2260    match h.get(recv) {
2261        Some(JsObj::Object(p)) => p.get("@@fr_tokens").cloned().unwrap_or(Value::Undef),
2262        _ => Value::Undef,
2263    }
2264}
2265
2266// ── TextEncoder / TextDecoder ─────────────────────────────────────────────────
2267
2268pub fn construct_text_encoder() -> Result<Value, String> {
2269    Ok(with_host(|h| {
2270        let mut m = IndexMap::new();
2271        m.insert("@@native".into(), h.new_str("TextEncoder"));
2272        // `encoding` is a getter on the prototype, so the value lives in the
2273        // hidden slot the getter reads. As an own property it enumerated —
2274        // `Object.keys(new TextEncoder())` answered `["encoding"]` where node
2275        // answers `[]`, and `JSON.stringify` of anything holding one carried it.
2276        m.insert("@@encoding".into(), h.new_str("utf-8"));
2277        h.new_object(m)
2278    }))
2279}
2280
2281pub fn text_encoder_call(_recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
2282    match method {
2283        // `encode(str)` → a Uint8Array of the UTF-8 bytes.
2284        // `encode(input = '')`: an absent or `undefined` input is the empty
2285        // string (it encoded the text "undefined"), anything else is
2286        // `ToString`ed — a `toString` runs and a symbol throws.
2287        "encode" => {
2288            let s = match args.first() {
2289                None | Some(Value::Undef) => String::new(),
2290                Some(v) => {
2291                    let s = crate::host::to_string_value(v)?;
2292                    with_host(|h| h.str_of(&s))
2293                }
2294            };
2295            Ok(make(
2296                "Uint8Array",
2297                s.as_bytes()
2298                    .iter()
2299                    .map(|b| Value::Float(*b as f64))
2300                    .collect(),
2301            ))
2302        }
2303        // `encodeInto(src, dest)`: the UTF-8 of as many WHOLE characters of
2304        // `src` as fit in `dest`, written in place; `{read, written}` counts
2305        // UTF-16 code units consumed and bytes produced. It was absent.
2306        "encodeInto" => {
2307            let src = args.first().cloned().unwrap_or(Value::Undef);
2308            let Some(s) = with_host(|h| h.as_str(&src)) else {
2309                return Err(crate::host::invalid_arg_type(
2310                    "src", "argument", "string", &src,
2311                ));
2312            };
2313            let dest = args.get(1).cloned().unwrap_or(Value::Undef);
2314            if super::util_types::ta_kind(&dest).as_deref() != Some("Uint8Array") {
2315                return Err(crate::host::coded_error(
2316                    "TypeError",
2317                    "ERR_INVALID_ARG_TYPE",
2318                    &format!(
2319                        "The \"dest\" argument must be an instance of Uint8Array. Received {}",
2320                        super::received_desc(&dest)
2321                    ),
2322                ));
2323            }
2324            let mut out = super::buffer::view_bytes(&dest).unwrap_or_default();
2325            let (mut read, mut written) = (0, 0);
2326            for c in s.chars() {
2327                let n = c.len_utf8();
2328                if written + n > out.len() {
2329                    break;
2330                }
2331                c.encode_utf8(&mut out[written..written + n]);
2332                written += n;
2333                read += c.len_utf16();
2334            }
2335            super::buffer::write_view(&dest, &out);
2336            Ok(with_host(|h| {
2337                let mut m = IndexMap::new();
2338                m.insert("read".into(), Value::Float(read as f64));
2339                m.insert("written".into(), Value::Float(written as f64));
2340                h.new_object(m)
2341            }))
2342        }
2343        _ => Err(crate::host::type_error(&format!(
2344            "{method} is not a function"
2345        ))),
2346    }
2347}
2348
2349/// The WHATWG encoding a label names, as node reports it through
2350/// `decoder.encoding`. The label is NOT the encoding: `latin1`, `ascii` and
2351/// `iso-8859-1` all name `windows-1252`, and `ucs-2` names `utf-16le`. This
2352/// echoed the label back, so `new TextDecoder("latin1").encoding` read
2353/// `"latin1"` — a name node never reports — and an unknown label was accepted
2354/// and then decoded as UTF-8.
2355fn encoding_for_label(label: &str) -> Option<&'static str> {
2356    Some(match label.trim().to_ascii_lowercase().as_str() {
2357        "utf-8" | "utf8" | "unicode-1-1-utf-8" | "unicode11utf8" | "unicode20utf8"
2358        | "x-unicode20utf8" => "utf-8",
2359        "latin1" | "iso-8859-1" | "iso8859-1" | "iso88591" | "ascii" | "us-ascii" | "cp1252"
2360        | "cp819" | "ibm819" | "l1" | "windows-1252" | "x-cp1252" => "windows-1252",
2361        "utf-16le" | "utf-16" | "ucs-2" | "ucs2" | "unicodefeff" | "unicodefffe"
2362        | "iso-10646-ucs-2" | "csunicode" => "utf-16le",
2363        _ => return None,
2364    })
2365}
2366
2367pub fn construct_text_decoder(args: &[Value]) -> Result<Value, String> {
2368    let label = if args.is_empty() || matches!(args[0], Value::Undef) {
2369        "utf-8".to_string()
2370    } else {
2371        super::arg_str(args, 0)
2372    };
2373    let Some(encoding) = encoding_for_label(&label) else {
2374        return Err(crate::host::coded_error(
2375            "RangeError",
2376            "ERR_ENCODING_NOT_SUPPORTED",
2377            &format!("The \"{label}\" encoding is not supported"),
2378        ));
2379    };
2380    // `fatal` and `ignoreBOM` were not read at all, so a decoder asked to reject
2381    // malformed input accepted it and one asked to keep the BOM never saw one —
2382    // both options silently did nothing.
2383    let flag = |key: &str| {
2384        args.get(1)
2385            .map(|o| crate::builtins::get_property(o, key).unwrap_or(Value::Undef))
2386            .map(|v| with_host(|h| h.truthy(&v)))
2387            .unwrap_or(false)
2388    };
2389    let (fatal, ignore_bom) = (flag("fatal"), flag("ignoreBOM"));
2390    Ok(with_host(|h| {
2391        let mut m = IndexMap::new();
2392        m.insert("@@native".into(), h.new_str("TextDecoder"));
2393        m.insert("@@encoding".into(), h.new_str(encoding.to_string()));
2394        m.insert("@@fatal".into(), Value::Bool(fatal));
2395        m.insert("@@ignoreBOM".into(), Value::Bool(ignore_bom));
2396        h.new_object(m)
2397    }))
2398}
2399
2400/// windows-1252's 0x80..=0x9F range, which is NOT latin1's: those 32 positions
2401/// carry the typographic characters (curly quotes, the euro sign, the dashes)
2402/// rather than C1 control codes. Decoding them as latin1 — `b as char`, what
2403/// this did — turned every smart quote in a Windows-encoded file into a control
2404/// character.
2405const CP1252_HIGH: [char; 32] = [
2406    '\u{20ac}', '\u{81}', '\u{201a}', '\u{192}', '\u{201e}', '\u{2026}', '\u{2020}', '\u{2021}',
2407    '\u{2c6}', '\u{2030}', '\u{160}', '\u{2039}', '\u{152}', '\u{8d}', '\u{17d}', '\u{8f}',
2408    '\u{90}', '\u{2018}', '\u{2019}', '\u{201c}', '\u{201d}', '\u{2022}', '\u{2013}', '\u{2014}',
2409    '\u{2dc}', '\u{2122}', '\u{161}', '\u{203a}', '\u{153}', '\u{9d}', '\u{17e}', '\u{178}',
2410];
2411
2412/// How many trailing bytes of `bytes` are an INCOMPLETE sequence in `enc` — a
2413/// prefix of a character the next streamed chunk may finish. For UTF-8 that is
2414/// a valid lead byte followed by fewer continuation bytes than it announces;
2415/// for UTF-16LE an odd final byte. A malformed tail is not incomplete: it is
2416/// decoded (or rejected) now.
2417fn incomplete_tail(bytes: &[u8], enc: &str) -> usize {
2418    match enc {
2419        "utf-16le" => bytes.len() % 2,
2420        "utf-8" => match std::str::from_utf8(bytes) {
2421            Err(e) if e.error_len().is_none() => bytes.len() - e.valid_up_to(),
2422            _ => 0,
2423        },
2424        _ => 0,
2425    }
2426}
2427pub fn text_decoder_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
2428    match method {
2429        // `decode(bytes)` → a string from the buffer's UTF-8 (or latin1) bytes.
2430        "decode" => {
2431            // The input is a BufferSource — any byte view or an ArrayBuffer —
2432            // read as the BYTES it views. It used to be the element values of a
2433            // typed array only, so a `Uint16Array` decoded its truncated
2434            // elements and an `ArrayBuffer` or `DataView` decoded as "".
2435            let input = args.first().cloned().unwrap_or(Value::Undef);
2436            let fresh = match &input {
2437                Value::Undef => Vec::new(),
2438                v => super::buffer::view_bytes(v).ok_or_else(|| {
2439                    crate::host::coded_error(
2440                        "TypeError",
2441                        "ERR_INVALID_ARG_TYPE",
2442                        "The \"list\" argument must be an instance of SharedArrayBuffer, \
2443                         ArrayBuffer or ArrayBufferView.",
2444                    )
2445                })?,
2446            };
2447            let stream = args
2448                .get(1)
2449                .map(|o| crate::builtins::get_property(o, "stream").unwrap_or(Value::Undef))
2450                .is_some_and(|v| with_host(|h| h.truthy(&v)));
2451            let slot = |key: &str| {
2452                with_host(|h| match h.get(recv) {
2453                    Some(JsObj::Object(p)) => p.get(key).cloned(),
2454                    _ => None,
2455                })
2456            };
2457            let enc = slot("@@encoding")
2458                .map(|v| with_host(|h| h.str_of(&v)))
2459                .unwrap_or_else(|| "utf-8".into());
2460            let flag = |key: &str| matches!(slot(key), Some(Value::Bool(true)));
2461            // `{stream: true}` holds back an incomplete trailing sequence for the
2462            // next call (WHATWG "do not flush"); the bytes it held last time go
2463            // in front of this chunk. Without it a character split across two
2464            // chunks decoded as two U+FFFD.
2465            let mut bytes: Vec<u8> = slot("@@pending")
2466                .map(|v| {
2467                    with_host(|h| h.str_of(&v))
2468                        .chars()
2469                        .map(|c| c as u8)
2470                        .collect()
2471                })
2472                .unwrap_or_default();
2473            bytes.extend(fresh);
2474            let keep = if stream {
2475                incomplete_tail(&bytes, &enc)
2476            } else {
2477                0
2478            };
2479            let held: String = bytes
2480                .split_off(bytes.len() - keep)
2481                .iter()
2482                .map(|b| *b as char)
2483                .collect();
2484            // The BOM is stripped only at the START of a stream, so remember
2485            // whether this call continues one.
2486            let continuing = flag("@@streaming");
2487            with_host(|h| {
2488                let held = h.new_str(held);
2489                if let Some(JsObj::Object(p)) = h.get_mut(recv) {
2490                    p.insert("@@pending".into(), held);
2491                    p.insert("@@streaming".into(), Value::Bool(stream));
2492                }
2493            });
2494            let s = match enc.as_str() {
2495                "windows-1252" => bytes
2496                    .iter()
2497                    .map(|b| match b {
2498                        0x80..=0x9f => CP1252_HIGH[(b - 0x80) as usize],
2499                        _ => *b as char,
2500                    })
2501                    .collect(),
2502                "utf-16le" => {
2503                    let units: Vec<u16> = bytes
2504                        .chunks_exact(2)
2505                        .map(|c| u16::from_le_bytes([c[0], c[1]]))
2506                        .collect();
2507                    String::from_utf16_lossy(&units)
2508                }
2509                // A `fatal` decoder REJECTS malformed input rather than
2510                // substituting U+FFFD. Both behaved as the lossy form, so bytes
2511                // that are not valid UTF-8 came back as replacement characters
2512                // from a decoder built to refuse them.
2513                _ if flag("@@fatal") => match std::str::from_utf8(&bytes) {
2514                    Ok(s) => s.to_string(),
2515                    Err(_) => {
2516                        return Err(crate::host::coded_error(
2517                            "TypeError",
2518                            "ERR_ENCODING_INVALID_ENCODED_DATA",
2519                            &format!("The encoded data was not valid for encoding {enc}"),
2520                        ))
2521                    }
2522                },
2523                _ => String::from_utf8_lossy(&bytes).into_owned(),
2524            };
2525            // A leading BOM is REMOVED unless `ignoreBOM` asked to keep it.
2526            let s = match s.strip_prefix('\u{feff}') {
2527                Some(rest) if !continuing && !flag("@@ignoreBOM") => rest.to_string(),
2528                _ => s,
2529            };
2530            Ok(with_host(|h| h.new_str(s)))
2531        }
2532        _ => Err(crate::host::type_error(&format!(
2533            "{method} is not a function"
2534        ))),
2535    }
2536}