Skip to main content

quickjs/builtins/
typedarray.rs

1//! `ArrayBuffer` and the typed-array views.
2//!
3//! # A view, not a copy
4//!
5//! A typed array is a *window* onto an `ArrayBuffer`'s bytes: `new Float32Array(buffer, 8, 1)`
6//! shares storage with `new Uint8Array(buffer)`, so a write through one is visible through
7//! the other. That is the whole point of the type — it is how a script reinterprets a byte
8//! range as numbers — and it is why the bytes live in the buffer object rather than in each
9//! view. The views hold a `Gc<JsObject>` of their buffer rather than an `Rc` of its storage,
10//! so the collector can see the reference and the buffer cannot be freed while a view lives.
11//!
12//! # Coercion on write
13//!
14//! Every store runs `ToNumber` and then the type's own conversion. The interesting cases are
15//! two:
16//!
17//! - an integer type *wraps*, so `new Int8Array(1)[0] = 255` reads back `-1`;
18//! - `Uint8ClampedArray` *clamps* instead, so `-100` becomes `0` and `1233.5` becomes `255`,
19//!   and it rounds to nearest-even rather than truncating (`0.5` becomes `0`, `1.5` becomes
20//!   `2`).
21//!
22//! # `Float16`
23//!
24//! Rust has no half-precision type, so the encoding is done by hand. It only has to be exact
25//! enough to round-trip the values a script stores; the code below is the standard
26//! round-to-nearest-even conversion with subnormals, infinities and `NaN` handled.
27//!
28//! # Detached buffers
29//!
30//! `ArrayBuffer.prototype.transfer()` hands the bytes to a new buffer and leaves this one
31//! detached. A view of a detached buffer reads `undefined` from every index and reports a
32//! length of `0`, which is what the reference does; the storage stays behind the `Rc` so all
33//! the views see the transition at once.
34
35use crate::builtins::{arg, define_method, install_species_accessor, install_tag};
36use crate::interp::{Interp, JsResult};
37use crate::object::{BufferStorage, JsObject, Property, ViewLength};
38use crate::value::Value;
39use js_gc::Gc;
40use std::cell::RefCell;
41use std::rc::Rc;
42
43/// Which element type a view reads and writes.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ElementType {
46    /// `Int8Array`
47    Int8,
48    /// `Uint8Array`
49    Uint8,
50    /// `Uint8ClampedArray`
51    Uint8Clamped,
52    /// `Int16Array`
53    Int16,
54    /// `Uint16Array`
55    Uint16,
56    /// `Int32Array`
57    Int32,
58    /// `Uint32Array`
59    Uint32,
60    /// `Float16Array`
61    Float16,
62    /// `Float32Array`
63    Float32,
64    /// `Float64Array`
65    Float64,
66    /// `BigInt64Array`
67    BigInt64,
68    /// `BigUint64Array`
69    BigUint64,
70}
71
72/// The view types, in the order their prototypes are installed.
73pub const ELEMENT_TYPES: [(ElementType, &str); 12] = [
74    (ElementType::Int8, "Int8Array"),
75    (ElementType::Uint8, "Uint8Array"),
76    (ElementType::Uint8Clamped, "Uint8ClampedArray"),
77    (ElementType::Int16, "Int16Array"),
78    (ElementType::Uint16, "Uint16Array"),
79    (ElementType::Int32, "Int32Array"),
80    (ElementType::Uint32, "Uint32Array"),
81    (ElementType::Float16, "Float16Array"),
82    (ElementType::Float32, "Float32Array"),
83    (ElementType::Float64, "Float64Array"),
84    (ElementType::BigInt64, "BigInt64Array"),
85    (ElementType::BigUint64, "BigUint64Array"),
86];
87
88impl ElementType {
89    /// Bytes per element.
90    pub fn size(self) -> usize {
91        match self {
92            ElementType::Int8 | ElementType::Uint8 | ElementType::Uint8Clamped => 1,
93            ElementType::Int16 | ElementType::Uint16 | ElementType::Float16 => 2,
94            ElementType::Int32 | ElementType::Uint32 | ElementType::Float32 => 4,
95            ElementType::Float64 | ElementType::BigInt64 | ElementType::BigUint64 => 8,
96        }
97    }
98
99    /// Whether elements are `BigInt`s rather than numbers.
100    ///
101    /// The two behave differently in ways that reach most methods: the sort order, what a
102    /// literal element converts to, and whether a Number is a `TypeError`.
103    pub fn is_bigint(self) -> bool {
104        matches!(self, ElementType::BigInt64 | ElementType::BigUint64)
105    }
106
107    /// The name, as `Symbol.toStringTag` and the class tag report it.
108    pub fn name(self) -> &'static str {
109        ELEMENT_TYPES
110            .into_iter()
111            .find(|(kind, _)| *kind == self)
112            .map(|(_, name)| name)
113            .unwrap_or("TypedArray")
114    }
115
116    /// Read the element at `offset`.
117    ///
118    /// A short buffer — only reachable if a view was built over a truncated one — reads as
119    /// `0` rather than panicking, because a script must not be able to make the engine abort.
120    pub fn read(self, heap: &js_gc::Heap, bytes: &[u8], offset: usize) -> Value {
121        let slice = bytes.get(offset..offset + self.size());
122        let Some(slice) = slice else {
123            // A short buffer reads as the type's zero, which for a BigInt type is `0n`.
124            return match self {
125                ElementType::BigInt64 | ElementType::BigUint64 => {
126                    Value::BigInt(js_gc::Gc::new(heap, crate::bigint::BigInt::zero()))
127                }
128                _ => Value::Int(0),
129            };
130        };
131        match self {
132            ElementType::Int8 => Value::Int(slice[0] as i8 as i32),
133            ElementType::Uint8 | ElementType::Uint8Clamped => Value::Int(slice[0] as i32),
134            ElementType::Int16 => Value::Int(i16::from_le_bytes([slice[0], slice[1]]) as i32),
135            ElementType::Uint16 => Value::Int(u16::from_le_bytes([slice[0], slice[1]]) as i32),
136            ElementType::Int32 => {
137                Value::Int(i32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
138            }
139            // An unsigned 32-bit value does not fit `i32`, so it becomes a float. The
140            // reference keeps it a number too, and the value is exact in an `f64`.
141            ElementType::Uint32 => {
142                Value::Float(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as f64)
143            }
144            ElementType::Float16 => {
145                Value::Float(f16_to_f64(u16::from_le_bytes([slice[0], slice[1]])))
146            }
147            ElementType::Float32 => {
148                Value::Float(f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as f64)
149            }
150            ElementType::Float64 => Value::Float(f64::from_le_bytes([
151                slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
152            ])),
153            // A BigInt element reads back as a `BigInt`, never as a number: `typeof
154            // new BigInt64Array(1)[0]` is `"bigint"` and `0n`, not `0`.
155            ElementType::BigInt64 => Value::BigInt(js_gc::Gc::new(
156                heap,
157                crate::bigint::BigInt::from_i64(i64::from_le_bytes([
158                    slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
159                ])),
160            )),
161            ElementType::BigUint64 => Value::BigInt(js_gc::Gc::new(
162                heap,
163                crate::bigint::BigInt::from_u64(u64::from_le_bytes([
164                    slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
165                ])),
166            )),
167        }
168    }
169
170    /// Store `value` into the element at `offset`.
171    ///
172    /// `value` must already be the primitive this element type stores — a number for the
173    /// numeric types, a BigInt for the two `BigInt` ones. [`write_element`] is what
174    /// applies `ToNumber`/`ToBigInt` beforehand, because both can run script (`valueOf`)
175    /// and the storage borrow must not be held across that.
176    ///
177    /// The `Err` carries the reason, which the caller turns into a `TypeError`.
178    pub fn write(self, bytes: &mut [u8], offset: usize, value: &Value) -> Result<(), &'static str> {
179        let size = self.size();
180        if offset + size > bytes.len() {
181            return Ok(());
182        }
183        // A BigInt element type stores the BigInt itself, modulo `2^64`.
184        if matches!(self, ElementType::BigInt64 | ElementType::BigUint64) {
185            let Value::BigInt(big) = value else {
186                return Err(NOT_A_BIGINT);
187            };
188            let slice = &mut bytes[offset..offset + size];
189            let bits = match self {
190                ElementType::BigInt64 => big.to_i64_wrapping() as u64,
191                _ => big.to_u64_wrapping(),
192            };
193            slice.copy_from_slice(&bits.to_le_bytes());
194            return Ok(());
195        }
196        // The numeric types: every primitive has a number form except a Symbol, which
197        // `ToNumber` refuses. Answering `NaN` here would store a wrong element silently.
198        if matches!(value, Value::Symbol(_)) {
199            return Err(NOT_A_NUMBER);
200        }
201        let number = value.to_number();
202        let slice = &mut bytes[offset..offset + size];
203        match self {
204            ElementType::Int8 => slice[0] = to_integer(number) as i8 as u8,
205            ElementType::Uint8 => slice[0] = to_integer(number) as u8,
206            ElementType::Uint8Clamped => slice[0] = clamp_to_uint8(number),
207            ElementType::Int16 => slice.copy_from_slice(&(to_integer(number) as i16).to_le_bytes()),
208            ElementType::Uint16 => {
209                slice.copy_from_slice(&(to_integer(number) as u16).to_le_bytes())
210            }
211            ElementType::Int32 => slice.copy_from_slice(&(to_integer(number) as i32).to_le_bytes()),
212            ElementType::Uint32 => {
213                slice.copy_from_slice(&(to_integer(number) as u32).to_le_bytes())
214            }
215            ElementType::Float16 => slice.copy_from_slice(&f64_to_f16(number).to_le_bytes()),
216            ElementType::Float32 => slice.copy_from_slice(&(number as f32).to_le_bytes()),
217            ElementType::Float64 => slice.copy_from_slice(&number.to_le_bytes()),
218            // Handled above; unreachable, but the match has to be exhaustive.
219            ElementType::BigInt64 | ElementType::BigUint64 => {}
220        }
221        Ok(())
222    }
223}
224
225/// Why an element write was refused: the target is a BigInt type and the value is not one.
226pub const NOT_A_BIGINT: &str = "cannot convert a Number to a BigInt";
227
228/// Why an element write was refused: the target is numeric and the value has no number form.
229pub const NOT_A_NUMBER: &str = "cannot convert a Symbol or BigInt to a number";
230
231/// `ToIntegerOrInfinity`, truncated toward zero, as the integer element types need it.
232///
233/// A cast through `i64` would be undefined for out-of-range floats in Rust (`as` saturates
234/// since 1.45, which is the behaviour wanted here anyway), so the wrap happens at the target
235/// width — `as i8` and friends keep the low bits, which is exactly the spec's modulo.
236fn to_integer(number: f64) -> i64 {
237    if number.is_nan() {
238        return 0;
239    }
240    if number.is_infinite() {
241        // The modulo of an infinity is 0 in every engine; the alternative is to wrap the
242        // saturated value, which no script expects.
243        return 0;
244    }
245    number.trunc() as i64
246}
247
248/// `ToUint8Clamp`: round half to even, then clamp into `0..=255`.
249fn clamp_to_uint8(number: f64) -> u8 {
250    if number.is_nan() || number <= 0.0 {
251        return 0;
252    }
253    if number >= 255.0 {
254        return 255;
255    }
256    // `round_ties_even` is what the spec asks for; `0.5` must land on `0`, not `1`.
257    let rounded = number.round_ties_even();
258    rounded as u8
259}
260
261/// Decode an IEEE-754 binary16 value.
262///
263/// `pub(crate)` because `Math.f16round` is defined in terms of exactly this pair — "round to
264/// nearest binary16, then read back as a double". Sharing the two functions instead of
265/// writing a second half-float conversion is the difference between one rounding rule and
266/// two that can drift: `Math.f16round(x)` has to agree bit for bit with what
267/// `new Float16Array([x])[0]` stores, and the only way to guarantee that is to call it.
268pub(crate) fn f16_to_f64(bits: u16) -> f64 {
269    let sign = if bits & 0x8000 == 0 { 1.0 } else { -1.0 };
270    let exponent = ((bits >> 10) & 0x1f) as i32;
271    let mantissa = (bits & 0x3ff) as f64;
272    if exponent == 0 {
273        // Zero or subnormal: no implicit leading bit, and the scale is the smallest one.
274        sign * mantissa * 2f64.powi(-24)
275    } else if exponent == 0x1f {
276        if mantissa == 0.0 {
277            sign * f64::INFINITY
278        } else {
279            f64::NAN
280        }
281    } else {
282        sign * (1.0 + mantissa / 1024.0) * 2f64.powi(exponent - 15)
283    }
284}
285
286/// Encode a value as IEEE-754 binary16, rounding to nearest even.
287pub(crate) fn f64_to_f16(value: f64) -> u16 {
288    if value.is_nan() {
289        return 0x7e00;
290    }
291    let sign = if value.is_sign_negative() {
292        0x8000u16
293    } else {
294        0
295    };
296    let magnitude = value.abs();
297    if magnitude == 0.0 {
298        return sign;
299    }
300    // The overflow threshold is 65520, not 65504: 65504 is the largest finite binary16 and
301    // the next representable value is infinity, so values in (65504, 65520) round *down* to
302    // 65504 under round-half-to-even (65520 itself is the tie and rounds up). Comparing
303    // against 65504 sent 65505..65519 to infinity, which the reference stores as 65504.
304    if magnitude >= 65520.0 {
305        return sign | 0x7c00; // infinity
306    }
307    if magnitude < 6.103_515_625e-5 {
308        // Subnormal: the mantissa counts in units of 2^-24, rounded to nearest even.
309        let scaled = magnitude / 2f64.powi(-24);
310        let mantissa = scaled.round_ties_even();
311        return sign | (mantissa as u16);
312    }
313    // Normal: 1.m × 2^(e-15), so the exponent field is e + 15 and the mantissa keeps 10 bits.
314    let exponent = magnitude.log2().floor() as i32;
315    let biased = exponent + 15;
316    let mantissa = (magnitude / 2f64.powi(exponent) - 1.0) * 1024.0;
317    let rounded = mantissa.round_ties_even();
318    if rounded >= 1024.0 {
319        // Rounding carried into the exponent.
320        let biased = biased + 1;
321        if biased >= 0x1f {
322            return sign | 0x7c00;
323        }
324        return sign | ((biased as u16) << 10);
325    }
326    sign | ((biased as u16) << 10) | (rounded as u16)
327}
328
329/// Install `ArrayBuffer` and every typed-array view.
330pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
331    install_array_buffer(interp, object_proto);
332    install_views(interp, object_proto);
333    install_data_view(interp, object_proto);
334}
335
336fn install_array_buffer(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
337    let proto = interp.new_object(Some(object_proto.clone()));
338    // `new_native_ctor`, not `new_native_constructor`: every refusal here (a bad length, a
339    // `maxByteLength` below it, an allocation that cannot be made) has to happen before
340    // `new.target.prototype` is read, and only the former leaves the instance to us.
341    let constructor = interp.new_native_ctor("ArrayBuffer", 1, buffer_constructor);
342    constructor.define(
343        "prototype",
344        Property::with_attributes(Value::Object(proto.clone()), false, false),
345    );
346    proto.define(
347        "constructor",
348        Property::with_attributes(Value::Object(constructor.clone()), true, false),
349    );
350    define_method(&proto, "transfer", 0, buffer_transfer_keep, interp);
351    define_method(
352        &proto,
353        "transferToFixedLength",
354        0,
355        buffer_transfer_to_fixed_length,
356        interp,
357    );
358    define_method(&proto, "slice", 2, buffer_slice, interp);
359    define_method(&proto, "resize", 1, buffer_resize, interp);
360    define_method(&constructor, "isView", 1, buffer_is_view, interp);
361    // `maxByteLength` and `resizable` are accessors for the same reason `byteLength` is: a
362    // detached buffer answers `0`/`false` rather than a stale number.
363    let max_getter = interp.new_native("get maxByteLength", 0, buffer_max_byte_length_getter);
364    proto.define(
365        "maxByteLength",
366        Property {
367            getter: Some(Value::Object(max_getter)),
368            enumerable: false,
369            configurable: true,
370            ..Property::default()
371        },
372    );
373    let resizable_getter = interp.new_native("get resizable", 0, buffer_resizable);
374    proto.define(
375        "resizable",
376        Property {
377            getter: Some(Value::Object(resizable_getter)),
378            enumerable: false,
379            configurable: true,
380            ..Property::default()
381        },
382    );
383    // `detached` (§25.1.5.1) answers the slot rather than the length: a buffer can be
384    // zero-length and alive, and only `transfer`/`transferToFixedLength` detach. It is the
385    // readable form of the state `transfer` leaves behind.
386    let detached_getter = interp.new_native("get detached", 0, buffer_detached);
387    proto.define(
388        "detached",
389        Property {
390            getter: Some(Value::Object(detached_getter)),
391            enumerable: false,
392            configurable: true,
393            ..Property::default()
394        },
395    );
396    // `byteLength` is an accessor so a detached buffer reports `0` instead of a stale size.
397    let getter = interp.new_native("get byteLength", 0, buffer_byte_length);
398    proto.define(
399        "byteLength",
400        Property {
401            getter: Some(Value::Object(getter)),
402            enumerable: false,
403            configurable: true,
404            ..Property::default()
405        },
406    );
407    install_tag(&proto, "ArrayBuffer", interp);
408    install_species_accessor(&constructor, interp);
409    interp.realm.array_buffer_proto = Some(proto);
410    let global = interp.realm.global.clone();
411    global.define(
412        "ArrayBuffer",
413        Property::with_attributes(Value::Object(constructor), true, false),
414    );
415}
416
417fn install_views(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
418    // One shared prototype carries every method and every accessor; each element type gets a
419    // prototype of its own on top of it, which is what lets `BYTES_PER_ELEMENT` and the
420    // string tag differ per type while the behaviour is written once.
421    let shared = interp.new_object(Some(object_proto.clone()));
422    define_method(&shared, "set", 1, set_from, interp);
423    define_method(&shared, "fill", 1, fill, interp);
424    define_method(&shared, "join", 1, join, interp);
425    // §23.2.3.31: `%TypedArray%.prototype.toString` **is** `Array.prototype.toString`, the
426    // same function object — `TypedArray/prototype/toString` compares them with
427    // `assert.sameValue`, so defining a wrapper over `join` is not enough.
428    let array_to_string = interp.realm.array_proto.own_property("toString");
429    if let Some(to_string) = array_to_string.and_then(|property| property.value)
430        && matches!(&to_string, Value::Object(function) if function.is_callable())
431    {
432        shared.define(
433            "toString",
434            crate::object::Property::with_attributes(to_string, true, false),
435        );
436    }
437    define_method(&shared, "toLocaleString", 0, to_locale_string, interp);
438    define_method(&shared, "slice", 2, slice, interp);
439    define_method(&shared, "subarray", 2, subarray, interp);
440    // The whole `%TypedArray%.prototype` iteration family, which was absent: every
441    // `[].map.call(typedArray, f)` reached `undefined is not a function`.
442    define_method(&shared, "at", 1, at as crate::object::NativeFn, interp);
443    define_method(&shared, "every", 1, every, interp);
444    define_method(&shared, "some", 1, some, interp);
445    define_method(&shared, "forEach", 1, for_each, interp);
446    define_method(&shared, "map", 1, map, interp);
447    define_method(&shared, "filter", 1, filter, interp);
448    define_method(&shared, "reduce", 1, reduce, interp);
449    define_method(&shared, "reduceRight", 1, reduce_right, interp);
450    define_method(&shared, "find", 1, find, interp);
451    define_method(&shared, "findIndex", 1, find_index, interp);
452    define_method(&shared, "findLast", 1, find_last, interp);
453    define_method(&shared, "findLastIndex", 1, find_last_index, interp);
454    define_method(&shared, "indexOf", 1, index_of, interp);
455    define_method(&shared, "lastIndexOf", 1, last_index_of, interp);
456    define_method(&shared, "includes", 1, includes, interp);
457    define_method(&shared, "reverse", 0, reverse, interp);
458    define_method(&shared, "sort", 1, sort, interp);
459    define_method(&shared, "copyWithin", 2, copy_within, interp);
460    define_method(&shared, "with", 2, with, interp);
461    define_method(&shared, "toReversed", 0, to_reversed, interp);
462    define_method(&shared, "toSorted", 1, to_sorted, interp);
463    define_method(&shared, "values", 0, values, interp);
464    define_method(&shared, "keys", 0, keys, interp);
465    define_method(&shared, "entries", 0, entries, interp);
466    // `%TypedArray%.prototype[Symbol.iterator]` *is* `values`, not a wrapper around it.
467    if let Some(values_fn) = shared.own_property("values").and_then(|p| p.value) {
468        let key = interp
469            .realm
470            .well_known_key(crate::interp::WellKnown::Iterator);
471        shared.define_key(&key, Property::with_attributes(values_fn, true, false));
472    }
473    for (name, getter) in [
474        ("buffer", buffer_of as crate::object::NativeFn),
475        ("byteOffset", byte_offset_of),
476        ("byteLength", byte_length_of),
477        ("length", length_of),
478        ("[Symbol.toStringTag]", tag_of),
479    ] {
480        // An accessor's `name` is `get <key>` — `get buffer`, `get [Symbol.toStringTag]` —
481        // not the bare key. `buffer/name.js` and `Symbol.toStringTag/name.js` both read
482        // this back off the descriptor.
483        let function = interp.new_native(format!("get {name}"), 0, getter);
484        let key = if name == "[Symbol.toStringTag]" {
485            interp
486                .realm
487                .well_known_key(crate::interp::WellKnown::ToStringTag)
488        } else {
489            crate::object::PropertyKey::from(name)
490        };
491        shared.define_key(
492            &key,
493            Property {
494                getter: Some(Value::Object(function)),
495                enumerable: false,
496                configurable: true,
497                ..Property::default()
498            },
499        );
500    }
501    interp.realm.typed_array_proto = Some(shared.clone());
502    // Built after the shared prototype exists, because `%TypedArray%.prototype` *is* that
503    // object and `constructor` has to point back at the intrinsic.
504    let intrinsic = install_typed_array_intrinsic(interp, &shared);
505
506    let global = interp.realm.global.clone();
507    for (element, name) in ELEMENT_TYPES {
508        let proto = interp.new_object(Some(shared.clone()));
509        // The constructor reads the element type off this, so `new` is the only way in.
510        proto.define(
511            "_element",
512            Property::with_attributes(Value::Int(element as i32), false, false),
513        );
514        proto.define(
515            "BYTES_PER_ELEMENT",
516            Property::with_attributes(Value::Int(element.size() as i32), false, false),
517        );
518        let constructor = interp.new_native_ctor(name, 3, view_constructor);
519        // `Object.getPrototypeOf(Int8Array)` is `%TypedArray%`, which is where `from` and
520        // `of` live; without it the statics were unreachable from every constructor.
521        constructor.set_proto(Some(intrinsic.clone()));
522        constructor.define(
523            "_element",
524            Property::with_attributes(Value::Int(element as i32), false, false),
525        );
526        constructor.define(
527            "BYTES_PER_ELEMENT",
528            Property::with_attributes(Value::Int(element.size() as i32), false, false),
529        );
530        constructor.define(
531            "prototype",
532            Property::with_attributes(Value::Object(proto.clone()), false, false),
533        );
534        proto.define(
535            "constructor",
536            Property::with_attributes(Value::Object(constructor.clone()), true, false),
537        );
538        // Remembered so a method that answers with a fresh view can give it the right
539        // prototype; `new_view` looks the type up in this vector.
540        interp.realm.typed_array_protos.push(proto.clone());
541        // The `uint8array-base64` proposal puts six methods on `Uint8Array` alone, so they
542        // cannot go on the shared `%TypedArray%` — `Uint16Array.fromHex` must not exist.
543        if element == ElementType::Uint8 {
544            crate::builtins::base64::install(interp, &constructor, &proto);
545        }
546        global.define(
547            name,
548            Property::with_attributes(Value::Object(constructor), true, false),
549        );
550    }
551}
552
553/// `ArrayBuffer.prototype[Symbol.toStringTag]`.
554/// `new ArrayBuffer(length)`.
555/// `ArrayBuffer(length [, options])`.
556///
557/// Everything that can be refused is refused before the instance exists: §25.1.3.1 runs
558/// `ToIndex`, reads `options.maxByteLength`, compares the two and allocates the data block,
559/// and only then `OrdinaryCreateFromConstructor`. The order is observable, and
560/// `options-maxbytelength-compared-before-object-creation` observes it with a throwing
561/// `new.target.prototype` getter — so this constructor is registered as
562/// `new_native_ctor`, the one whose instance `new` does not build up front.
563fn buffer_constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
564    // §25.1.3.1 step 1: `If NewTarget is undefined, throw a TypeError exception`. Every
565    // other built-in constructor has a `[[Call]]` that either works or refuses for its own
566    // reason; `ArrayBuffer()` is a plain `TypeError` (`undefined-newtarget-throws`).
567    if !matches!(interp.current_new_target(), Value::Object(_)) {
568        return Err(interp.type_error("Constructor ArrayBuffer requires 'new'"));
569    }
570    let length = to_index(interp, &arg(args, 0), "array buffer length")?;
571    // The optional second argument is the options bag: `{maxByteLength}` makes the buffer
572    // resizable. Absent means fixed-length, which is the case every other caller wants.
573    let max_byte_length = buffer_max_byte_length(interp, &arg(args, 1))?;
574    if max_byte_length.is_some_and(|max| max < length) {
575        return Err(interp.range_error("invalid max byte length"));
576    }
577    // The *maximum* has to be allocatable too, even though nothing is allocated for it yet:
578    // `new ArrayBuffer(0, {maxByteLength: 7 * 1024**5})` is a `RangeError` in the reference,
579    // because a ceiling the machine could never reach makes the buffer a lie. The probe is a
580    // reservation rather than a fill, so it costs address space and no pages.
581    //
582    // It goes here, with the other argument checks, and not with the allocation below:
583    // `AllocateArrayBuffer` has no such step at all, so there is nothing to order it
584    // against, and everything the spec *does* order belongs before
585    // `OrdinaryCreateFromConstructor`.
586    if let Some(max) = max_byte_length
587        && max > length
588        && !can_allocate(max)
589    {
590        return Err(interp.range_error("invalid max byte length"));
591    }
592    // `OrdinaryCreateFromConstructor` before `CreateByteDataBlock`: a throwing
593    // `new.target.prototype` getter wins over an allocation that could not be made. The two
594    // orders are pinned by two tests pointing opposite ways —
595    // `data-allocation-after-object-creation` wants the getter first, and
596    // `options-maxbytelength-compared-before-object-creation` wants the `maxByteLength`
597    // comparison before the getter — which is why only *this* one moves.
598    let default_proto = interp
599        .realm
600        .array_buffer_proto
601        .clone()
602        .unwrap_or_else(|| interp.realm.object_proto.clone());
603    let object = interp.new_ctor_instance(default_proto)?;
604    // The allocation can fail, and the spec makes that a `RangeError`
605    // (`CreateByteDataBlock`: "if it is impossible to create such a Data Block, throw a
606    // RangeError"). Letting `vec![0; length]` abort the process made
607    // `new ArrayBuffer(7 * 1024**5)` a crash instead of an exception — which is also what
608    // `ArrayBuffer/allocation-limit.js` asserts, so it has to be caught here rather than
609    // left to the allocator.
610    let bytes =
611        allocate_zeroed(length).ok_or_else(|| interp.range_error("invalid array buffer length"))?;
612    object.set_array_buffer(Rc::new(RefCell::new(BufferStorage {
613        bytes,
614        detached: false,
615        max_byte_length,
616        release: None,
617    })));
618    Ok(Value::Object(object))
619}
620
621/// Whether `length` bytes can be reserved, without committing them.
622///
623/// `try_reserve_exact` asks the allocator and gives the block straight back; the pages are
624/// never touched, so this is a check rather than a second allocation.
625fn can_allocate(length: usize) -> bool {
626    let mut probe: Vec<u8> = Vec::new();
627    probe.try_reserve_exact(length).is_ok()
628}
629
630/// A zeroed byte vector of `length` bytes, or `None` if the allocation would fail.
631///
632/// `try_reserve_exact` rather than `vec![0; length]`: the latter aborts on failure, and a
633/// script must not be able to abort the engine by asking for a buffer the machine cannot
634/// give it. The reserve is done in one step so that a huge length fails immediately instead
635/// of zeroing page by page until the process dies.
636fn allocate_zeroed(length: usize) -> Option<Vec<u8>> {
637    let mut bytes: Vec<u8> = Vec::new();
638    bytes.try_reserve_exact(length).ok()?;
639    bytes.resize(length, 0);
640    Some(bytes)
641}
642
643/// `maxByteLength` from the constructor's options bag, or `None` for a fixed-length buffer.
644///
645/// Read the way the spec reads an options object: only an *object* argument has properties to
646/// read, and a non-number `maxByteLength` is a `RangeError` rather than being ignored — a
647/// buffer silently not resizable would be the wrong answer for `assert(ab.resizable)`.
648fn buffer_max_byte_length(interp: &mut Interp<'_>, options: &Value) -> JsResult<Option<usize>> {
649    let Some(object) = options.as_object().cloned() else {
650        return Ok(None);
651    };
652    let max = interp.get_property(&object, "maxByteLength")?;
653    match max {
654        None | Some(Value::Undefined) => Ok(None),
655        Some(value) => {
656            let number = to_integer_or_infinity(interp, &value)?;
657            if !(0.0..=9_007_199_254_740_991.0).contains(&number) {
658                return Err(interp.range_error("invalid max byte length"));
659            }
660            Ok(Some(number as usize))
661        }
662    }
663}
664
665/// `ArrayBuffer.prototype.maxByteLength`.
666fn buffer_max_byte_length_getter(
667    interp: &mut Interp<'_>,
668    this: Value,
669    _args: &[Value],
670) -> JsResult<Value> {
671    let storage = buffer_storage_of(interp, &this)?;
672    let storage = storage.borrow();
673    Ok(Value::Float(if storage.detached {
674        0.0
675    } else {
676        storage.max_byte_length() as f64
677    }))
678}
679
680/// `ArrayBuffer.prototype.resizable`.
681fn buffer_resizable(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
682    let storage = buffer_storage_of(interp, &this)?;
683    // `IsResizableArrayBuffer` looks at the `[[ArrayBufferMaxByteLength]]` *slot*, so a
684    // detached buffer keeps answering `true` — only `byteLength`/`maxByteLength` collapse to
685    // zero. Adding the detached check here made
686    // `ArrayBuffer/prototype/resizable/detached-buffer.js` fail on its second assertion.
687    let resizable = storage.borrow().is_resizable();
688    Ok(Value::Bool(resizable))
689}
690
691/// `ArrayBuffer.prototype.detached`.
692fn buffer_detached(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
693    let storage = buffer_storage_of(interp, &this)?;
694    let detached = storage.borrow().detached;
695    Ok(Value::Bool(detached))
696}
697
698/// `ArrayBuffer.prototype.resize(newLength)`.
699///
700/// Growing zero-fills and shrinking truncates, which is what `Vec::resize` does — the two
701/// behaviours the spec asks for and the reason the old bytes are kept intact across a grow.
702fn buffer_resize(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
703    let storage = buffer_storage_of(interp, &this)?;
704    let requested = to_integer_or_infinity(interp, &arg(args, 0))?;
705    let mut storage = storage.borrow_mut();
706    if storage.detached {
707        return Err(interp.type_error("ArrayBuffer has already been detached"));
708    }
709    let Some(max) = storage.max_byte_length else {
710        return Err(interp.type_error("ArrayBuffer is not resizable"));
711    };
712    if requested < 0.0 || requested > max as f64 || requested > 9_007_199_254_740_991.0 {
713        return Err(interp.range_error("invalid array buffer length"));
714    }
715    storage.bytes.resize(requested as usize, 0);
716    Ok(Value::Undefined)
717}
718
719/// The storage of `this`, which must be an `ArrayBuffer`.
720fn buffer_storage_of(interp: &Interp<'_>, this: &Value) -> JsResult<Rc<RefCell<BufferStorage>>> {
721    this.as_object()
722        .and_then(|object| object.array_buffer_storage())
723        .ok_or_else(|| interp.type_error("not an ArrayBuffer"))
724}
725
726/// `ArrayBuffer.isView(arg)`.
727///
728/// The one predicate here that must *not* accept a Proxy: §25.1.3.1 tests for the
729/// `[[ViewedArrayBuffer]]` internal slot, and a Proxy over a typed array has none (it is
730/// not a view, it merely forwards to one). `isArrayBufferView` in the reference behaves
731/// the same way.
732fn buffer_is_view(_interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
733    let view = matches!(arg(args, 0), Value::Object(object) if object.is_array_buffer_view());
734    Ok(Value::Bool(view))
735}
736
737/// `ArrayBuffer.prototype.byteLength`.
738fn buffer_byte_length(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
739    let storage = buffer_storage_of(interp, &this)?;
740    let storage = storage.borrow();
741    Ok(Value::Int(if storage.detached {
742        0
743    } else {
744        storage.bytes.len() as i32
745    }))
746}
747
748/// `ArrayBuffer.prototype.transfer(newLength?)` and `transferToFixedLength(newLength?)`,
749/// which differ in one step of `ArrayBufferCopyAndDetach`: whether the new buffer keeps the
750/// old one's `[[ArrayBufferMaxByteLength]]`.
751///
752/// Two things are easy to get wrong and are pinned by test262 one case at a time:
753///
754/// * the new buffer is **resizable if the source was**, with the same `maxByteLength`,
755///   even when `newLength` is smaller — `transfer` is not "copy into a fixed buffer";
756/// * `newLength` above that maximum is a `RangeError`, because a resizable buffer whose
757///   length exceeds its own maximum cannot exist.
758fn buffer_transfer(
759    interp: &mut Interp<'_>,
760    this: Value,
761    args: &[Value],
762    preserve_resizability: bool,
763) -> JsResult<Value> {
764    let storage = buffer_storage_of(interp, &this)?;
765    // `ToIndex` runs before the detach check in the spec's step order, so a `valueOf` that
766    // detaches is still called — and `transfer(2**53)` is a `RangeError` either way.
767    let requested = if args.is_empty() || matches!(arg(args, 0), Value::Undefined) {
768        None
769    } else {
770        Some(to_index(interp, &arg(args, 0), "new length")?)
771    };
772    let (bytes, max) = {
773        let mut storage = storage.borrow_mut();
774        if storage.detached {
775            return Err(interp.type_error("ArrayBuffer has already been detached"));
776        }
777        let length = requested.unwrap_or(storage.bytes.len());
778        let max = match (preserve_resizability, storage.max_byte_length) {
779            (true, Some(max)) => {
780                if length > max {
781                    return Err(interp.range_error("invalid array buffer length"));
782                }
783                Some(max)
784            }
785            // A fixed-length source, or `transferToFixedLength`: the new buffer cannot grow.
786            _ => None,
787        };
788        storage.detached = true;
789        let mut bytes = std::mem::take(&mut storage.bytes);
790        bytes.resize(length, 0);
791        bytes.truncate(length);
792        (bytes, max)
793    };
794    let fresh_storage = Rc::new(RefCell::new(match max {
795        Some(max) => BufferStorage::resizable(bytes, max),
796        None => BufferStorage::fixed(bytes),
797    }));
798    let proto = interp
799        .realm
800        .array_buffer_proto
801        .clone()
802        .unwrap_or_else(|| interp.realm.object_proto.clone());
803    let object = interp.new_object(Some(proto));
804    object.set_array_buffer(fresh_storage);
805    Ok(Value::Object(object))
806}
807
808/// `ArrayBuffer.prototype.transfer(newLength?)`: move the bytes, keeping resizability.
809fn buffer_transfer_keep(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
810    buffer_transfer(interp, this, args, true)
811}
812
813/// `ArrayBuffer.prototype.transferToFixedLength(newLength?)`: move the bytes into a buffer
814/// that cannot be resized, whatever the source could do.
815fn buffer_transfer_to_fixed_length(
816    interp: &mut Interp<'_>,
817    this: Value,
818    args: &[Value],
819) -> JsResult<Value> {
820    buffer_transfer(interp, this, args, false)
821}
822
823/// §25.1.5.3 `ArrayBuffer.prototype.slice ( start, end )`.
824///
825/// The result comes from **`SpeciesConstructor(O, %ArrayBuffer%)`**, not from a fresh
826/// intrinsic buffer, and every one of the three things that can go wrong with the species'
827/// answer is a `TypeError`: a non-`ArrayBuffer`, the *same* buffer, or one shorter than the
828/// range being copied. Building the buffer directly made all six `species*` cases pass
829/// vacuously with the wrong answer.
830///
831/// `begin`/`end` go through `ToIntegerOrInfinity`, in that order and before the species
832/// lookup: `slice(0, NaN)` copies nothing (`ToIntegerOrInfinity(NaN)` is `0`), where a plain
833/// `to_number` left the `NaN` in place and `clamp_index` read it as "to the end".
834fn buffer_slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
835    let storage = buffer_storage_of(interp, &this)?;
836    let length = {
837        let storage = storage.borrow();
838        if storage.detached {
839            return Err(interp.type_error("ArrayBuffer has already been detached"));
840        }
841        storage.bytes.len()
842    };
843    let length_i = length as i64;
844    // Steps 5–6.
845    let first = clamp_index(to_integer_or_infinity(interp, &arg(args, 0))?, length_i, 0);
846    // Steps 7–8: a missing `end` is the whole buffer; a present one is converted too.
847    let last = match args.get(1) {
848        None | Some(Value::Undefined) => length_i,
849        Some(value) => clamp_index(to_integer_or_infinity(interp, value)?, length_i, length_i),
850    };
851    // Step 9.
852    let new_length = (last - first).max(0) as usize;
853    // Step 10.
854    let Some(receiver) = this.as_object().cloned() else {
855        return Err(interp.type_error("not an ArrayBuffer"));
856    };
857    // The default is the **intrinsic** `%ArrayBuffer%`, not `O.constructor`: a `constructor`
858    // whose `@@species` is `null`/`undefined` falls back to the intrinsic, and reading the
859    // default off the receiver answered the user's object instead
860    // (`species-is-null`, `species-is-undefined`).
861    let default = match interp.realm.array_buffer_proto.clone() {
862        Some(proto) => interp
863            .get_property(&proto, "constructor")?
864            .unwrap_or(Value::Undefined),
865        None => Value::Undefined,
866    };
867    let constructor = interp.species_constructor(&receiver, default)?;
868    // Step 11: `Construct(ctor, « newLen »)` — the argument is observable, so it is a
869    // Number that the constructor's own `ToIndex` will see.
870    let produced = interp.construct(
871        constructor.clone(),
872        constructor,
873        vec![Value::Float(new_length as f64)],
874    )?;
875    let Some(produced_object) = produced.as_object().cloned() else {
876        return Err(interp.type_error("species constructor did not answer an ArrayBuffer"));
877    };
878    let Some(destination) = produced_object.array_buffer_storage() else {
879        return Err(interp.type_error("species constructor did not answer an ArrayBuffer"));
880    };
881    if destination.borrow().detached {
882        return Err(interp.type_error("the new ArrayBuffer is detached"));
883    }
884    if Rc::ptr_eq(&destination, &storage) {
885        return Err(interp.type_error("species constructor answered the same ArrayBuffer"));
886    }
887    if destination.borrow().bytes.len() < new_length {
888        return Err(interp.type_error("the new ArrayBuffer is too small"));
889    }
890    // Step 13: copy from a snapshot of the source, so a getter on the destination cannot
891    // interfere with the read.
892    let bytes = {
893        let source = storage.borrow();
894        if source.detached {
895            return Err(interp.type_error("ArrayBuffer has already been detached"));
896        }
897        source.bytes[first as usize..first as usize + new_length].to_vec()
898    };
899    destination.borrow_mut().bytes[..new_length].copy_from_slice(&bytes);
900    Ok(Value::Object(produced_object))
901}
902
903/// Resolve a `begin`/`end` argument the way every slice does: relative to the end when
904/// negative, then clamped into range.
905fn clamp_index(value: f64, length: i64, default: i64) -> i64 {
906    if value.is_nan() {
907        return default.min(length).max(0);
908    }
909    let value = if value.is_infinite() {
910        if value > 0.0 { length } else { 0 }
911    } else {
912        value.trunc() as i64
913    };
914    (if value < 0 { length + value } else { value }).clamp(0, length)
915}
916
917/// `ToIndex`: `undefined` and `NaN` are `0`, a negative or infinite value is a
918/// `RangeError`, and so is a fraction rather than being truncated.
919///
920/// This is what makes `new Uint8Array(buffer)` mean "from byte 0, to the end": the missing
921/// second argument is `undefined`, which is `0`, and a `NaN` offset must not be a failure.
922/// `ToIntegerOrInfinity(value)`, which refuses a Symbol and a BigInt.
923///
924/// `Value::to_number` answers `NaN` for both so that it stays total; that made
925/// `copyWithin(0, Symbol())` a silent no-op instead of the `TypeError` the spec requires.
926fn to_integer_or_infinity(interp: &mut Interp<'_>, value: &Value) -> JsResult<f64> {
927    // `to_js_number` already refuses a Symbol and a BigInt, boxed ones included.
928    let number = interp.to_js_number(value)?;
929    Ok(if number.is_nan() { 0.0 } else { number.trunc() })
930}
931
932/// `ToIndex(value)`: `ToIntegerOrInfinity` and then a range check.
933///
934/// `ToIntegerOrInfinity` *truncates*, so `new Int32Array(2.7)` is two elements rather than
935/// a `RangeError`; only a negative or infinite result is refused. `ToNumber` on a BigInt is
936/// a `TypeError`, which is why the conversion goes through the interpreter.
937fn to_index(interp: &mut Interp<'_>, value: &Value, what: &str) -> JsResult<usize> {
938    // Through `ToIntegerOrInfinity`, so a Symbol or BigInt is a `TypeError` rather than the
939    // `NaN` that `Value::to_number` answers to stay total.
940    let number = to_integer_or_infinity(interp, value)?;
941    // `2^53 - 1` is the largest index the spec allows.
942    if number < 0.0 || number > 9_007_199_254_740_991.0 {
943        return Err(interp.range_error(format!("invalid {what}")));
944    }
945    Ok(number as usize)
946}
947
948/// The element type a typed-array *constructor* stands for, read off its `_element`.
949fn element_of_constructor(interp: &Interp<'_>, callee: &Gc<JsObject>) -> Option<ElementType> {
950    let raw = callee
951        .own_property("_element")
952        .and_then(|property| property.value)?;
953    let raw = raw.to_number() as i32;
954    let found = ELEMENT_TYPES
955        .into_iter()
956        .map(|(element, _)| element)
957        .find(|element| *element as i32 == raw);
958    let _ = interp;
959    found
960}
961
962/// `new Uint8Array(...)`: from a length, from a buffer, or from an array-like.
963fn view_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
964    // A typed-array constructor cannot be called as a function: there is no receiver to
965    // take an element type from, and the spec makes that a `TypeError`.
966    // The element type comes from the *callee*, not from a receiver: a native constructor is
967    // handed `this = undefined` and builds its own instance once its arguments are valid.
968    let _ = &this;
969    let callee = interp
970        .current_native()
971        .ok_or_else(|| interp.type_error("constructor requires 'new'"))?;
972    let element = element_of_constructor(interp, &callee)
973        .ok_or_else(|| interp.type_error("constructor requires 'new'"))?;
974    if !interp.is_constructing() {
975        return Err(interp.type_error("constructor requires 'new'"));
976    }
977    let first = arg(args, 0);
978    let (buffer, offset, length) = match &first {
979        // `new X(buffer, byteOffset, length)`: a window onto existing bytes.
980        Value::Object(object) if object.array_buffer_storage().is_some() => {
981            let storage = object
982                .array_buffer_storage()
983                .expect("checked by the guard above");
984            let storage = storage.borrow();
985            // §23.2.5.1 step 3: a detached buffer is a `TypeError` before the offset is
986            // even read (`ctors/buffer-arg/detachedbuffer`).
987            if storage.detached {
988                return Err(interp.type_error("the ArrayBuffer is detached"));
989            }
990            let total = storage.bytes.len();
991            let resizable = storage.is_resizable();
992            drop(storage);
993            let byte_offset = to_index(interp, &arg(args, 1), "byte offset")?;
994            // Misalignment is always `invalid offset`, but the two bounds failures are not
995            // the same error and do not even happen in the same branch. Reading
996            // `js_typed_array_constructor` in the reference:
997            //
998            // * no length given  -> `offset > byte_length` is `invalid offset`;
999            // * a length given    -> the *sum* `offset + len * size` is checked, and the
1000            //   failure is `invalid length`. There is no separate `offset > byte_length`
1001            //   test on that path, so `(buf16, 20, 1)` says `invalid length`.
1002            if byte_offset % element.size() != 0 {
1003                return Err(interp.range_error("invalid offset"));
1004            }
1005            // No third argument means "the rest of the buffer", which is different from
1006            // `undefined` meaning 0 — hence a length check rather than a nullish one.
1007            let length = if args.len() < 3 || matches!(arg(args, 2), Value::Undefined) {
1008                if byte_offset > total {
1009                    return Err(interp.range_error("invalid offset"));
1010                }
1011                if resizable {
1012                    // A view of a resizable buffer with no length **tracks** it: growing the
1013                    // buffer grows the view, and no divisibility is required because the
1014                    // length is not pinned to the current contents
1015                    // (`new Uint32Array(rabOf5)` is one element, not an error).
1016                    ViewLength::Tracking
1017                } else {
1018                    // The remainder of the buffer has to be a whole number of elements:
1019                    // `04 00 00 00 05` is not a `Uint32Array` and cannot be one.
1020                    if total % element.size() != 0 {
1021                        return Err(interp.range_error("invalid length"));
1022                    }
1023                    ViewLength::Fixed((total - byte_offset) / element.size())
1024                }
1025            } else {
1026                let requested = to_index(interp, &arg(args, 2), "length")?;
1027                if byte_offset + requested * element.size() > total {
1028                    return Err(interp.range_error("invalid length"));
1029                }
1030                ViewLength::Fixed(requested)
1031            };
1032            // The offset and length conversions run script, so either could have detached
1033            // the buffer — and the detached `TypeError` is checked again before the view is
1034            // made (`ctors/buffer-arg/byteoffset-to-number-detachbuffer`, `…/length-…`).
1035            if object
1036                .array_buffer_storage()
1037                .is_some_and(|storage| storage.borrow().detached)
1038            {
1039                return Err(interp.type_error("the ArrayBuffer is detached"));
1040            }
1041            (object.clone(), byte_offset, length)
1042        }
1043        // `new X(length)` for any *primitive* argument: the spec goes to `ToIndex` before
1044        // it ever looks for `Symbol.iterator`, so `new Int32Array("3")` is three zeroes
1045        // rather than the three characters. Only an object is treated as a source.
1046        Value::Int(_)
1047        | Value::Float(_)
1048        | Value::String(_)
1049        | Value::Bool(_)
1050        | Value::BigInt(_)
1051        // A Symbol belongs here too: `ToIndex` is what refuses it, with a `TypeError`
1052        // (`ctors/length-arg/is-symbol-throws`). Falling into the iterable arm answered an
1053        // empty view instead.
1054        | Value::Symbol(_)
1055        | Value::Null
1056        | Value::Undefined => {
1057            let count = to_index(interp, &first, "typed array length")?;
1058            let proto = interp
1059                .realm
1060                .array_buffer_proto
1061                .clone()
1062                .unwrap_or_else(|| interp.realm.object_proto.clone());
1063            let buffer = interp.new_object(Some(proto));
1064            buffer.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed(vec![
1065                0;
1066                count * element.size()
1067            ]))));
1068            (buffer, 0, ViewLength::Fixed(count))
1069        }
1070        // `new X(iterable)`: a buffer sized by the source, filled from it.
1071        _ => {
1072            // `Symbol.iterator` wins over `length`: an object that is both iterable and
1073            // array-like is read through the iterator. That is what the harness's
1074            // `makeIterable` — a plain object carrying only `Symbol.iterator` — needs, and
1075            // without it every such source constructed an *empty* view.
1076            // The array-like branch takes its count with `ToIndex`, **not** `ToLength`:
1077            // `{length: Symbol()}` is a `TypeError` and `{length: 2**53}` a `RangeError`
1078            // (`ctors/object-arg/length-is-symbol-throws`, `…/length-excessive-throws`).
1079            let values = if interp.has_iterator(&first)? {
1080                interp.collect_iterable(&first)?
1081            } else {
1082                match first.as_object().cloned() {
1083                    Some(object) => {
1084                        let raw_length = interp.get_property(&object, "length")?;
1085                        let count = match &raw_length {
1086                            Some(value) => interp.to_index(value)?,
1087                            None => 0,
1088                        };
1089                        let mut items = Vec::with_capacity(count.min(1024));
1090                        for index in 0..count {
1091                            items.push(
1092                                interp
1093                                    .get_property(&object, &index.to_string())?
1094                                    .unwrap_or(Value::Undefined),
1095                            );
1096                        }
1097                        items
1098                    }
1099                    None => Vec::new(),
1100                }
1101            };
1102            let proto = interp
1103                .realm
1104                .array_buffer_proto
1105                .clone()
1106                .unwrap_or_else(|| interp.realm.object_proto.clone());
1107            let buffer = interp.new_object(Some(proto));
1108            let storage = Rc::new(RefCell::new(BufferStorage::fixed(vec![
1109                0;
1110                values.len()
1111                    * element.size()
1112            ])));
1113            buffer.set_array_buffer(storage);
1114            let count = values.len();
1115            for (index, value) in values.into_iter().enumerate() {
1116                // `new BigInt64Array([1])` is a TypeError: the initialiser runs
1117                // `ToBigInt` on each value, and a Number is not convertible.
1118                write_element(interp, &buffer, element, 0, index, value)?;
1119            }
1120            (buffer, 0, ViewLength::Fixed(count))
1121        }
1122    };
1123    let default_proto = interp
1124        .realm
1125        .typed_array_protos
1126        .get(element as usize)
1127        .cloned()
1128        .or_else(|| interp.realm.typed_array_proto.clone())
1129        .unwrap_or_else(|| interp.realm.object_proto.clone());
1130    let object = interp.new_ctor_instance(default_proto)?;
1131    object.set_typed_array(buffer, element, offset, length);
1132    Ok(Value::Object(object))
1133}
1134
1135/// Write one element through a buffer, for the paths that do not have a view in hand.
1136/// Store `value` into the element at `index`, applying `ToNumber` or `ToBigInt` first.
1137///
1138/// Both conversions are fallible *and* can run script — `ToPrimitive` calls `valueOf` —
1139/// so they happen before the buffer's `RefCell` is borrowed. Doing it inside
1140/// [`ElementType::write`] would either need the borrow held across a script call (a
1141/// re-entrancy panic waiting to happen) or would silently store `NaN` for an object,
1142/// which is how `new Uint8Array([{valueOf(){return 5}}])` used to produce `0` instead of
1143/// `5`.
1144fn write_element(
1145    interp: &mut Interp<'_>,
1146    buffer: &Gc<JsObject>,
1147    element: ElementType,
1148    offset: usize,
1149    index: usize,
1150    value: Value,
1151) -> JsResult<()> {
1152    // The conversion first, and *outside* the storage borrow: `ToPrimitive` runs
1153    // `valueOf`, which is script and can reach back into this very buffer.
1154    let stored = interp.element_value(element, value)?;
1155    let Some(storage) = buffer.array_buffer_storage() else {
1156        return Ok(());
1157    };
1158    let mut storage = storage.borrow_mut();
1159    if storage.detached {
1160        return Ok(());
1161    }
1162    // The bounds check inside `write` answers `Ok`, so an out-of-range index stays a
1163    // no-op rather than an error.
1164    element
1165        .write(&mut storage.bytes, offset + index * element.size(), &stored)
1166        .map_err(|reason| match reason {
1167            NOT_A_BIGINT => interp.type_error("cannot convert a Number to a BigInt"),
1168            other => interp.type_error(other),
1169        })
1170}
1171
1172/// A view's elements, read one at a time.
1173///
1174/// The length is fixed once, when the method starts (every one of these algorithms begins
1175/// `Let len be TypedArrayLength(taRecord)`), but each element is read *when the walk gets
1176/// there*, through the integer-indexed exotic `[[Get]]` — which answers `undefined` for an
1177/// index the buffer no longer covers. Snapshotting the elements up front is what
1178/// `every/callbackfn-resize` catches: a callback that shrinks the buffer has to make the
1179/// remaining elements `undefined` (`[0, 0, undefined]`), not replay the bytes that were
1180/// there when the method started.
1181///
1182/// No `Interp` is needed, because reading an element is a pure function of the object and
1183/// the index; only the callback calls go through the interpreter.
1184struct Elements {
1185    object: Gc<JsObject>,
1186    length: usize,
1187}
1188
1189impl Elements {
1190    fn len(&self) -> usize {
1191        self.length
1192    }
1193
1194    /// Element `index`, or `undefined` when it is no longer in bounds.
1195    fn get(&self, index: usize) -> Value {
1196        self.object
1197            .typed_array_element(index)
1198            .unwrap_or(Value::Undefined)
1199    }
1200
1201    fn iter(&self) -> impl Iterator<Item = (usize, Value)> + '_ {
1202        (0..self.length).map(move |index| (index, self.get(index)))
1203    }
1204
1205    /// Whether element `index` is still there, which is the `HasProperty` step
1206    /// `indexOf`/`lastIndexOf`/`includes` run before reading: a view that went out of bounds
1207    /// mid-call has no indices left, so those methods skip rather than compare against
1208    /// `undefined`. That difference is exactly what
1209    /// `indexOf/detached-buffer-during-fromIndex-returns-minus-one-for-undefined` pins.
1210    fn has(&self, index: usize) -> bool {
1211        index < self.object.typed_array_length().unwrap_or(0)
1212    }
1213
1214    /// Every element as it stands right now, for the methods that permute their input.
1215    fn to_vec(&self) -> Vec<Value> {
1216        self.iter().map(|(_, value)| value).collect()
1217    }
1218}
1219
1220/// Read the elements of a typed array, which `join`/`set`/`slice` all need.
1221fn elements_of(interp: &Interp<'_>, this: &Value) -> JsResult<Elements> {
1222    let object = this
1223        .as_object()
1224        .ok_or_else(|| interp.type_error("not a typed array"))?;
1225    let (_, _, _, length) = validate_view(interp, object)?;
1226    Ok(Elements {
1227        object: object.clone(),
1228        length,
1229    })
1230}
1231
1232/// `a.join(separator)`; `toString` shares it, which is what `Array.prototype.toString` does.
1233fn join(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1234    // §23.2.3.14: `len` comes from the record at validation, and `ToString(separator)`
1235    // runs *after* that — so a separator whose `toString` resizes the buffer still joins
1236    // the original count, with the elements that are no longer there reading as empty.
1237    // Reading the length afterwards made `join/coerced-separator-grow` answer six zeros
1238    // instead of four.
1239    let elements = elements_of(interp, &this)?;
1240    // `ToString(separator)`: a Symbol is a `TypeError`, which `to_js_string`'s total path
1241    // answered as `"Symbol()"` (`join/return-abrupt-from-separator-symbol`).
1242    let separator = match arg(args, 0) {
1243        Value::Undefined => ",".to_string(),
1244        _ => interp.to_string_strict(&arg(args, 0))?,
1245    };
1246    let mut parts = Vec::with_capacity(elements.len());
1247    for (_, element) in elements.iter() {
1248        parts.push(match element {
1249            Value::Undefined | Value::Null => String::new(),
1250            other => interp.to_js_string(&other)?,
1251        });
1252    }
1253    Ok(interp.string(parts.join(&separator)))
1254}
1255
1256/// `a.set(source, offset)` — §23.2.3.24.
1257///
1258/// The source comes in two shapes with **different** rules, and the whole directory turns
1259/// on telling them apart:
1260///
1261/// * a typed array is recognised by its internal slot, and its length is `[[ArrayLength]]`.
1262///   `length` is never read, so a getter planted on `TA.prototype` — or on the source —
1263///   must not run (`typedarray-arg-{src,target}-arraylength-internal`);
1264/// * anything else is `ToObject`'d and measured with `LengthOfArrayLike(src)`, i.e.
1265///   `ToLength(Get(src, "length"))`, which is script and runs `valueOf`.
1266///
1267/// The copy itself is one `Get` and one write per index, **interleaved**, not a
1268/// snapshot-and-write: `array-arg-set-values-in-order` records the target's contents inside
1269/// each source getter and requires the earlier writes to be visible, and
1270/// `target-shrink-mid-iteration` requires a write after a resize that pushed the view out
1271/// of bounds to be dropped rather than land on a stale geometry.
1272fn set_from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1273    // Steps 1–2: the receiver must be a typed array, checked before any conversion. The
1274    // length read *here* is the one the bounds check below uses — a source `length` getter
1275    // that resizes the buffer must not widen or narrow it
1276    // (`target-grow-source-length-getter` asserts the `RangeError` the original length
1277    // produces even though the buffer has since grown).
1278    let target = this
1279        .as_object()
1280        .cloned()
1281        .ok_or_else(|| interp.type_error("not a typed array"))?;
1282    let (_, _, _, target_length) = validate_view(interp, &target)?;
1283    // Steps 3–4. `ToIntegerOrInfinity(offset)` runs script, and a `valueOf` may detach or
1284    // resize the target's buffer — hence the detachment check right after.
1285    let offset = match args.get(1) {
1286        None => 0.0,
1287        Some(value) => to_integer_or_infinity(interp, value)?,
1288    };
1289    if offset < 0.0 {
1290        return Err(interp.range_error("offset is out of range"));
1291    }
1292    let offset = if offset.is_finite() {
1293        offset as usize
1294    } else {
1295        usize::MAX
1296    };
1297    let src = arg(args, 0);
1298
1299    // Step 5: a typed-array source, decided by internal slot.
1300    if let Some(source) = src.as_object().cloned()
1301        && let Some(geometry) = source.typed_array_geometry()
1302    {
1303        let (source_buffer, source_element, source_base, source_length, source_oob) = geometry;
1304        // 5.a: the source's own buffer has to still be attached.
1305        if source_oob {
1306            return Err(
1307                interp.type_error("the source buffer was detached or resized out of bounds")
1308            );
1309        }
1310        // 5.b–c: and so does the target's, *after* the offset conversion ran.
1311        let (target_buffer, target_element, target_base, _) = validate_view(interp, &target)?;
1312        // 5.f–g.
1313        if offset.saturating_add(source_length) > target_length {
1314            return Err(interp.range_error("source is too large"));
1315        }
1316        // `SetTypedArrayFromTypedArray` asks for a **byte-wise** copy when both views share
1317        // one buffer and one element type, precisely so that overlap behaves like `memmove`.
1318        // Copying element by element instead overwrote the source as it went, which turned
1319        // `a.set(a, 1)` into `1,1,1,1` (`typedarray-arg-set-values-same-buffer-same-type`).
1320        if Gc::ptr_eq(&source_buffer, &target_buffer) && source_element == target_element {
1321            let size = source_element.size();
1322            let start = source_base;
1323            let end = source_base + source_length * size;
1324            let destination = target_base + offset * size;
1325            if let Some(storage) = target_buffer.array_buffer_storage() {
1326                let mut storage = storage.borrow_mut();
1327                if !storage.detached && end <= storage.bytes.len() {
1328                    storage.bytes.copy_within(start..end, destination);
1329                }
1330            }
1331            return Ok(Value::Undefined);
1332        }
1333        // 5.h: element by element, converting through each side's element type.
1334        for index in 0..source_length {
1335            let value = source
1336                .typed_array_element(index)
1337                .unwrap_or(Value::Undefined);
1338            set_element(interp, &target, offset + index, value)?;
1339        }
1340        return Ok(Value::Undefined);
1341    }
1342
1343    // Step 6.a: `ToObject(src)`.
1344    let source = interp.object_from(&src)?;
1345    // 6.b: `LengthOfArrayLike(src)` — `Get(src, "length")` then `ToLength`.
1346    let source_length = match interp.get_property(&source, "length")? {
1347        None | Some(Value::Undefined) => 0,
1348        Some(value) => {
1349            let number = interp.to_js_number(&value)?;
1350            if number.is_nan() || number <= 0.0 {
1351                0
1352            } else {
1353                // `ToLength` clamps at 2^53 − 1; anything that large is refused by the
1354                // bounds check rather than allocated.
1355                number.min(9_007_199_254_740_991.0) as usize
1356            }
1357        }
1358    };
1359    // 6.d–e: the target's buffer must still be attached.
1360    ensure_attached(interp, &target)?;
1361    // 6.f.
1362    if offset.saturating_add(source_length) > target_length {
1363        return Err(interp.range_error("source is too large"));
1364    }
1365    // 6.g: one `Get` and one write per index, in order.
1366    for index in 0..source_length {
1367        let value = interp
1368            .get_property(&source, &index.to_string())?
1369            .unwrap_or(Value::Undefined);
1370        set_element(interp, &target, offset + index, value)?;
1371    }
1372    Ok(Value::Undefined)
1373}
1374
1375/// `TypedArraySetElement(target, index, value)` — §10.4.5.16.
1376///
1377/// The number conversion runs **first** (it is `ToPrimitive` + `ToNumber`, so it can run
1378/// script), and only then does the *current* geometry decide whether anything is written.
1379/// Re-deriving the view here is what makes a resize during the loop drop the remaining
1380/// writes instead of landing on a stale byte offset (`target-shrink-mid-iteration`).
1381fn set_element(
1382    interp: &mut Interp<'_>,
1383    target: &Gc<JsObject>,
1384    index: usize,
1385    value: Value,
1386) -> JsResult<()> {
1387    let Some((buffer, element, base, length, out_of_bounds)) = target.typed_array_geometry() else {
1388        return Ok(());
1389    };
1390    let stored = interp.element_value(element, value)?;
1391    // `IsValidIntegerIndex`: false when the view no longer fits, or when the index is past
1392    // the length it has *now*.
1393    if out_of_bounds || index >= length {
1394        return Ok(());
1395    }
1396    let Some(storage) = buffer.array_buffer_storage() else {
1397        return Ok(());
1398    };
1399    let mut storage = storage.borrow_mut();
1400    if storage.detached {
1401        return Ok(());
1402    }
1403    element
1404        .write(&mut storage.bytes, base + index * element.size(), &stored)
1405        .map_err(|reason| match reason {
1406            NOT_A_BIGINT => interp.type_error("cannot convert a Number to a BigInt"),
1407            other => interp.type_error(other),
1408        })
1409}
1410
1411/// Refuse a view whose buffer is gone, without objecting to one merely resized out of
1412/// bounds.
1413///
1414/// `set` runs this *between* its conversions: the spec checks `IsDetachedBuffer` there, and
1415/// a view the buffer has shrunk away from is still a view — its writes are simply dropped.
1416fn ensure_attached(interp: &Interp<'_>, target: &Gc<JsObject>) -> JsResult<()> {
1417    let Some((buffer, _, _, _, _)) = target.typed_array_geometry() else {
1418        return Err(interp.type_error("not a typed array"));
1419    };
1420    let detached = buffer
1421        .array_buffer_storage()
1422        .is_some_and(|storage| storage.borrow().detached);
1423    if detached {
1424        return Err(interp.type_error("the buffer is detached"));
1425    }
1426    Ok(())
1427}
1428
1429/// `a.fill(value, start, end)`.
1430fn fill(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1431    let object = this
1432        .as_object()
1433        .ok_or_else(|| interp.type_error("not a typed array"))?
1434        .clone();
1435    let (buffer, element, base, length) = validate_view(interp, &object)?;
1436    // §23.2.3.9 steps 2–4: the *value* is converted first, then `start`, then `end`, and
1437    // every one of the three can run script. All three used `Value::to_number`, which
1438    // answers `NaN` for an object without calling `valueOf` — so none of them ran, and
1439    // `fill/coerced-value-start-end-resize` saw a view that had never been resized.
1440    let stored = interp.element_value(element, arg(args, 0))?;
1441    let length_i = length as i64;
1442    let start = clamp_index(
1443        match args.get(1) {
1444            None => 0.0,
1445            Some(value) => to_integer_or_infinity(interp, value)?,
1446        },
1447        length_i,
1448        0,
1449    );
1450    let end = clamp_index(
1451        match args.get(2) {
1452            None | Some(Value::Undefined) => length as f64,
1453            Some(value) => to_integer_or_infinity(interp, value)?,
1454        },
1455        length_i,
1456        length_i,
1457    );
1458    // …and the view has to still fit afterwards. A length-tracking view does (the write
1459    // loop simply runs off the end, which `write_element` drops), but a fixed-length one
1460    // that no longer fits is a `TypeError` rather than a no-op.
1461    revalidate(interp, &object)?;
1462    for index in start as usize..end.max(start) as usize {
1463        write_element(interp, &buffer, element, base, index, stored.clone())?;
1464    }
1465    Ok(Value::Object(object))
1466}
1467
1468/// `%TypedArray%`: the intrinsic every view constructor inherits from.
1469///
1470/// Absent until now, which is why `Object.getPrototypeOf(Int8Array)` answered
1471/// `Function.prototype` and `Object.getPrototypeOf(Int8Array).from` was `undefined`. It is
1472/// not a constructor — calling or `new`-ing it is a `TypeError` — it exists to hold the
1473/// shared statics and `Symbol.species`.
1474fn install_typed_array_intrinsic(interp: &mut Interp<'_>, shared: &Gc<JsObject>) -> Gc<JsObject> {
1475    let intrinsic = interp.new_native("TypedArray", 0, typed_array_intrinsic_call);
1476    // `from` and `of` go on before `prototype`, because `Object.getOwnPropertyNames` reports
1477    // insertion order and the reference lists them in this order.
1478    define_method(
1479        &intrinsic,
1480        "from",
1481        1,
1482        from as crate::object::NativeFn,
1483        interp,
1484    );
1485    define_method(&intrinsic, "of", 0, of, interp);
1486    // `%TypedArray%.prototype` is the shared prototype, and it is read-only.
1487    intrinsic.define(
1488        "prototype",
1489        Property::prototype_of(Value::Object(shared.clone()), false),
1490    );
1491    // The constructor property points back, which is what `TA.prototype.constructor === TA`
1492    // and a species lookup both rely on.
1493    shared.define(
1494        "constructor",
1495        Property {
1496            value: Some(Value::Object(intrinsic.clone())),
1497            writable: true,
1498            enumerable: false,
1499            configurable: true,
1500            ..Property::default()
1501        },
1502    );
1503    // `get %TypedArray%[Symbol.species]` answers `this`, so a subclass that does not
1504    // override it still produces instances of itself.
1505    install_species_accessor(&intrinsic, interp);
1506    intrinsic
1507}
1508
1509/// `%TypedArray%` is abstract: both forms of construction are refused.
1510fn typed_array_intrinsic_call(
1511    interp: &mut Interp<'_>,
1512    _this: Value,
1513    _args: &[Value],
1514) -> JsResult<Value> {
1515    Err(interp.type_error("Abstract class TypedArray not directly constructable"))
1516}
1517
1518/// `%TypedArray%.from(source, mapfn, thisArg)`.
1519///
1520/// The result is built by calling `this` as a constructor, which is what makes
1521/// `MyArray.from(...)` answer a `MyArray` rather than an `Int8Array`.
1522fn from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1523    let source = arg(args, 0);
1524    let mapper = match args.get(1) {
1525        None | Some(Value::Undefined) => None,
1526        Some(candidate) if matches!(candidate, Value::Object(o) if o.is_callable()) => {
1527            Some(candidate.clone())
1528        }
1529        Some(_) => return Err(interp.type_error("mapfn is not a function")),
1530    };
1531    let this_arg = arg(args, 2);
1532    // The source is read either through `Symbol.iterator` or as an array-like, the same
1533    // choice the constructor makes.
1534    let values = if interp.has_iterator(&source)? {
1535        interp.collect_iterable(&source)?
1536    } else {
1537        // `ToIndex(Get(items, "length"))` — a throwing `valueOf` there must propagate
1538        // (`from/arylk-to-length-error`), and a Symbol is a `TypeError`. `ToLength` swallowed
1539        // both by answering `0`.
1540        match source.as_object().cloned() {
1541            Some(object) => {
1542                let raw_length = interp.get_property(&object, "length")?;
1543                let count = match &raw_length {
1544                    Some(value) => interp.to_index(value)?,
1545                    None => 0,
1546                };
1547                let mut items = Vec::with_capacity(count.min(1024));
1548                for index in 0..count {
1549                    items.push(
1550                        interp
1551                            .get_property(&object, &index.to_string())?
1552                            .unwrap_or(Value::Undefined),
1553                    );
1554                }
1555                items
1556            }
1557            None => Vec::new(),
1558        }
1559    };
1560    // The result is created *before* the mapper runs, and each mapped value is written as
1561    // soon as it comes back (§23.2.1.2.1 steps 8–10). Both halves are observable: the
1562    // target's length is fixed at that point, so a mapper that resizes the buffer the target
1563    // is a view of makes the remaining writes land out of bounds and be dropped — not throw
1564    // (`from/from-array-mapper-makes-result-out-of-bounds`, which expects the result to keep
1565    // the one element that still fit).
1566    let (created, buffer, element, base) =
1567        typed_array_construct_target(interp, &this, values.len())?;
1568    for (index, value) in values.into_iter().enumerate() {
1569        let mapped = match &mapper {
1570            Some(mapper) => interp.call_value(
1571                mapper.clone(),
1572                this_arg.clone(),
1573                vec![value, Value::Int(index as i32)],
1574            )?,
1575            None => value,
1576        };
1577        write_element(interp, &buffer, element, base, index, mapped)?;
1578    }
1579    Ok(created)
1580}
1581
1582/// `%TypedArray%.of(...items)`.
1583fn of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1584    typed_array_from_values(interp, &this, args)
1585}
1586
1587/// Build a view by calling `constructor` with a length, then filling it.
1588fn typed_array_from_values(
1589    interp: &mut Interp<'_>,
1590    constructor: &Value,
1591    values: &[Value],
1592) -> JsResult<Value> {
1593    let (created, buffer, element, base) =
1594        typed_array_construct_target(interp, constructor, values.len())?;
1595    for (index, value) in values.iter().enumerate() {
1596        write_element(interp, &buffer, element, base, index, value.clone())?;
1597    }
1598    Ok(created)
1599}
1600
1601/// `Construct(C, « len »)` plus the bounds check, as `%TypedArray%.from`/`of` need it.
1602///
1603/// Answers the view along with where to write: the caller interleaves its own per-element
1604/// work with the stores, and an out-of-bounds store must be dropped rather than refused.
1605fn typed_array_construct_target(
1606    interp: &mut Interp<'_>,
1607    constructor: &Value,
1608    len: usize,
1609) -> JsResult<(Value, Gc<JsObject>, ElementType, usize)> {
1610    if !matches!(constructor, Value::Object(o) if o.is_callable()) {
1611        return Err(interp.type_error("not a constructor"));
1612    }
1613    let created = interp.construct(
1614        constructor.clone(),
1615        constructor.clone(),
1616        vec![Value::Int(len as i32)],
1617    )?;
1618    let Some(object) = created.as_object().cloned() else {
1619        return Err(interp.type_error("constructor did not answer an object"));
1620    };
1621    let Some(element) = object.typed_array_element_type() else {
1622        return Err(interp.type_error("constructor did not answer a typed array"));
1623    };
1624    // The constructor is arbitrary script: it may answer a shorter view than asked for,
1625    // which the spec refuses rather than writing past the end.
1626    let available = object.typed_array_length().unwrap_or(0);
1627    if len > available {
1628        return Err(interp.type_error("derived typed array has an insufficient length"));
1629    }
1630    let Some((buffer, _, base, _)) = object.typed_array_parts() else {
1631        return Err(interp.type_error("constructor did not answer a typed array"));
1632    };
1633    Ok((created, buffer, element, base))
1634}
1635
1636/// A new view of `element` type holding `values`, which is what `map`/`filter`/`slice`
1637/// and friends answer with.
1638///
1639/// `%TypedArray%.prototype.map` is *not* `Array.prototype.map`: the result is a typed array
1640/// of the same element type, not an ordinary array, which is why the spec goes through
1641/// `TypedArraySpeciesCreate` rather than `ArraySpeciesCreate`.
1642fn new_view(
1643    interp: &mut Interp<'_>,
1644    element: ElementType,
1645    values: &[Value],
1646) -> JsResult<Gc<JsObject>> {
1647    let fresh = blank_view(interp, element, values.len())?;
1648    write_back(interp, &fresh, element, values)?;
1649    Ok(fresh)
1650}
1651
1652/// A fresh, zero-filled view of `count` elements of `element`, with the intrinsic prototype.
1653///
1654/// The zero fill is not a shortcut: `TypedArrayCreateFromConstructor` builds the block with
1655/// `CreateByteDataBlock`, which is zeroed, and the caller then decides what to store. Going
1656/// through `new_view` with a vector of `Value::Int(0)` instead is what broke every BigInt
1657/// species test — `0` is not convertible to a BigInt, so the *blank* result view threw
1658/// before the callback ever ran.
1659fn blank_view(
1660    interp: &mut Interp<'_>,
1661    element: ElementType,
1662    count: usize,
1663) -> JsResult<Gc<JsObject>> {
1664    let proto = interp
1665        .realm
1666        .array_buffer_proto
1667        .clone()
1668        .unwrap_or_else(|| interp.realm.object_proto.clone());
1669    let buffer = interp.new_object(Some(proto));
1670    buffer.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed(vec![
1671        0;
1672        count * element.size()
1673    ]))));
1674    let proto = interp
1675        .realm
1676        .typed_array_protos
1677        .get(element as usize)
1678        .cloned()
1679        .or_else(|| interp.realm.typed_array_proto.clone())
1680        .unwrap_or_else(|| interp.realm.object_proto.clone());
1681    let fresh = interp.new_object(Some(proto));
1682    fresh.set_typed_array(buffer, element, 0, ViewLength::Fixed(count));
1683    Ok(fresh)
1684}
1685
1686/// `TypedArraySpeciesCreate(receiver, len)`: the view a method answers with.
1687///
1688/// The spec does not simply build a view of the same type. It reads `receiver.constructor`,
1689/// then that function's `Symbol.species`, and calls it with the length — so a subclass can
1690/// redirect the result and a test can assert the override was honoured, or that a throwing
1691/// species propagates. Falling straight through to `new_view` made every `speciesctor` case
1692/// fail even though the elements were right.
1693fn species_create(
1694    interp: &mut Interp<'_>,
1695    receiver: &Gc<JsObject>,
1696    element: ElementType,
1697    values: &[Value],
1698) -> JsResult<Gc<JsObject>> {
1699    let (object, actual_element) = species_create_view(interp, receiver, element, values.len())?;
1700    write_back(interp, &object, actual_element, values)?;
1701    Ok(object)
1702}
1703
1704/// `TypedArraySpeciesCreate(O, argumentsList)` for a caller that supplies the arguments.
1705///
1706/// `subarray` is the one that does: the spec passes `(buffer, byteOffset[, length])` straight
1707/// to `TypedArrayCreateFromConstructor`, and the constructor is then what rejects a length
1708/// that no longer fits.
1709fn species_construct(
1710    interp: &mut Interp<'_>,
1711    receiver: &Gc<JsObject>,
1712    arguments: Vec<Value>,
1713) -> JsResult<Value> {
1714    let constructor = interp.get_property(receiver, "constructor")?;
1715    let species = match &constructor {
1716        None | Some(Value::Undefined) => None,
1717        Some(Value::Object(constructor)) => {
1718            let key = interp
1719                .realm
1720                .well_known_key(crate::interp::WellKnown::Species);
1721            interp.get_property_key(constructor, &key)?
1722        }
1723        Some(_) => return Err(interp.type_error("constructor is not an object")),
1724    };
1725    let species = match species {
1726        // No `constructor`/`Symbol.species` override: `%TypedArray%` is the default, which
1727        // for a view means the intrinsic constructor of its own element type.
1728        Some(Value::Null) | None | Some(Value::Undefined) => {
1729            let Some((_, element, _, _)) = receiver.typed_array_stored() else {
1730                return Err(interp.type_error("not a typed array"));
1731            };
1732            let global = interp.realm.global.clone();
1733            match interp.get_property(&global, element.name())? {
1734                Some(constructor @ Value::Object(_)) => constructor,
1735                _ => return Err(interp.type_error("not a typed array")),
1736            }
1737        }
1738        Some(other) => other,
1739    };
1740    if !matches!(&species, Value::Object(o) if o.is_callable()) {
1741        return Err(interp.type_error("species is not a constructor"));
1742    }
1743    let created = interp.construct(species.clone(), species, arguments)?;
1744    if created
1745        .as_object()
1746        .and_then(|o| o.typed_array_element_type())
1747        .is_none()
1748    {
1749        return Err(interp.type_error("species constructor did not answer a typed array"));
1750    }
1751    Ok(created)
1752}
1753
1754/// `TypedArraySpeciesCreate(O, « count »)`, without filling the result in.
1755///
1756/// Split out because the *creation* is observable and has to happen before the source is
1757/// read: a species constructor may resize the buffer the receiver is a view of, and
1758/// `slice`/`map` are asserted to see that (`slice/speciesctor-resize`,
1759/// `map/speciesctor-resizable-buffer-shrink`). Answering `(view, element type)` rather than
1760/// a filled view is what lets the caller interleave its own reads.
1761fn species_create_view(
1762    interp: &mut Interp<'_>,
1763    receiver: &Gc<JsObject>,
1764    element: ElementType,
1765    count: usize,
1766) -> JsResult<(Gc<JsObject>, ElementType)> {
1767    let constructor = interp.get_property(receiver, "constructor")?;
1768    let species = match &constructor {
1769        // `undefined` — or no `constructor` at all — means "use the default".
1770        None | Some(Value::Undefined) => None,
1771        Some(Value::Object(constructor)) => {
1772            let key = interp
1773                .realm
1774                .well_known_key(crate::interp::WellKnown::Species);
1775            interp.get_property_key(constructor, &key)?
1776        }
1777        // Anything else is neither absent nor an object, and `SpeciesConstructor` refuses
1778        // it outright: `sample.constructor = 42` makes `sample.map(f)` a `TypeError`.
1779        Some(_) => return Err(interp.type_error("constructor is not an object")),
1780    };
1781    let species = match species {
1782        Some(Value::Null) | None | Some(Value::Undefined) => {
1783            return Ok((blank_view(interp, element, count)?, element));
1784        }
1785        Some(other) => other,
1786    };
1787    if !matches!(&species, Value::Object(o) if o.is_callable()) {
1788        return Err(interp.type_error("species is not a constructor"));
1789    }
1790    let created = interp.construct(species.clone(), species, vec![Value::Int(count as i32)])?;
1791    let Some(object) = created.as_object().cloned() else {
1792        return Err(interp.type_error("species constructor did not answer an object"));
1793    };
1794    let Some(actual_element) = object.typed_array_element_type() else {
1795        return Err(interp.type_error("species constructor did not answer a typed array"));
1796    };
1797    // A species is allowed to answer a *longer* view but not a shorter one: the spec
1798    // checks `srcLength <= targetLength`.
1799    let available = object.typed_array_length().unwrap_or(0);
1800    if count > available {
1801        return Err(interp.type_error("derived typed array has an insufficient length"));
1802    }
1803    Ok((object, actual_element))
1804}
1805
1806/// The receiver as `(buffer, element, byte offset, element count)` after
1807/// `ValidateTypedArray`.
1808///
1809/// §10.4.5.13 step 3 makes a view whose bytes no longer fit a `TypeError`, exactly like a
1810/// detached one — the two are the same "gone" state from the script's side, and the
1811/// difference from an *empty* view is observable: `new Uint8Array(rab, 40)` on a 40-byte
1812/// buffer is empty and legal, while the same view after `rab.resize(8)` is out of bounds
1813/// and must throw. One test per method pins that (`return-abrupt-from-this-out-of-bounds`),
1814/// so every method funnels through here rather than asking for its own length.
1815fn validate_view(
1816    interp: &Interp<'_>,
1817    object: &Gc<JsObject>,
1818) -> JsResult<(Gc<JsObject>, ElementType, usize, usize)> {
1819    let Some((buffer, element, offset, length, out_of_bounds)) = object.typed_array_geometry()
1820    else {
1821        return Err(interp.type_error("not a typed array"));
1822    };
1823    if out_of_bounds {
1824        return Err(interp.type_error("the buffer was detached or resized out of bounds"));
1825    }
1826    Ok((buffer, element, offset, length))
1827}
1828
1829/// The receiver as `(elements, element type)`, the shape every method here starts from.
1830///
1831/// A typed array is never a plain object: unlike `Array.prototype`'s methods, these do not
1832/// run `ToObject` on anything, they refuse a receiver that is not a view.
1833fn view_parts(interp: &mut Interp<'_>, this: &Value) -> JsResult<(Elements, ElementType)> {
1834    let Some(object) = this.as_object() else {
1835        return Err(interp.type_error("not a typed array"));
1836    };
1837    let (_, element, _, _) = validate_view(interp, object)?;
1838    Ok((elements_of(interp, this)?, element))
1839}
1840
1841/// `ValidateTypedArray` again, after a coercion that may have run script.
1842///
1843/// `fill`, `copyWithin` and `slice` convert their own arguments *between* their first
1844/// validation and the copy, and those conversions are observable: a `valueOf` can resize
1845/// the buffer until the view no longer fits. The spec has these three run the check again
1846/// (it is what makes the answer a `TypeError` rather than a silent read of `undefined`),
1847/// and the split is per method, not a general rule — `map`, `join` and `at` do not, which
1848/// is why their out-of-bounds elements are `undefined` instead of an exception. Both halves
1849/// are pinned by test262, one directory at a time.
1850fn revalidate(interp: &Interp<'_>, object: &Gc<JsObject>) -> JsResult<()> {
1851    match object.typed_array_geometry() {
1852        Some((_, _, _, _, true)) => {
1853            Err(interp.type_error("the buffer was detached or resized out of bounds"))
1854        }
1855        Some(_) => Ok(()),
1856        None => Err(interp.type_error("not a typed array")),
1857    }
1858}
1859
1860/// The callback a typed-array method requires, or a `TypeError`.
1861fn typed_callback(interp: &mut Interp<'_>, args: &[Value]) -> JsResult<Value> {
1862    let callback = arg(args, 0);
1863    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
1864        return Err(interp.type_error("callback is not a function"));
1865    }
1866    Ok(callback)
1867}
1868
1869/// Call `callback(element, index, receiver)` for every element.
1870fn call_typed(
1871    interp: &mut Interp<'_>,
1872    callback: &Value,
1873    value: Value,
1874    index: usize,
1875    receiver: &Gc<JsObject>,
1876    this_arg: Value,
1877) -> JsResult<Value> {
1878    interp.call_value(
1879        callback.clone(),
1880        this_arg,
1881        vec![
1882            value,
1883            Value::Int(index as i32),
1884            Value::Object(receiver.clone()),
1885        ],
1886    )
1887}
1888
1889/// `a.at(index)`: negative counts from the end, out of range is `undefined`.
1890fn at(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1891    let (elements, _) = view_parts(interp, &this)?;
1892    // `len` is the one the record gave at validation; the *read* below happens after
1893    // `ToIntegerOrInfinity` has run, so a `valueOf` that shrinks the buffer makes this
1894    // answer `undefined` even though the index is inside the original length.
1895    // `to_number()` could not: it answers `NaN` for an object instead of calling `valueOf`,
1896    // which is how `at/coerced-index-resize` used to see the stale element.
1897    let length = elements.len() as f64;
1898    let raw = to_integer_or_infinity(interp, &arg(args, 0))?;
1899    let index = if raw < 0.0 { length + raw } else { raw };
1900    if index < 0.0 || index >= length {
1901        return Ok(Value::Undefined);
1902    }
1903    Ok(elements.get(index as usize))
1904}
1905
1906/// `a.every(f)` / `a.some(f)`.
1907fn every(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1908    quantify(interp, this, args, false)
1909}
1910
1911fn some(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1912    quantify(interp, this, args, true)
1913}
1914
1915fn quantify(
1916    interp: &mut Interp<'_>,
1917    this: Value,
1918    args: &[Value],
1919    want_any: bool,
1920) -> JsResult<Value> {
1921    let receiver = this
1922        .as_object()
1923        .cloned()
1924        .ok_or_else(|| interp.type_error("not a typed array"))?;
1925    let (elements, _) = view_parts(interp, &this)?;
1926    let callback = typed_callback(interp, args)?;
1927    let this_arg = crate::builtins::array::callback_this(args);
1928    for (index, value) in elements.iter() {
1929        let answer = call_typed(interp, &callback, value, index, &receiver, this_arg.clone())?;
1930        // `every` stops on the first falsy answer, `some` on the first truthy one.
1931        if answer.to_boolean() == want_any {
1932            return Ok(Value::Bool(want_any));
1933        }
1934    }
1935    Ok(Value::Bool(!want_any))
1936}
1937
1938fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1939    let receiver = this
1940        .as_object()
1941        .cloned()
1942        .ok_or_else(|| interp.type_error("not a typed array"))?;
1943    let (elements, _) = view_parts(interp, &this)?;
1944    let callback = typed_callback(interp, args)?;
1945    let this_arg = crate::builtins::array::callback_this(args);
1946    for (index, value) in elements.iter() {
1947        call_typed(interp, &callback, value, index, &receiver, this_arg.clone())?;
1948    }
1949    Ok(Value::Undefined)
1950}
1951
1952fn map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1953    let receiver = this
1954        .as_object()
1955        .cloned()
1956        .ok_or_else(|| interp.type_error("not a typed array"))?;
1957    let (elements, element_type) = view_parts(interp, &this)?;
1958    let callback = typed_callback(interp, args)?;
1959    let this_arg = crate::builtins::array::callback_this(args);
1960    // §23.2.3.19 creates the result *before* the loop, so a species constructor that
1961    // resizes the buffer makes the remaining elements read as `undefined` — which is what
1962    // `map/speciesctor-resizable-buffer-shrink` asserts, callback by callback. And unlike
1963    // `slice`, `map` does not re-check the source afterwards: it walks elements, so an
1964    // out-of-bounds read is `undefined` rather than a `TypeError`.
1965    let (target, target_element) =
1966        species_create_view(interp, &receiver, element_type, elements.len())?;
1967    let Some((buffer, _, base, _)) = target.typed_array_parts() else {
1968        return Err(interp.type_error("not a typed array"));
1969    };
1970    for (index, value) in elements.iter() {
1971        let mapped = call_typed(interp, &callback, value, index, &receiver, this_arg.clone())?;
1972        write_element(interp, &buffer, target_element, base, index, mapped)?;
1973    }
1974    Ok(Value::Object(target))
1975}
1976
1977fn filter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1978    let receiver = this
1979        .as_object()
1980        .cloned()
1981        .ok_or_else(|| interp.type_error("not a typed array"))?;
1982    let (elements, element_type) = view_parts(interp, &this)?;
1983    let callback = typed_callback(interp, args)?;
1984    let this_arg = crate::builtins::array::callback_this(args);
1985    let mut out = Vec::new();
1986    for (index, value) in elements.iter() {
1987        let keep = call_typed(
1988            interp,
1989            &callback,
1990            value.clone(),
1991            index,
1992            &receiver,
1993            this_arg.clone(),
1994        )?;
1995        if keep.to_boolean() {
1996            out.push(value);
1997        }
1998    }
1999    Ok(Value::Object(species_create(
2000        interp,
2001        &receiver,
2002        element_type,
2003        &out,
2004    )?))
2005}
2006
2007fn reduce(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2008    reduce_with(interp, this, args, false)
2009}
2010
2011fn reduce_right(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2012    reduce_with(interp, this, args, true)
2013}
2014
2015fn reduce_with(
2016    interp: &mut Interp<'_>,
2017    this: Value,
2018    args: &[Value],
2019    right_to_left: bool,
2020) -> JsResult<Value> {
2021    let receiver = this
2022        .as_object()
2023        .cloned()
2024        .ok_or_else(|| interp.type_error("not a typed array"))?;
2025    let (elements, _) = view_parts(interp, &this)?;
2026    let callback = typed_callback(interp, args)?;
2027    let mut indices: Vec<usize> = (0..elements.len()).collect();
2028    if right_to_left {
2029        indices.reverse();
2030    }
2031    let mut ordered = indices.into_iter();
2032    // "`initialValue` is present" is `argCount > 1`, not "the value is not `undefined`":
2033    // `reduce(fn, undefined)` passes `undefined` as the accumulator and never calls the
2034    // callback, even on an empty view (`reduce/callbackfn-not-called-on-empty`).
2035    let mut accumulator = match args.get(1) {
2036        Some(value) if args.len() > 1 => value.clone(),
2037        _ => match ordered.next() {
2038            Some(index) => elements.get(index),
2039            None => {
2040                return Err(interp.type_error("Reduce of empty array with no initial value"));
2041            }
2042        },
2043    };
2044    for index in ordered {
2045        accumulator = interp.call_value(
2046            callback.clone(),
2047            Value::Undefined,
2048            vec![
2049                accumulator,
2050                elements.get(index),
2051                Value::Int(index as i32),
2052                Value::Object(receiver.clone()),
2053            ],
2054        )?;
2055    }
2056    Ok(accumulator)
2057}
2058
2059fn find(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2060    find_with(interp, this, args, FindKind::Value, false)
2061}
2062
2063fn find_index(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2064    find_with(interp, this, args, FindKind::Index, false)
2065}
2066
2067fn find_last(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2068    find_with(interp, this, args, FindKind::Value, true)
2069}
2070
2071fn find_last_index(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2072    find_with(interp, this, args, FindKind::Index, true)
2073}
2074
2075#[derive(Clone, Copy)]
2076enum FindKind {
2077    Value,
2078    Index,
2079}
2080
2081fn find_with(
2082    interp: &mut Interp<'_>,
2083    this: Value,
2084    args: &[Value],
2085    kind: FindKind,
2086    from_end: bool,
2087) -> JsResult<Value> {
2088    let receiver = this
2089        .as_object()
2090        .cloned()
2091        .ok_or_else(|| interp.type_error("not a typed array"))?;
2092    let (elements, _) = view_parts(interp, &this)?;
2093    let callback = typed_callback(interp, args)?;
2094    let this_arg = crate::builtins::array::callback_this(args);
2095    let mut indices: Vec<usize> = (0..elements.len()).collect();
2096    if from_end {
2097        indices.reverse();
2098    }
2099    for index in indices {
2100        let value = elements.get(index);
2101        let answer = call_typed(
2102            interp,
2103            &callback,
2104            value.clone(),
2105            index,
2106            &receiver,
2107            this_arg.clone(),
2108        )?;
2109        if answer.to_boolean() {
2110            return Ok(match kind {
2111                FindKind::Value => value,
2112                FindKind::Index => Value::Int(index as i32),
2113            });
2114        }
2115    }
2116    Ok(match kind {
2117        FindKind::Value => Value::Undefined,
2118        FindKind::Index => Value::Int(-1),
2119    })
2120}
2121
2122fn index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2123    search(interp, this, args, SearchKind::IndexOf, false)
2124}
2125
2126fn last_index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2127    search(interp, this, args, SearchKind::IndexOf, true)
2128}
2129
2130fn includes(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2131    search(interp, this, args, SearchKind::Includes, false)
2132}
2133
2134#[derive(Clone, Copy, PartialEq, Eq)]
2135enum SearchKind {
2136    /// `===`-style, so `NaN` is never found.
2137    IndexOf,
2138    /// `SameValueZero`, so `NaN` is found, and the answer is a boolean.
2139    Includes,
2140}
2141
2142fn search(
2143    interp: &mut Interp<'_>,
2144    this: Value,
2145    args: &[Value],
2146    kind: SearchKind,
2147    from_end: bool,
2148) -> JsResult<Value> {
2149    let (elements, _) = view_parts(interp, &this)?;
2150    let needle = arg(args, 0);
2151    let length = elements.len();
2152    // §23.2.3.13 step 5 / §23.2.3.15 step 5 / §23.2.3.16 step 5: an empty view answers
2153    // "not found" **before** `fromIndex` is converted. Converting first ran
2154    // `fromIndex.valueOf` — or threw its error — where the spec has already returned
2155    // (`includes/length-zero-returns-false`, and the same file for `indexOf` and
2156    // `lastIndexOf`).
2157    if length == 0 {
2158        return Ok(match kind {
2159            SearchKind::Includes => Value::Bool(false),
2160            _ => Value::Int(-1),
2161        });
2162    }
2163    // `fromIndex` is `ToIntegerOrInfinity`, so a Symbol here is a `TypeError` — which is
2164    // why the conversion has to happen even when the answer is already decided. Ignoring
2165    // the argument made `includes(7, Symbol())` return cleanly instead of throwing.
2166    // "`fromIndex` was **not passed**" is `args.len() <= 1`. An explicit `undefined` is
2167    // converted like any other value — `ToIntegerOrInfinity(undefined)` is `0`, so
2168    // `lastIndexOf(43, undefined)` searches from index 0 and answers `-1`
2169    // (`lastIndexOf/tointeger-fromindex`).
2170    let missing = args.len() <= 1;
2171    let start = if from_end {
2172        // `lastIndexOf`: the default is the last index, and a negative offset counts back
2173        // from the end; anything below zero means "not found".
2174        let raw = if missing {
2175            length as f64
2176        } else {
2177            to_integer_or_infinity(interp, &arg(args, 1))?
2178        };
2179        if raw < 0.0 {
2180            match (length as f64 + raw) as i64 {
2181                n if n < 0 => None,
2182                n => Some(n as usize),
2183            }
2184        } else {
2185            Some((raw.min(length as f64) as usize).min(length.saturating_sub(1)))
2186        }
2187    } else {
2188        // `indexOf`/`includes`: the default is the first index, and a negative offset
2189        // counts back from the end but clamps to zero.
2190        let raw = if missing {
2191            0.0
2192        } else {
2193            to_integer_or_infinity(interp, &arg(args, 1))?
2194        };
2195        if raw >= 0.0 {
2196            Some(raw.min(length as f64) as usize)
2197        } else {
2198            Some(((length as f64 + raw).max(0.0)) as usize)
2199        }
2200    };
2201    let mut order: Vec<usize> = match start {
2202        None => Vec::new(),
2203        Some(start) if from_end => (0..=start.min(length.saturating_sub(1))).rev().collect(),
2204        Some(start) => (start..length).collect(),
2205    };
2206    if length == 0 {
2207        order.clear();
2208    }
2209    for index in order {
2210        if !elements.has(index) {
2211            // §23.2.3.13 step 8.b: `includes` reads an **invalid** index as `undefined`,
2212            // where `indexOf`/`lastIndexOf` skip it. That is what makes a view the buffer
2213            // was detached or shrunk away from "include `undefined`"
2214            // (`includes/detached-buffer-during-fromIndex-returns-true-for-undefined`,
2215            // `…/search-undefined-after-shrinking-buffer`).
2216            if kind == SearchKind::Includes && needle.same_value_zero(&Value::Undefined) {
2217                return Ok(Value::Bool(true));
2218            }
2219            continue;
2220        }
2221        let value = elements.get(index);
2222        let found = match kind {
2223            SearchKind::IndexOf => value.strict_equals(&needle),
2224            // `includes` uses SameValueZero, which finds a `NaN` that `indexOf` cannot.
2225            SearchKind::Includes => value.same_value_zero(&needle),
2226        };
2227        if found {
2228            return Ok(match kind {
2229                SearchKind::IndexOf => Value::Int(index as i32),
2230                SearchKind::Includes => Value::Bool(true),
2231            });
2232        }
2233    }
2234    Ok(match kind {
2235        SearchKind::IndexOf => Value::Int(-1),
2236        SearchKind::Includes => Value::Bool(false),
2237    })
2238}
2239
2240/// `a.reverse()`: in place, and it answers the receiver.
2241fn reverse(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2242    let object = this
2243        .as_object()
2244        .cloned()
2245        .ok_or_else(|| interp.type_error("not a typed array"))?;
2246    let (elements, element_type) = view_parts(interp, &this)?;
2247    let mut items = elements.to_vec();
2248    items.reverse();
2249    let elements = items;
2250    write_back(interp, &object, element_type, &elements)?;
2251    Ok(Value::Object(object))
2252}
2253
2254fn sort(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2255    let object = this
2256        .as_object()
2257        .cloned()
2258        .ok_or_else(|| interp.type_error("not a typed array"))?;
2259    let (elements, element_type) = view_parts(interp, &this)?;
2260    let mut elements = elements.to_vec();
2261    match args.first() {
2262        // The default order is numeric for a typed array, unlike `Array.prototype.sort`'s
2263        // string order — `new Int32Array([10, 9]).sort()` is `[9, 10]`.
2264        None | Some(Value::Undefined) => {
2265            if element_type.is_bigint() {
2266                elements.sort_by(compare_bigints);
2267            } else {
2268                elements.sort_by(typed_array_sort_compare);
2269            }
2270        }
2271        Some(comparator) if matches!(comparator, Value::Object(o) if o.is_callable()) => {
2272            // A comparator is arbitrary script, so Rust's sort cannot be told it is a
2273            // total order; this merge sort keeps the comparison count deterministic.
2274            merge_sort_typed(interp, &mut elements, comparator)?;
2275        }
2276        Some(_) => return Err(interp.type_error("comparator is not a function")),
2277    }
2278    write_back(interp, &object, element_type, &elements)?;
2279    Ok(Value::Object(object))
2280}
2281
2282fn compare_bigints(a: &Value, b: &Value) -> std::cmp::Ordering {
2283    match (a, b) {
2284        (Value::BigInt(a), Value::BigInt(b)) => a.cmp(b),
2285        _ => std::cmp::Ordering::Equal,
2286    }
2287}
2288
2289fn merge_sort_typed(
2290    interp: &mut Interp<'_>,
2291    items: &mut Vec<Value>,
2292    comparator: &Value,
2293) -> JsResult<()> {
2294    if items.len() <= 1 {
2295        return Ok(());
2296    }
2297    let mid = items.len() / 2;
2298    let mut right = items.split_off(mid);
2299    merge_sort_typed(interp, items, comparator)?;
2300    merge_sort_typed(interp, &mut right, comparator)?;
2301    let mut merged = Vec::with_capacity(items.len() + right.len());
2302    let mut left_iter = std::mem::take(items).into_iter().peekable();
2303    let mut right_iter = right.into_iter().peekable();
2304    loop {
2305        match (left_iter.peek(), right_iter.peek()) {
2306            (Some(left), Some(right_value)) => {
2307                let answer = interp.call_value(
2308                    comparator.clone(),
2309                    Value::Undefined,
2310                    vec![left.clone(), right_value.clone()],
2311                )?;
2312                // `SortCompare` ends with `ToNumber(Call(comparator, …))`, so a comparator
2313                // that answers an object has its `@@toPrimitive` run (`sort-tonumber`
2314                // counts that call).
2315                let answer = interp.to_js_number(&answer)?;
2316                if answer > 0.0 {
2317                    merged.push(right_iter.next().expect("peeked"));
2318                } else {
2319                    merged.push(left_iter.next().expect("peeked"));
2320                }
2321            }
2322            (Some(_), None) => merged.push(left_iter.next().expect("peeked")),
2323            (None, Some(_)) => merged.push(right_iter.next().expect("peeked")),
2324            (None, None) => break,
2325        }
2326    }
2327    *items = merged;
2328    Ok(())
2329}
2330
2331/// Store `values` back into the receiver's view, which is how the in-place methods answer.
2332fn write_back(
2333    interp: &mut Interp<'_>,
2334    object: &Gc<JsObject>,
2335    element_type: ElementType,
2336    values: &[Value],
2337) -> JsResult<()> {
2338    let Some((buffer, _, base, _, _)) = object.typed_array_geometry() else {
2339        return Err(interp.type_error("not a typed array"));
2340    };
2341    for (index, value) in values.iter().enumerate() {
2342        // `Set(O, ! ToString(index), value, true)`: a view whose buffer shrank away underneath
2343        // it has *no* valid indices, so every store is dropped rather than clamped to whatever
2344        // still fits — a fixed-length view of four elements on a buffer shrunk to two keeps its
2345        // original contents, which is what `sort/comparefn-shrink` asserts. The geometry is
2346        // re-read per write because the conversion inside `write_element` runs script
2347        // (`valueOf`) that can resize the buffer again.
2348        match object.typed_array_geometry() {
2349            Some((_, _, _, length, out_of_bounds)) if !out_of_bounds && index < length => {}
2350            _ => continue,
2351        }
2352        write_element(interp, &buffer, element_type, base, index, value.clone())?;
2353    }
2354    Ok(())
2355}
2356
2357/// `a.copyWithin(target, start, end)`: copies a run of elements over an earlier one.
2358fn copy_within(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2359    let object = this
2360        .as_object()
2361        .cloned()
2362        .ok_or_else(|| interp.type_error("not a typed array"))?;
2363    let (elements, element_type) = view_parts(interp, &this)?;
2364    // The conversions run one at a time and each may resize the buffer, so the length they
2365    // are clamped against is the one from *before* each of them — which is what
2366    // `copyWithin/coerced-target-start-end-shrink` pins: `copyWithin(0, evil)` on a
2367    // 4-element view the coercion shrinks to 3 copies **one** element, not two.
2368    let length_i = elements.len() as i64;
2369    let target = clamp_index(to_integer_or_infinity(interp, &arg(args, 0))?, length_i, 0);
2370    let start = clamp_index(to_integer_or_infinity(interp, &arg(args, 1))?, length_i, 0);
2371    let end = match args.get(2) {
2372        // The default is the length the record gave at validation, not the one the view has
2373        // after the conversions — that is what makes `copyWithin(evil, 2)` on a view the
2374        // coercion *grows* to 6 copy two elements (4 − 2) rather than four.
2375        None | Some(Value::Undefined) => length_i,
2376        Some(value) => clamp_index(to_integer_or_infinity(interp, value)?, length_i, length_i),
2377    };
2378    // `Set taRecord to MakeTypedArrayWithBufferWitnessRecord(O, seq-cst)` (the spec's
2379    // step 10). It does two things: a view that no longer fits — or a buffer the last
2380    // `valueOf` detached — is a `TypeError` rather than a copy from storage that is gone,
2381    // and `count` is then clamped by the length the view has *now*, so the same call on a
2382    // view the coercion *shrinks* to 3 copies one element instead of two.
2383    revalidate(interp, &object)?;
2384    let current_i = object.typed_array_length().unwrap_or(0) as i64;
2385    // Both halves of `count = min(final - from, len - to)` come from *different* records,
2386    // which the two halves of `copyWithin/coerced-target-start-grow` pin from opposite
2387    // directions: the source end is bounded by the length the view has **now** (a shrink
2388    // truncates the copy), while the destination end is bounded by the length it had **at
2389    // validation** (a grow does not extend a `copyWithin(2, 0)` past the original end).
2390    let source_end = end.min(current_i);
2391    let count = (source_end - start).min(length_i - target).max(0) as usize;
2392    // A temporary, because the ranges may overlap: `copyWithin(0, 1)` would otherwise read
2393    // values it had already overwritten.
2394    let source: Vec<Value> = (0..count)
2395        .map(|offset| elements.get(start as usize + offset))
2396        .collect();
2397    // Written straight into the buffer rather than through a value vector: the conversions
2398    // may have *grown* the buffer, so a destination index can legitimately be past the
2399    // length the method started with, and `write_element` is what knows to drop a write
2400    // that only became... impossible.
2401    let Some((buffer, _, base, _)) = object.typed_array_parts() else {
2402        return Err(interp.type_error("not a typed array"));
2403    };
2404    for (offset, value) in source.into_iter().enumerate() {
2405        write_element(
2406            interp,
2407            &buffer,
2408            element_type,
2409            base,
2410            target as usize + offset,
2411            value,
2412        )?;
2413    }
2414    Ok(Value::Object(object))
2415}
2416
2417/// `a.toLocaleString()`: each element through its own `toLocaleString`, joined by `,`.
2418fn to_locale_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2419    // `len` once, from the record — then each element is read and converted as the walk
2420    // reaches it, so an element `toLocaleString` resizes away contributes an empty field
2421    // rather than aborting the call or replaying a value that is no longer there.
2422    let elements = elements_of(interp, &this)?;
2423    let mut parts = Vec::with_capacity(elements.len());
2424    for (_, element) in elements.iter() {
2425        // `undefined` and `null` contribute an empty field, exactly as `join` does.
2426        if matches!(element, Value::Undefined | Value::Null) {
2427            parts.push(String::new());
2428            continue;
2429        }
2430        // Read `toLocaleString` off the element's own chain, so a Number reaches
2431        // `Number.prototype.toLocaleString` and a BigInt reaches `BigInt.prototype`'s.
2432        let method = match &element {
2433            Value::Object(object) => interp.get_property(object, "toLocaleString")?,
2434            primitive => {
2435                let boxed = interp.object_from(primitive)?;
2436                interp.get_property(&boxed, "toLocaleString")?
2437            }
2438        };
2439        let text = match method {
2440            Some(method) => {
2441                let result = interp.call_value(method, element.clone(), Vec::new())?;
2442                interp.to_js_string(&result)?
2443            }
2444            None => interp.to_js_string(&element)?,
2445        };
2446        parts.push(text);
2447    }
2448    Ok(interp.string(parts.join(",")))
2449}
2450
2451/// `a.with(index, value)`: a copy with one element replaced.
2452fn with(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2453    let object = this
2454        .as_object()
2455        .cloned()
2456        .ok_or_else(|| interp.type_error("not a typed array"))?;
2457    let (_, element_type, _, len) = validate_view(interp, &object)?;
2458    // §23.2.3.35, in this order (§23.2.3.35 steps 3–9): the length from the record, then
2459    // the index conversion, then the value conversion, and only then the validity check —
2460    // so a `valueOf` that resizes decides whether `index` is legal *now*, while a negative
2461    // index is still counted back from the length it was when the call started.
2462    let relative = to_integer_or_infinity(interp, &arg(args, 0))?;
2463    let index = if relative >= 0.0 {
2464        relative
2465    } else {
2466        len as f64 + relative
2467    };
2468    let numeric = interp.element_value(element_type, arg(args, 1))?;
2469    if index < 0.0 || index >= object.typed_array_length().unwrap_or(0) as f64 {
2470        return Err(interp.range_error("index is out of range"));
2471    }
2472    let index = index as usize;
2473    // The result is a fresh view of the same element type, built without reading
2474    // `constructor` or `Symbol.species` — `with` is defined to ignore both
2475    // (`with/ignores-species` fails if either is even *read*).
2476    // The result has the *record's* length, and the substitution is `If k = actualIndex`
2477    // over `k < len` — so an index that only became valid because the buffer grew matches no
2478    // `k` at all and changes nothing (`with/index-validated-against-current-length`, where
2479    // `ta.with(4, …)` on a 2-element record answers a 2-element copy).
2480    let mut items: Vec<Value> = (0..len)
2481        .map(|k| object.typed_array_element(k).unwrap_or(Value::Undefined))
2482        .collect();
2483    if index < len {
2484        items[index] = numeric;
2485    }
2486    Ok(Value::Object(new_view(interp, element_type, &items)?))
2487}
2488
2489fn to_reversed(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2490    let (elements, element_type) = view_parts(interp, &this)?;
2491    let mut items = elements.to_vec();
2492    items.reverse();
2493    // §23.2.3.29 step 3 is `TypedArrayCreateSameType`, **not** `TypedArraySpeciesCreate`: the
2494    // intrinsic constructor for the element type is used directly, so `constructor` and
2495    // `Symbol.species` are never read (`ignores-species` defines a throwing `constructor`
2496    // getter).
2497    Ok(Value::Object(new_view(interp, element_type, &items)?))
2498}
2499
2500fn to_sorted(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2501    let (elements, element_type) = view_parts(interp, &this)?;
2502    // Reuse `sort` by handing it a fresh view of the same contents.
2503    let copy = new_view(interp, element_type, &elements.to_vec())?;
2504    sort(interp, Value::Object(copy.clone()), args)?;
2505    Ok(Value::Object(copy))
2506}
2507
2508/// `a.values()` / `a.keys()` / `a.entries()`.
2509///
2510/// The iterator machinery is shared with `Array.prototype`: `length_of` and `element_at`
2511/// reach a typed array through its exotic `length` and index properties, so the same
2512/// `next` walks it correctly and the laziness carries over.
2513fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2514    // `%TypedArray%.prototype.values` runs `ValidateTypedArray` before building the
2515    // iterator, so a detached view throws here rather than on the first `next`.
2516    view_parts(interp, &this)?;
2517    crate::builtins::array::iterator(
2518        interp,
2519        this,
2520        crate::builtins::array::IteratorKind::Value,
2521        crate::builtins::array::ARRAY_ITERATOR_TAG,
2522    )
2523}
2524
2525fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2526    view_parts(interp, &this)?;
2527    crate::builtins::array::iterator(
2528        interp,
2529        this,
2530        crate::builtins::array::IteratorKind::Key,
2531        crate::builtins::array::ARRAY_ITERATOR_TAG,
2532    )
2533}
2534
2535fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2536    view_parts(interp, &this)?;
2537    crate::builtins::array::iterator(
2538        interp,
2539        this,
2540        crate::builtins::array::IteratorKind::Entry,
2541        crate::builtins::array::ARRAY_ITERATOR_TAG,
2542    )
2543}
2544
2545/// `a.slice(begin, end)`: a new view with a buffer of its own.
2546fn slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2547    let receiver = this
2548        .as_object()
2549        .cloned()
2550        .ok_or_else(|| interp.type_error("not a typed array"))?;
2551    let (_, element_type, _, src_len) = validate_view(interp, &receiver)?;
2552    // §23.2.3.27: `srcLength` comes from the record, so both bounds are clamped against the
2553    // length the view had *before* either conversion ran — which is what makes
2554    // `lengthTracking.slice(evil)` with a growing buffer answer 4 elements and not 6.
2555    let src_len_i = src_len as i64;
2556    let begin = clamp_index(to_integer_or_infinity(interp, &arg(args, 0))?, src_len_i, 0);
2557    let end = clamp_index(
2558        match args.get(1) {
2559            None | Some(Value::Undefined) => src_len_i as f64,
2560            Some(value) => to_integer_or_infinity(interp, value)?,
2561        },
2562        src_len_i,
2563        src_len_i,
2564    );
2565    let count = (end - begin).max(0) as usize;
2566    // The result view is created *before* the source is read, because the species
2567    // constructor is observable and may resize the buffer `receiver` is a view of.
2568    let (target, target_element) = species_create_view(interp, &receiver, element_type, count)?;
2569    // Then the source is checked again — but only when there is something to copy, which is
2570    // the spec's `If count > 0` guard: a zero-count `slice` of an already-detached view has
2571    // to return the empty species result rather than throw
2572    // (`detached-buffer-zero-count-custom-ctor-*`). `slice` is specified as a byte-range
2573    // copy, so a non-empty one that no longer fits *is* a `TypeError`; `map` deliberately
2574    // does not do this — its elements just read as `undefined`.
2575    if count > 0 {
2576        revalidate(interp, &receiver)?;
2577    }
2578    let Some((target_buffer, _, target_base, _)) = target.typed_array_parts() else {
2579        return Err(interp.type_error("not a typed array"));
2580    };
2581    // Each element is read now — not from a snapshot — and an element the buffer no longer
2582    // covers contributes the **target type's zero**, not the `undefined` a `[[Get]]` answers.
2583    // That distinction is the whole of `slice/resize-count-bytes-to-zero`: a float view
2584    // stores `ToNumber(undefined)` as `NaN`, while the spec leaves the freshly zeroed result
2585    // block alone. It is stated as a byte copy ("must preserve the bit-level encoding") in
2586    // §23.2.3.27, and this is that behaviour written element-wise so a species that answers
2587    // a *different* element type still converts instead of reinterpreting bytes.
2588    let present = receiver.typed_array_length().unwrap_or(0);
2589    for offset in 0..count {
2590        let index = begin as usize + offset;
2591        let value = if index < present {
2592            receiver
2593                .typed_array_element(index)
2594                .unwrap_or(Value::Undefined)
2595        } else {
2596            target
2597                .typed_array_element_type()
2598                .map_or(Value::Int(0), |kind| match kind {
2599                    ElementType::BigInt64 | ElementType::BigUint64 => {
2600                        Value::BigInt(js_gc::Gc::new(interp.heap, crate::bigint::BigInt::zero()))
2601                    }
2602                    _ => Value::Int(0),
2603                })
2604        };
2605        write_element(
2606            interp,
2607            &target_buffer,
2608            target_element,
2609            target_base,
2610            offset,
2611            value,
2612        )?;
2613    }
2614    Ok(Value::Object(target))
2615}
2616
2617/// `a.subarray(begin, end)`: a view over the *same* buffer.
2618///
2619/// Built by **constructing** the species with `(buffer, byteOffset[, length])` rather than by
2620/// assembling a view here, because the constructor is where the bounds are checked: a
2621/// subarray whose length was computed from the pre-coercion length *can* be too long for a
2622/// buffer that shrank during the conversion, and that has to be a `RangeError`
2623/// (`subarray/coerced-begin-end-shrink`).
2624fn subarray(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2625    let object = this
2626        .as_object()
2627        .cloned()
2628        .ok_or_else(|| interp.type_error("not a typed array"))?;
2629    let Some((buffer, element, stored_offset, _)) = object.typed_array_stored() else {
2630        return Err(interp.type_error("not a typed array"));
2631    };
2632    // `[[ByteOffset]]` keeps its value even when the view is out of bounds, so the *stored*
2633    // offset is the base — a view the buffer shrank away from still starts where it did, and
2634    // an `auto`-length subarray of it therefore starts there too once the buffer grows back.
2635    // The witness is taken first — a resizable buffer's length at *entry* is what clamps
2636    // the bounds — but its **detached** check is deferred until after the two arguments
2637    // have been converted, because both `valueOf`s are still observable on a view whose
2638    // buffer is already gone (`subarray/detached-buffer` asserts `begin` *and* `end` ran).
2639    let witness = object.typed_array_geometry();
2640    let detached = witness.as_ref().is_some_and(|(buffer, ..)| {
2641        buffer
2642            .array_buffer_storage()
2643            .is_some_and(|storage| storage.borrow().detached)
2644    });
2645    let src_len = witness.as_ref().map_or(0, |(_, _, _, length, _)| *length);
2646    // §23.2.3.30: `srcLength` from the record clamps both bounds, so a `valueOf` that grows
2647    // the buffer cannot widen the window past the length the call started with — but the
2648    // byte offset is the clamped start index mapped onto the buffer as it is now, which is
2649    // why `tracking.subarray(evil)` after a grow reports `[4, 2]` and not `[4, 0]`.
2650    let src_len_i = src_len as i64;
2651    let element_size = element.size();
2652    let begin = clamp_index(to_integer_or_infinity(interp, &arg(args, 0))?, src_len_i, 0);
2653    let begin_byte = stored_offset + begin as usize * element_size;
2654    // `IsAutoLength(taRecord)` **and** an `undefined` `end`: an `auto` view with an explicit
2655    // end gets a fixed length, and a fixed-length view always does.
2656    let end_missing = args
2657        .get(1)
2658        .is_none_or(|end| matches!(end, Value::Undefined));
2659    let auto = object.typed_array_tracks_length() && end_missing;
2660    let mut arguments = vec![Value::Object(buffer), Value::Int(begin_byte as i32)];
2661    if !auto {
2662        let end = clamp_index(
2663            match args.get(1) {
2664                None | Some(Value::Undefined) => src_len_i as f64,
2665                Some(value) => to_integer_or_infinity(interp, value)?,
2666            },
2667            src_len_i,
2668            src_len_i,
2669        );
2670        let count = (end - begin).max(0);
2671        arguments.push(Value::Int(count as i32));
2672    }
2673    if detached {
2674        return Err(interp.type_error("the buffer is detached"));
2675    }
2676    species_construct(interp, &object, arguments)
2677}
2678
2679/// The `buffer` accessor.
2680fn buffer_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2681    let object = this
2682        .as_object()
2683        .ok_or_else(|| interp.type_error("not a typed array"))?;
2684    object
2685        .typed_array_parts()
2686        .map(|(buffer, _, _, _)| Value::Object(buffer))
2687        .ok_or_else(|| interp.type_error("not a typed array"))
2688}
2689
2690/// The `byteOffset` accessor.
2691fn byte_offset_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2692    let object = this
2693        .as_object()
2694        .ok_or_else(|| interp.type_error("not a typed array"))?;
2695    object
2696        .typed_array_parts()
2697        .map(|(_, _, base, _)| Value::Int(base as i32))
2698        .ok_or_else(|| interp.type_error("not a typed array"))
2699}
2700
2701/// The `byteLength` accessor.
2702fn byte_length_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2703    let object = this
2704        .as_object()
2705        .ok_or_else(|| interp.type_error("not a typed array"))?;
2706    object
2707        .typed_array_parts()
2708        .map(|(_, element, _, length)| Value::Int((length * element.size()) as i32))
2709        .ok_or_else(|| interp.type_error("not a typed array"))
2710}
2711
2712/// The `length` accessor.
2713fn length_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2714    let object = this
2715        .as_object()
2716        .ok_or_else(|| interp.type_error("not a typed array"))?;
2717    object
2718        .typed_array_length()
2719        .map(|length| Value::Int(length as i32))
2720        .ok_or_else(|| interp.type_error("not a typed array"))
2721}
2722
2723/// The `Symbol.toStringTag` accessor, which names the element type.
2724/// §23.2.3.32 `get %TypedArray%.prototype[@@toStringTag]`.
2725///
2726/// The element type decides the name, and **anything that is not a view answers
2727/// `undefined`** — no `TypeError`, and no brand check on the receiver at all, which is why
2728/// the getter can be called with `undefined`, a number, a string, a boolean or a symbol
2729/// (`this-is-not-object`, `invoked-as-func`). Throwing here instead made all six of those
2730/// cases fail on the first line.
2731fn tag_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2732    let Some(object) = this.as_object() else {
2733        return Ok(Value::Undefined);
2734    };
2735    Ok(match object.typed_array_element_type() {
2736        Some(element) => interp.string(element.name()),
2737        None => Value::Undefined,
2738    })
2739}
2740
2741// ---------------------------------------------------------------------------
2742// DataView
2743// ---------------------------------------------------------------------------
2744
2745/// One `get`/`set` pair per width. `NativeFn` is a bare function pointer, so the width has
2746/// to be baked into the function rather than captured: the macro below writes one pair of
2747/// thin wrappers per row.
2748macro_rules! data_view_accessors {
2749    ($($get:ident, $set:ident => $element:expr, $width:literal);* $(;)?) => {
2750        $(
2751            fn $get(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2752                data_view_get(interp, &this, args, $element)
2753            }
2754            fn $set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2755                data_view_set(interp, &this, args, $element)
2756            }
2757        )*
2758
2759        /// Every accessor, as `(name, length, body)`.
2760        const DATA_VIEW_METHODS: &[(&str, u32, crate::object::NativeFn)] = &[
2761            $(
2762                (concat!("get", $width), 1, $get as crate::object::NativeFn),
2763                (concat!("set", $width), 2, $set as crate::object::NativeFn),
2764            )*
2765        ];
2766    };
2767}
2768
2769data_view_accessors! {
2770    get_int8, set_int8 => ElementType::Int8, "Int8";
2771    get_uint8, set_uint8 => ElementType::Uint8, "Uint8";
2772    get_int16, set_int16 => ElementType::Int16, "Int16";
2773    get_uint16, set_uint16 => ElementType::Uint16, "Uint16";
2774    get_int32, set_int32 => ElementType::Int32, "Int32";
2775    get_uint32, set_uint32 => ElementType::Uint32, "Uint32";
2776    get_float16, set_float16 => ElementType::Float16, "Float16";
2777    get_float32, set_float32 => ElementType::Float32, "Float32";
2778    get_float64, set_float64 => ElementType::Float64, "Float64";
2779    get_bigint64, set_bigint64 => ElementType::BigInt64, "BigInt64";
2780    get_biguint64, set_biguint64 => ElementType::BigUint64, "BigUint64";
2781}
2782
2783/// Install `DataView` and its prototype.
2784pub fn install_data_view(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
2785    let proto = interp.new_object(Some(object_proto.clone()));
2786    let constructor = interp.new_native_ctor("DataView", 1, data_view_constructor);
2787    constructor.define(
2788        "prototype",
2789        Property::prototype_of(Value::Object(proto.clone()), false),
2790    );
2791    proto.define(
2792        "constructor",
2793        Property {
2794            value: Some(Value::Object(constructor.clone())),
2795            writable: true,
2796            enumerable: false,
2797            configurable: true,
2798            ..Property::default()
2799        },
2800    );
2801    for (name, getter) in [
2802        ("buffer", data_view_buffer as crate::object::NativeFn),
2803        ("byteOffset", data_view_byte_offset),
2804        ("byteLength", data_view_byte_length),
2805    ] {
2806        let function = interp.new_native(format!("get {name}"), 0, getter);
2807        proto.define(
2808            name,
2809            Property {
2810                getter: Some(Value::Object(function)),
2811                enumerable: false,
2812                configurable: true,
2813                ..Property::default()
2814            },
2815        );
2816    }
2817    for (name, length, body) in DATA_VIEW_METHODS {
2818        define_method(&proto, name, *length, *body, interp);
2819    }
2820    interp.realm.data_view_proto = Some(proto.clone());
2821    let global = interp.realm.global.clone();
2822    global.define(
2823        "DataView",
2824        Property::with_attributes(Value::Object(constructor), true, false),
2825    );
2826    install_tag(&proto, "DataView", interp);
2827}
2828
2829/// The receiver as `(buffer, offset, length)`, refusing anything that is not a live view.
2830///
2831/// A detached buffer is a `TypeError` from every accessor and every property read, which is
2832/// what `MakeDataViewWithBufferWitnessRecord`'s `IsDetachedBuffer` check amounts to.
2833fn data_view_parts(
2834    interp: &mut Interp<'_>,
2835    this: &Value,
2836) -> JsResult<(Gc<JsObject>, usize, usize)> {
2837    let Some(object) = this.as_object() else {
2838        return Err(interp.type_error("not a DataView"));
2839    };
2840    let Some(parts) = object.data_view_parts() else {
2841        return Err(interp.type_error("not a DataView"));
2842    };
2843    Ok(parts)
2844}
2845
2846/// The receiver as `(buffer, offset, length)` **after** `MakeDataViewWithBufferWitnessRecord`,
2847/// which is what an accessor has to ask: the length is the one that holds now, and a view
2848/// whose bytes no longer fit is out of bounds, which is a `TypeError` rather than a short
2849/// view. `data_view_parts` answers the same numbers but cannot report that state, so this
2850/// is the one the accessors use.
2851fn data_view_witness(
2852    interp: &mut Interp<'_>,
2853    this: &Value,
2854) -> JsResult<(Gc<JsObject>, usize, usize)> {
2855    let Some(object) = this.as_object() else {
2856        return Err(interp.type_error("not a DataView"));
2857    };
2858    let Some((buffer, offset, length, out_of_bounds)) = object.data_view_geometry() else {
2859        return Err(interp.type_error("not a DataView"));
2860    };
2861    if out_of_bounds {
2862        return Err(interp.type_error("the buffer was detached or resized out of bounds"));
2863    }
2864    Ok((buffer, offset, length))
2865}
2866
2867/// Whether this view's buffer has been detached.
2868fn data_view_is_detached(object: &Gc<JsObject>) -> bool {
2869    object
2870        .data_view_parts()
2871        .and_then(|(buffer, _, _)| buffer.array_buffer_storage())
2872        .is_some_and(|storage| storage.borrow().detached)
2873}
2874
2875fn data_view_buffer(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2876    let (buffer, _, _) = data_view_parts(interp, &this)?;
2877    Ok(Value::Object(buffer))
2878}
2879
2880fn data_view_byte_offset(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2881    let (_, offset, _) = data_view_parts(interp, &this)?;
2882    // A detached view is zero-length, so its offset is 0 as well.
2883    let detached = this.as_object().is_some_and(data_view_is_detached);
2884    Ok(Value::Int(if detached { 0 } else { offset as i32 }))
2885}
2886
2887fn data_view_byte_length(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2888    let (_, _, length) = data_view_parts(interp, &this)?;
2889    // A detached buffer has no bytes left, so the view reports 0 rather than throwing.
2890    let detached = this.as_object().is_some_and(data_view_is_detached);
2891    Ok(Value::Int(if detached { 0 } else { length as i32 }))
2892}
2893
2894/// `dv.getInt32(byteOffset, littleEndian)` and siblings.
2895fn data_view_get(
2896    interp: &mut Interp<'_>,
2897    this: &Value,
2898    args: &[Value],
2899    element: ElementType,
2900) -> JsResult<Value> {
2901    // `ToIndex(byteOffset)` runs before anything else, so a `valueOf` that detaches still
2902    // runs and an `Infinity` offset is a `RangeError` either way.
2903    let byte_offset = to_index(interp, &arg(args, 0), "byte offset")?;
2904    let (buffer, offset, length) = data_view_witness(interp, this)?;
2905    let size = element.size();
2906    // Order matters and is observable: §25.3.1.1 step 6 makes an out-of-bounds *view* a
2907    // `TypeError`, and only then does step 9 make a bad *index* a `RangeError`. Answering
2908    // `RangeError` for both is what
2909    // `DataView/prototype/getUint8/resizable-buffer` catches, one accessor at a time.
2910    if byte_offset + size > length {
2911        return Err(interp.range_error("byte offset is out of range"));
2912    }
2913    let little_endian = arg(args, 1).to_boolean();
2914    let storage = buffer
2915        .array_buffer_storage()
2916        .ok_or_else(|| interp.type_error("not a DataView"))?;
2917    let storage = storage.borrow();
2918    let start = offset + byte_offset;
2919    // A `DataView` defaults to *big*-endian while the element types read little-endian, so
2920    // the bytes are reversed into a scratch buffer first. One-byte widths are unaffected.
2921    let mut scratch = [0u8; 8];
2922    let raw = &storage.bytes[start..start + size];
2923    if little_endian {
2924        scratch[..size].copy_from_slice(raw);
2925    } else {
2926        for (slot, byte) in scratch[..size].iter_mut().zip(raw.iter().rev()) {
2927            *slot = *byte;
2928        }
2929    }
2930    Ok(element.read(buffer.heap(), &scratch, 0))
2931}
2932
2933/// `dv.setInt32(byteOffset, value, littleEndian)` and siblings.
2934fn data_view_set(
2935    interp: &mut Interp<'_>,
2936    this: &Value,
2937    args: &[Value],
2938    element: ElementType,
2939) -> JsResult<Value> {
2940    // §25.3.1.11 SetViewValue, step for step:
2941    //
2942    // 3. `? ToIndex(byteOffset)`
2943    // 4. the witness record, and the detached check
2944    // 5. **`? ToNumber(value)` / `? ToBigInt(value)`** — *before* the bounds check
2945    // 6. `GetViewByteLength`, then the range check (a `RangeError`)
2946    //
2947    // The order of 5 and 6 is observable both ways: a poisoned `valueOf` must be reached
2948    // even when the offset is out of range (`range-check-after-value-conversion`), and a
2949    // `valueOf` that detaches the buffer must make the *detached* `TypeError` win over the
2950    // `RangeError` (`detached-buffer-after-*-value`).
2951    let byte_offset = to_index(interp, &arg(args, 0), "byte offset")?;
2952    // The value is converted first, while the view may still be valid.
2953    let stored = interp.element_value(element, arg(args, 1))?;
2954    let (buffer, offset, length) = data_view_witness(interp, this)?;
2955    let size = element.size();
2956    if byte_offset + size > length {
2957        return Err(interp.range_error("byte offset is out of range"));
2958    }
2959    let little_endian = arg(args, 2).to_boolean();
2960    // Little-endian first, into scratch, so the conversion (wrap, clamp, or BigInt modulo)
2961    // runs before any byte is reversed.
2962    let mut scratch = [0u8; 8];
2963    element
2964        .write(&mut scratch, 0, &stored)
2965        .map_err(|reason| interp.type_error(reason))?;
2966    let storage = buffer
2967        .array_buffer_storage()
2968        .ok_or_else(|| interp.type_error("not a DataView"))?;
2969    let mut storage = storage.borrow_mut();
2970    let start = offset + byte_offset;
2971    let target = &mut storage.bytes[start..start + size];
2972    if little_endian {
2973        target.copy_from_slice(&scratch[..size]);
2974    } else {
2975        for (slot, byte) in target.iter_mut().zip(scratch[..size].iter().rev()) {
2976            *slot = *byte;
2977        }
2978    }
2979    Ok(Value::Undefined)
2980}
2981
2982/// `new DataView(buffer, byteOffset, byteLength)`.
2983///
2984/// The step order is observable and follows 25.3.2.1 exactly: `ToIndex(byteOffset)` runs
2985/// *before* the detached-buffer check, so a `valueOf` that detaches is still called, and the
2986/// detached check is repeated after the prototype lookup because
2987/// `OrdinaryCreateFromConstructor` can run a getter that detaches.
2988fn data_view_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2989    // Called as a function rather than with `new`: there is no instance to build.
2990    let _ = &this;
2991    if !interp.is_constructing() {
2992        return Err(interp.type_error("Constructor DataView requires 'new'"));
2993    }
2994    let Some(buffer) = arg(args, 0).as_object().cloned() else {
2995        return Err(interp.type_error("first argument to DataView must be an ArrayBuffer"));
2996    };
2997    if buffer.array_buffer_storage().is_none() {
2998        return Err(interp.type_error("first argument to DataView must be an ArrayBuffer"));
2999    }
3000    // Step 5 before step 6.
3001    let offset = to_index(interp, &arg(args, 1), "byte offset")?;
3002    let detached = |buffer: &Gc<JsObject>| {
3003        buffer
3004            .array_buffer_storage()
3005            .is_some_and(|storage| storage.borrow().detached)
3006    };
3007    if detached(&buffer) {
3008        return Err(interp.type_error("the buffer is detached"));
3009    }
3010    let total = buffer
3011        .array_buffer_storage()
3012        .map(|storage| {
3013            let storage = storage.borrow();
3014            (storage.bytes.len(), storage.is_resizable())
3015        })
3016        .unwrap_or((0, false));
3017    let (total, resizable) = total;
3018    if offset > total {
3019        return Err(interp.range_error("byte offset is out of range"));
3020    }
3021    let length = match args.get(2) {
3022        // An absent or explicit `undefined` length means "the rest of the buffer" — and on a
3023        // resizable buffer that means "the rest, whatever it becomes": the view tracks the
3024        // buffer instead of pinning today's remainder.
3025        None | Some(Value::Undefined) => {
3026            if resizable {
3027                ViewLength::Tracking
3028            } else {
3029                ViewLength::Fixed(total - offset)
3030            }
3031        }
3032        Some(_) => {
3033            let requested = to_index(interp, &arg(args, 2), "byte length")?;
3034            if requested > total - offset {
3035                return Err(interp.range_error("byte length is out of range"));
3036            }
3037            ViewLength::Fixed(requested)
3038        }
3039    };
3040    // `OrdinaryCreateFromConstructor` is where `new.target.prototype` is read, and that
3041    // getter may resize or detach the buffer — so every check has to be repeated *after*
3042    // it, not before it. (`custom-proto-access-resizes-buffer-invalid-by-offset` and
3043    // `…-by-length` are the two halves: the resize can break either bound.)
3044    let proto = interp
3045        .realm
3046        .data_view_proto
3047        .clone()
3048        .unwrap_or_else(|| interp.realm.object_proto.clone());
3049    let instance = interp.new_ctor_instance(proto)?;
3050    if detached(&buffer) {
3051        return Err(interp.type_error("the buffer is detached"));
3052    }
3053    let total_now = buffer
3054        .array_buffer_storage()
3055        .map(|storage| storage.borrow().bytes.len())
3056        .unwrap_or(0);
3057    if offset > total_now {
3058        return Err(interp.range_error("byte offset is out of range"));
3059    }
3060    if let ViewLength::Fixed(requested) = length
3061        && requested > total_now - offset
3062    {
3063        return Err(interp.range_error("byte length is out of range"));
3064    }
3065    instance.set_data_view(buffer, offset, length);
3066    Ok(Value::Object(instance))
3067}
3068
3069/// §23.2.4.13's default `SortCompare` for a typed array, whose order is **numeric** rather
3070/// than `Array.prototype.sort`'s string order.
3071///
3072/// The three special cases are each a test:
3073///
3074/// * a `NaN` sorts **after** every number (`sorted-values-nan`), which `partial_cmp`
3075///   answers as "equal" and so leaves wherever it started;
3076/// * `-0` sorts **before** `+0`;
3077/// * everything else is the plain numeric comparison.
3078fn typed_array_sort_compare(left: &Value, right: &Value) -> std::cmp::Ordering {
3079    use std::cmp::Ordering;
3080    let (left, right) = (left.to_number(), right.to_number());
3081    // The spec spells these as "x is NaN" / "y is NaN" before the comparisons, so a NaN
3082    // pair still orders as equal but sits at the end.
3083    match (left.is_nan(), right.is_nan()) {
3084        (true, true) => Ordering::Equal,
3085        (true, false) => Ordering::Greater,
3086        (false, true) => Ordering::Less,
3087        (false, false) => {
3088            if left < right {
3089                Ordering::Less
3090            } else if left > right {
3091                Ordering::Greater
3092            } else if left == 0.0 && right == 0.0 {
3093                // `-0` before `+0`; `0 == -0` in Rust, so the bits decide.
3094                match (left.is_sign_negative(), right.is_sign_negative()) {
3095                    (true, false) => Ordering::Less,
3096                    (false, true) => Ordering::Greater,
3097                    _ => Ordering::Equal,
3098                }
3099            } else {
3100                Ordering::Equal
3101            }
3102        }
3103    }
3104}