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