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