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