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