Skip to main content

quickjs/builtins/
typedarray.rs

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