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};
38use crate::value::Value;
39use js_gc::Gc;
40use std::cell::RefCell;
41use std::rc::Rc;
42
43/// Which element type a view reads and writes.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ElementType {
46    /// `Int8Array`
47    Int8,
48    /// `Uint8Array`
49    Uint8,
50    /// `Uint8ClampedArray`
51    Uint8Clamped,
52    /// `Int16Array`
53    Int16,
54    /// `Uint16Array`
55    Uint16,
56    /// `Int32Array`
57    Int32,
58    /// `Uint32Array`
59    Uint32,
60    /// `Float16Array`
61    Float16,
62    /// `Float32Array`
63    Float32,
64    /// `Float64Array`
65    Float64,
66    /// `BigInt64Array`
67    BigInt64,
68    /// `BigUint64Array`
69    BigUint64,
70}
71
72/// The view types, in the order their prototypes are installed.
73pub const ELEMENT_TYPES: [(ElementType, &str); 12] = [
74    (ElementType::Int8, "Int8Array"),
75    (ElementType::Uint8, "Uint8Array"),
76    (ElementType::Uint8Clamped, "Uint8ClampedArray"),
77    (ElementType::Int16, "Int16Array"),
78    (ElementType::Uint16, "Uint16Array"),
79    (ElementType::Int32, "Int32Array"),
80    (ElementType::Uint32, "Uint32Array"),
81    (ElementType::Float16, "Float16Array"),
82    (ElementType::Float32, "Float32Array"),
83    (ElementType::Float64, "Float64Array"),
84    (ElementType::BigInt64, "BigInt64Array"),
85    (ElementType::BigUint64, "BigUint64Array"),
86];
87
88impl ElementType {
89    /// Bytes per element.
90    pub fn size(self) -> usize {
91        match self {
92            ElementType::Int8 | ElementType::Uint8 | ElementType::Uint8Clamped => 1,
93            ElementType::Int16 | ElementType::Uint16 | ElementType::Float16 => 2,
94            ElementType::Int32 | ElementType::Uint32 | ElementType::Float32 => 4,
95            ElementType::Float64 | ElementType::BigInt64 | ElementType::BigUint64 => 8,
96        }
97    }
98
99    /// Whether elements are `BigInt`s rather than numbers.
100    ///
101    /// The two behave differently in ways that reach most methods: the sort order, what a
102    /// literal element converts to, and whether a Number is a `TypeError`.
103    pub fn is_bigint(self) -> bool {
104        matches!(self, ElementType::BigInt64 | ElementType::BigUint64)
105    }
106
107    /// The name, as `Symbol.toStringTag` and the class tag report it.
108    pub fn name(self) -> &'static str {
109        ELEMENT_TYPES
110            .into_iter()
111            .find(|(kind, _)| *kind == self)
112            .map(|(_, name)| name)
113            .unwrap_or("TypedArray")
114    }
115
116    /// Read the element at `offset`.
117    ///
118    /// A short buffer — only reachable if a view was built over a truncated one — reads as
119    /// `0` rather than panicking, because a script must not be able to make the engine abort.
120    pub fn read(self, heap: &js_gc::Heap, bytes: &[u8], offset: usize) -> Value {
121        let slice = bytes.get(offset..offset + self.size());
122        let Some(slice) = slice else {
123            // A short buffer reads as the type's zero, which for a BigInt type is `0n`.
124            return match self {
125                ElementType::BigInt64 | ElementType::BigUint64 => {
126                    Value::BigInt(js_gc::Gc::new(heap, crate::bigint::BigInt::zero()))
127                }
128                _ => Value::Int(0),
129            };
130        };
131        match self {
132            ElementType::Int8 => Value::Int(slice[0] as i8 as i32),
133            ElementType::Uint8 | ElementType::Uint8Clamped => Value::Int(slice[0] as i32),
134            ElementType::Int16 => Value::Int(i16::from_le_bytes([slice[0], slice[1]]) as i32),
135            ElementType::Uint16 => Value::Int(u16::from_le_bytes([slice[0], slice[1]]) as i32),
136            ElementType::Int32 => {
137                Value::Int(i32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
138            }
139            // An unsigned 32-bit value does not fit `i32`, so it becomes a float. The
140            // reference keeps it a number too, and the value is exact in an `f64`.
141            ElementType::Uint32 => {
142                Value::Float(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as f64)
143            }
144            ElementType::Float16 => {
145                Value::Float(f16_to_f64(u16::from_le_bytes([slice[0], slice[1]])))
146            }
147            ElementType::Float32 => {
148                Value::Float(f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as f64)
149            }
150            ElementType::Float64 => Value::Float(f64::from_le_bytes([
151                slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
152            ])),
153            // A BigInt element reads back as a `BigInt`, never as a number: `typeof
154            // new BigInt64Array(1)[0]` is `"bigint"` and `0n`, not `0`.
155            ElementType::BigInt64 => Value::BigInt(js_gc::Gc::new(
156                heap,
157                crate::bigint::BigInt::from_i64(i64::from_le_bytes([
158                    slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
159                ])),
160            )),
161            ElementType::BigUint64 => Value::BigInt(js_gc::Gc::new(
162                heap,
163                crate::bigint::BigInt::from_u64(u64::from_le_bytes([
164                    slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
165                ])),
166            )),
167        }
168    }
169
170    /// Store `value` into the element at `offset`.
171    ///
172    /// `value` must already be the primitive this element type stores — a number for the
173    /// numeric types, a BigInt for the two `BigInt` ones. [`write_element`] is what
174    /// applies `ToNumber`/`ToBigInt` beforehand, because both can run script (`valueOf`)
175    /// and the storage borrow must not be held across that.
176    ///
177    /// The `Err` carries the reason, which the caller turns into a `TypeError`.
178    pub fn write(self, bytes: &mut [u8], offset: usize, value: &Value) -> Result<(), &'static str> {
179        let size = self.size();
180        if offset + size > bytes.len() {
181            return Ok(());
182        }
183        // A BigInt element type stores the BigInt itself, modulo `2^64`.
184        if matches!(self, ElementType::BigInt64 | ElementType::BigUint64) {
185            let Value::BigInt(big) = value else {
186                return Err(NOT_A_BIGINT);
187            };
188            let slice = &mut bytes[offset..offset + size];
189            let bits = match self {
190                ElementType::BigInt64 => big.to_i64_wrapping() as u64,
191                _ => big.to_u64_wrapping(),
192            };
193            slice.copy_from_slice(&bits.to_le_bytes());
194            return Ok(());
195        }
196        // The numeric types: every primitive has a number form except a Symbol, which
197        // `ToNumber` refuses. Answering `NaN` here would store a wrong element silently.
198        if matches!(value, Value::Symbol(_)) {
199            return Err(NOT_A_NUMBER);
200        }
201        let number = value.to_number();
202        let slice = &mut bytes[offset..offset + size];
203        match self {
204            ElementType::Int8 => slice[0] = to_integer(number) as i8 as u8,
205            ElementType::Uint8 => slice[0] = to_integer(number) as u8,
206            ElementType::Uint8Clamped => slice[0] = clamp_to_uint8(number),
207            ElementType::Int16 => slice.copy_from_slice(&(to_integer(number) as i16).to_le_bytes()),
208            ElementType::Uint16 => {
209                slice.copy_from_slice(&(to_integer(number) as u16).to_le_bytes())
210            }
211            ElementType::Int32 => slice.copy_from_slice(&(to_integer(number) as i32).to_le_bytes()),
212            ElementType::Uint32 => {
213                slice.copy_from_slice(&(to_integer(number) as u32).to_le_bytes())
214            }
215            ElementType::Float16 => slice.copy_from_slice(&f64_to_f16(number).to_le_bytes()),
216            ElementType::Float32 => slice.copy_from_slice(&(number as f32).to_le_bytes()),
217            ElementType::Float64 => slice.copy_from_slice(&number.to_le_bytes()),
218            // Handled above; unreachable, but the match has to be exhaustive.
219            ElementType::BigInt64 | ElementType::BigUint64 => {}
220        }
221        Ok(())
222    }
223}
224
225/// Why an element write was refused: the target is a BigInt type and the value is not one.
226pub const NOT_A_BIGINT: &str = "cannot convert a Number to a BigInt";
227
228/// Why an element write was refused: the target is numeric and the value has no number form.
229pub const NOT_A_NUMBER: &str = "cannot convert a Symbol or BigInt to a number";
230
231/// `ToIntegerOrInfinity`, truncated toward zero, as the integer element types need it.
232///
233/// A cast through `i64` would be undefined for out-of-range floats in Rust (`as` saturates
234/// since 1.45, which is the behaviour wanted here anyway), so the wrap happens at the target
235/// width — `as i8` and friends keep the low bits, which is exactly the spec's modulo.
236fn to_integer(number: f64) -> i64 {
237    if number.is_nan() {
238        return 0;
239    }
240    if number.is_infinite() {
241        // The modulo of an infinity is 0 in every engine; the alternative is to wrap the
242        // saturated value, which no script expects.
243        return 0;
244    }
245    number.trunc() as i64
246}
247
248/// `ToUint8Clamp`: round half to even, then clamp into `0..=255`.
249fn clamp_to_uint8(number: f64) -> u8 {
250    if number.is_nan() || number <= 0.0 {
251        return 0;
252    }
253    if number >= 255.0 {
254        return 255;
255    }
256    // `round_ties_even` is what the spec asks for; `0.5` must land on `0`, not `1`.
257    let rounded = number.round_ties_even();
258    rounded as u8
259}
260
261/// Decode an IEEE-754 binary16 value.
262fn f16_to_f64(bits: u16) -> f64 {
263    let sign = if bits & 0x8000 == 0 { 1.0 } else { -1.0 };
264    let exponent = ((bits >> 10) & 0x1f) as i32;
265    let mantissa = (bits & 0x3ff) as f64;
266    if exponent == 0 {
267        // Zero or subnormal: no implicit leading bit, and the scale is the smallest one.
268        sign * mantissa * 2f64.powi(-24)
269    } else if exponent == 0x1f {
270        if mantissa == 0.0 {
271            sign * f64::INFINITY
272        } else {
273            f64::NAN
274        }
275    } else {
276        sign * (1.0 + mantissa / 1024.0) * 2f64.powi(exponent - 15)
277    }
278}
279
280/// Encode a value as IEEE-754 binary16, rounding to nearest even.
281fn f64_to_f16(value: f64) -> u16 {
282    if value.is_nan() {
283        return 0x7e00;
284    }
285    let sign = if value.is_sign_negative() {
286        0x8000u16
287    } else {
288        0
289    };
290    let magnitude = value.abs();
291    if magnitude == 0.0 {
292        return sign;
293    }
294    if magnitude >= 65504.0 {
295        return sign | 0x7c00; // infinity
296    }
297    if magnitude < 6.103_515_625e-5 {
298        // Subnormal: the mantissa counts in units of 2^-24, rounded to nearest even.
299        let scaled = magnitude / 2f64.powi(-24);
300        let mantissa = scaled.round_ties_even();
301        return sign | (mantissa as u16);
302    }
303    // Normal: 1.m × 2^(e-15), so the exponent field is e + 15 and the mantissa keeps 10 bits.
304    let exponent = magnitude.log2().floor() as i32;
305    let biased = exponent + 15;
306    let mantissa = (magnitude / 2f64.powi(exponent) - 1.0) * 1024.0;
307    let rounded = mantissa.round_ties_even();
308    if rounded >= 1024.0 {
309        // Rounding carried into the exponent.
310        let biased = biased + 1;
311        if biased >= 0x1f {
312            return sign | 0x7c00;
313        }
314        return sign | ((biased as u16) << 10);
315    }
316    sign | ((biased as u16) << 10) | (rounded as u16)
317}
318
319/// Install `ArrayBuffer` and every typed-array view.
320pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
321    install_array_buffer(interp, object_proto);
322    install_views(interp, object_proto);
323    install_data_view(interp, object_proto);
324}
325
326fn install_array_buffer(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
327    let proto = interp.new_object(Some(object_proto.clone()));
328    let constructor = interp.new_native_constructor("ArrayBuffer", 1, buffer_constructor);
329    constructor.define(
330        "prototype",
331        Property::with_attributes(Value::Object(proto.clone()), false, false),
332    );
333    proto.define(
334        "constructor",
335        Property::with_attributes(Value::Object(constructor.clone()), true, false),
336    );
337    define_method(&proto, "transfer", 0, buffer_transfer, interp);
338    define_method(&proto, "slice", 2, buffer_slice, interp);
339    define_method(&proto, "resize", 1, buffer_resize, interp);
340    define_method(&constructor, "isView", 1, buffer_is_view, interp);
341    // `maxByteLength` and `resizable` are accessors for the same reason `byteLength` is: a
342    // detached buffer answers `0`/`false` rather than a stale number.
343    let max_getter = interp.new_native("get maxByteLength", 0, buffer_max_byte_length_getter);
344    proto.define(
345        "maxByteLength",
346        Property {
347            getter: Some(Value::Object(max_getter)),
348            enumerable: false,
349            configurable: true,
350            ..Property::default()
351        },
352    );
353    let resizable_getter = interp.new_native("get resizable", 0, buffer_resizable);
354    proto.define(
355        "resizable",
356        Property {
357            getter: Some(Value::Object(resizable_getter)),
358            enumerable: false,
359            configurable: true,
360            ..Property::default()
361        },
362    );
363    // `byteLength` is an accessor so a detached buffer reports `0` instead of a stale size.
364    let getter = interp.new_native("get byteLength", 0, buffer_byte_length);
365    proto.define(
366        "byteLength",
367        Property {
368            getter: Some(Value::Object(getter)),
369            enumerable: false,
370            configurable: true,
371            ..Property::default()
372        },
373    );
374    install_tag(&proto, "ArrayBuffer", interp);
375    install_species_accessor(&constructor, interp);
376    interp.realm.array_buffer_proto = Some(proto);
377    let global = interp.realm.global.clone();
378    global.define(
379        "ArrayBuffer",
380        Property::with_attributes(Value::Object(constructor), true, false),
381    );
382}
383
384fn install_views(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
385    // One shared prototype carries every method and every accessor; each element type gets a
386    // prototype of its own on top of it, which is what lets `BYTES_PER_ELEMENT` and the
387    // string tag differ per type while the behaviour is written once.
388    let shared = interp.new_object(Some(object_proto.clone()));
389    define_method(&shared, "set", 1, set_from, interp);
390    define_method(&shared, "fill", 1, fill, interp);
391    define_method(&shared, "join", 1, join, interp);
392    define_method(&shared, "toString", 0, join, interp);
393    define_method(&shared, "toLocaleString", 0, to_locale_string, interp);
394    define_method(&shared, "slice", 2, slice, interp);
395    define_method(&shared, "subarray", 2, subarray, interp);
396    // The whole `%TypedArray%.prototype` iteration family, which was absent: every
397    // `[].map.call(typedArray, f)` reached `undefined is not a function`.
398    define_method(&shared, "at", 1, at as crate::object::NativeFn, interp);
399    define_method(&shared, "every", 1, every, interp);
400    define_method(&shared, "some", 1, some, interp);
401    define_method(&shared, "forEach", 1, for_each, interp);
402    define_method(&shared, "map", 1, map, interp);
403    define_method(&shared, "filter", 1, filter, interp);
404    define_method(&shared, "reduce", 1, reduce, interp);
405    define_method(&shared, "reduceRight", 1, reduce_right, interp);
406    define_method(&shared, "find", 1, find, interp);
407    define_method(&shared, "findIndex", 1, find_index, interp);
408    define_method(&shared, "findLast", 1, find_last, interp);
409    define_method(&shared, "findLastIndex", 1, find_last_index, interp);
410    define_method(&shared, "indexOf", 1, index_of, interp);
411    define_method(&shared, "lastIndexOf", 1, last_index_of, interp);
412    define_method(&shared, "includes", 1, includes, interp);
413    define_method(&shared, "reverse", 0, reverse, interp);
414    define_method(&shared, "sort", 1, sort, interp);
415    define_method(&shared, "copyWithin", 2, copy_within, interp);
416    define_method(&shared, "with", 2, with, interp);
417    define_method(&shared, "toReversed", 0, to_reversed, interp);
418    define_method(&shared, "toSorted", 1, to_sorted, interp);
419    define_method(&shared, "values", 0, values, interp);
420    define_method(&shared, "keys", 0, keys, interp);
421    define_method(&shared, "entries", 0, entries, interp);
422    // `%TypedArray%.prototype[Symbol.iterator]` *is* `values`, not a wrapper around it.
423    if let Some(values_fn) = shared.own_property("values").and_then(|p| p.value) {
424        let key = interp
425            .realm
426            .well_known_key(crate::interp::WellKnown::Iterator);
427        shared.define_key(&key, Property::with_attributes(values_fn, true, false));
428    }
429    for (name, getter) in [
430        ("buffer", buffer_of as crate::object::NativeFn),
431        ("byteOffset", byte_offset_of),
432        ("byteLength", byte_length_of),
433        ("length", length_of),
434        ("[Symbol.toStringTag]", tag_of),
435    ] {
436        let function = interp.new_native(name, 0, getter);
437        let key = if name == "[Symbol.toStringTag]" {
438            interp
439                .realm
440                .well_known_key(crate::interp::WellKnown::ToStringTag)
441        } else {
442            crate::object::PropertyKey::from(name)
443        };
444        shared.define_key(
445            &key,
446            Property {
447                getter: Some(Value::Object(function)),
448                enumerable: false,
449                configurable: true,
450                ..Property::default()
451            },
452        );
453    }
454    interp.realm.typed_array_proto = Some(shared.clone());
455    // Built after the shared prototype exists, because `%TypedArray%.prototype` *is* that
456    // object and `constructor` has to point back at the intrinsic.
457    let intrinsic = install_typed_array_intrinsic(interp, &shared);
458
459    let global = interp.realm.global.clone();
460    for (element, name) in ELEMENT_TYPES {
461        let proto = interp.new_object(Some(shared.clone()));
462        // The constructor reads the element type off this, so `new` is the only way in.
463        proto.define(
464            "_element",
465            Property::with_attributes(Value::Int(element as i32), false, false),
466        );
467        proto.define(
468            "BYTES_PER_ELEMENT",
469            Property::with_attributes(Value::Int(element.size() as i32), false, false),
470        );
471        let constructor = interp.new_native_ctor(name, 3, view_constructor);
472        // `Object.getPrototypeOf(Int8Array)` is `%TypedArray%`, which is where `from` and
473        // `of` live; without it the statics were unreachable from every constructor.
474        constructor.set_proto(Some(intrinsic.clone()));
475        constructor.define(
476            "_element",
477            Property::with_attributes(Value::Int(element as i32), false, false),
478        );
479        constructor.define(
480            "BYTES_PER_ELEMENT",
481            Property::with_attributes(Value::Int(element.size() as i32), false, false),
482        );
483        constructor.define(
484            "prototype",
485            Property::with_attributes(Value::Object(proto.clone()), false, false),
486        );
487        proto.define(
488            "constructor",
489            Property::with_attributes(Value::Object(constructor.clone()), true, false),
490        );
491        // Remembered so a method that answers with a fresh view can give it the right
492        // prototype; `new_view` looks the type up in this vector.
493        interp.realm.typed_array_protos.push(proto.clone());
494        global.define(
495            name,
496            Property::with_attributes(Value::Object(constructor), true, false),
497        );
498    }
499}
500
501/// `ArrayBuffer.prototype[Symbol.toStringTag]`.
502/// `new ArrayBuffer(length)`.
503fn buffer_constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
504    let length = arg(args, 0).to_number();
505    // 2^53 - 1 is the largest byte length the spec allows, and the bound matters: a script
506    // asking for 2^60 bytes has to get a `RangeError` rather than an abort.
507    if length < 0.0 || length.fract() != 0.0 || length > 9_007_199_254_740_991.0 {
508        return Err(interp.range_error("invalid array buffer length"));
509    }
510    let length = length as usize;
511    // The optional second argument is the options bag: `{maxByteLength}` makes the buffer
512    // resizable. Absent means fixed-length, which is the case every other caller wants.
513    let max_byte_length = buffer_max_byte_length(interp, &arg(args, 1))?;
514    if max_byte_length.is_some_and(|max| max < length) {
515        return Err(interp.range_error("invalid max byte length"));
516    }
517    // The allocation can fail, and the spec makes that a `RangeError`
518    // (`CreateByteDataBlock`: "if it is impossible to create such a Data Block, throw a
519    // RangeError"). Letting `vec![0; length]` abort the process made
520    // `new ArrayBuffer(7 * 1024**5)` a crash instead of an exception — which is also what
521    // `ArrayBuffer/allocation-limit.js` asserts, so it has to be caught here rather than
522    // left to the allocator.
523    let bytes =
524        allocate_zeroed(length).ok_or_else(|| interp.range_error("invalid array buffer length"))?;
525    let storage = Rc::new(RefCell::new(BufferStorage {
526        bytes,
527        detached: false,
528        max_byte_length,
529        release: None,
530    }));
531    let default_proto = interp
532        .realm
533        .array_buffer_proto
534        .clone()
535        .unwrap_or_else(|| interp.realm.object_proto.clone());
536    let object = interp.new_ctor_instance(default_proto)?;
537    object.set_array_buffer(storage);
538    Ok(Value::Object(object))
539}
540
541/// A zeroed byte vector of `length` bytes, or `None` if the allocation would fail.
542///
543/// `try_reserve_exact` rather than `vec![0; length]`: the latter aborts on failure, and a
544/// script must not be able to abort the engine by asking for a buffer the machine cannot
545/// give it. The reserve is done in one step so that a huge length fails immediately instead
546/// of zeroing page by page until the process dies.
547fn allocate_zeroed(length: usize) -> Option<Vec<u8>> {
548    let mut bytes: Vec<u8> = Vec::new();
549    bytes.try_reserve_exact(length).ok()?;
550    bytes.resize(length, 0);
551    Some(bytes)
552}
553
554/// `maxByteLength` from the constructor's options bag, or `None` for a fixed-length buffer.
555///
556/// Read the way the spec reads an options object: only an *object* argument has properties to
557/// read, and a non-number `maxByteLength` is a `RangeError` rather than being ignored — a
558/// buffer silently not resizable would be the wrong answer for `assert(ab.resizable)`.
559fn buffer_max_byte_length(interp: &mut Interp<'_>, options: &Value) -> JsResult<Option<usize>> {
560    let Some(object) = options.as_object().cloned() else {
561        return Ok(None);
562    };
563    let max = interp.get_property(&object, "maxByteLength")?;
564    match max {
565        None | Some(Value::Undefined) => Ok(None),
566        Some(value) => {
567            let number = to_integer_or_infinity(interp, &value)?;
568            if !(0.0..=9_007_199_254_740_991.0).contains(&number) {
569                return Err(interp.range_error("invalid max byte length"));
570            }
571            Ok(Some(number as usize))
572        }
573    }
574}
575
576/// `ArrayBuffer.prototype.maxByteLength`.
577fn buffer_max_byte_length_getter(
578    interp: &mut Interp<'_>,
579    this: Value,
580    _args: &[Value],
581) -> JsResult<Value> {
582    let storage = buffer_storage_of(interp, &this)?;
583    let storage = storage.borrow();
584    Ok(Value::Float(if storage.detached {
585        0.0
586    } else {
587        storage.max_byte_length() as f64
588    }))
589}
590
591/// `ArrayBuffer.prototype.resizable`.
592fn buffer_resizable(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
593    let storage = buffer_storage_of(interp, &this)?;
594    let storage = storage.borrow();
595    Ok(Value::Bool(!storage.detached && storage.is_resizable()))
596}
597
598/// `ArrayBuffer.prototype.resize(newLength)`.
599///
600/// Growing zero-fills and shrinking truncates, which is what `Vec::resize` does — the two
601/// behaviours the spec asks for and the reason the old bytes are kept intact across a grow.
602fn buffer_resize(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
603    let storage = buffer_storage_of(interp, &this)?;
604    let requested = to_integer_or_infinity(interp, &arg(args, 0))?;
605    let mut storage = storage.borrow_mut();
606    if storage.detached {
607        return Err(interp.type_error("ArrayBuffer has already been detached"));
608    }
609    let Some(max) = storage.max_byte_length else {
610        return Err(interp.type_error("ArrayBuffer is not resizable"));
611    };
612    if requested < 0.0 || requested > max as f64 || requested > 9_007_199_254_740_991.0 {
613        return Err(interp.range_error("invalid array buffer length"));
614    }
615    storage.bytes.resize(requested as usize, 0);
616    Ok(Value::Undefined)
617}
618
619/// The storage of `this`, which must be an `ArrayBuffer`.
620fn buffer_storage_of(interp: &Interp<'_>, this: &Value) -> JsResult<Rc<RefCell<BufferStorage>>> {
621    this.as_object()
622        .and_then(|object| object.array_buffer_storage())
623        .ok_or_else(|| interp.type_error("not an ArrayBuffer"))
624}
625
626/// `ArrayBuffer.isView(arg)`.
627///
628/// The one predicate here that must *not* accept a Proxy: §25.1.3.1 tests for the
629/// `[[ViewedArrayBuffer]]` internal slot, and a Proxy over a typed array has none (it is
630/// not a view, it merely forwards to one). `isArrayBufferView` in the reference behaves
631/// the same way.
632fn buffer_is_view(_interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
633    let view = matches!(arg(args, 0), Value::Object(object) if object.is_array_buffer_view());
634    Ok(Value::Bool(view))
635}
636
637/// `ArrayBuffer.prototype.byteLength`.
638fn buffer_byte_length(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
639    let storage = buffer_storage_of(interp, &this)?;
640    let storage = storage.borrow();
641    Ok(Value::Int(if storage.detached {
642        0
643    } else {
644        storage.bytes.len() as i32
645    }))
646}
647
648/// `Buffer.prototype.transfer()`: hand the bytes to a new buffer and detach this one.
649fn buffer_transfer(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
650    let storage = buffer_storage_of(interp, &this)?;
651    let bytes = {
652        let mut storage = storage.borrow_mut();
653        if storage.detached {
654            return Err(interp.type_error("ArrayBuffer has already been detached"));
655        }
656        storage.detached = true;
657        std::mem::take(&mut storage.bytes)
658    };
659    let fresh_storage = Rc::new(RefCell::new(BufferStorage::fixed(bytes)));
660    let proto = interp
661        .realm
662        .array_buffer_proto
663        .clone()
664        .unwrap_or_else(|| interp.realm.object_proto.clone());
665    let object = interp.new_object(Some(proto));
666    object.set_array_buffer(fresh_storage);
667    Ok(Value::Object(object))
668}
669
670/// `buffer.slice(begin, end)`: a copy, which is what keeps the two independent.
671fn buffer_slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
672    let storage = buffer_storage_of(interp, &this)?;
673    let storage = storage.borrow();
674    if storage.detached {
675        return Err(interp.type_error("ArrayBuffer has already been detached"));
676    }
677    let length = storage.bytes.len() as i64;
678    let begin = clamp_index(arg(args, 0).to_number(), length, 0);
679    let end = clamp_index(arg(args, 1).to_number(), length, length);
680    let bytes = storage.bytes[begin as usize..end.max(begin) as usize].to_vec();
681    drop(storage);
682    let proto = interp
683        .realm
684        .array_buffer_proto
685        .clone()
686        .unwrap_or_else(|| interp.realm.object_proto.clone());
687    let object = interp.new_object(Some(proto));
688    object.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed(bytes))));
689    Ok(Value::Object(object))
690}
691
692/// Resolve a `begin`/`end` argument the way every slice does: relative to the end when
693/// negative, then clamped into range.
694fn clamp_index(value: f64, length: i64, default: i64) -> i64 {
695    if value.is_nan() {
696        return default.min(length).max(0);
697    }
698    let value = if value.is_infinite() {
699        if value > 0.0 { length } else { 0 }
700    } else {
701        value.trunc() as i64
702    };
703    (if value < 0 { length + value } else { value }).clamp(0, length)
704}
705
706/// `ToIndex`: `undefined` and `NaN` are `0`, a negative or infinite value is a
707/// `RangeError`, and so is a fraction rather than being truncated.
708///
709/// This is what makes `new Uint8Array(buffer)` mean "from byte 0, to the end": the missing
710/// second argument is `undefined`, which is `0`, and a `NaN` offset must not be a failure.
711/// `ToIntegerOrInfinity(value)`, which refuses a Symbol and a BigInt.
712///
713/// `Value::to_number` answers `NaN` for both so that it stays total; that made
714/// `copyWithin(0, Symbol())` a silent no-op instead of the `TypeError` the spec requires.
715fn to_integer_or_infinity(interp: &mut Interp<'_>, value: &Value) -> JsResult<f64> {
716    // `to_js_number` already refuses a Symbol and a BigInt, boxed ones included.
717    let number = interp.to_js_number(value)?;
718    Ok(if number.is_nan() { 0.0 } else { number.trunc() })
719}
720
721/// `ToIndex(value)`: `ToIntegerOrInfinity` and then a range check.
722///
723/// `ToIntegerOrInfinity` *truncates*, so `new Int32Array(2.7)` is two elements rather than
724/// a `RangeError`; only a negative or infinite result is refused. `ToNumber` on a BigInt is
725/// a `TypeError`, which is why the conversion goes through the interpreter.
726fn to_index(interp: &mut Interp<'_>, value: &Value, what: &str) -> JsResult<usize> {
727    // Through `ToIntegerOrInfinity`, so a Symbol or BigInt is a `TypeError` rather than the
728    // `NaN` that `Value::to_number` answers to stay total.
729    let number = to_integer_or_infinity(interp, value)?;
730    // `2^53 - 1` is the largest index the spec allows.
731    if number < 0.0 || number > 9_007_199_254_740_991.0 {
732        return Err(interp.range_error(format!("invalid {what}")));
733    }
734    Ok(number as usize)
735}
736
737/// The element type a typed-array *constructor* stands for, read off its `_element`.
738fn element_of_constructor(interp: &Interp<'_>, callee: &Gc<JsObject>) -> Option<ElementType> {
739    let raw = callee
740        .own_property("_element")
741        .and_then(|property| property.value)?;
742    let raw = raw.to_number() as i32;
743    let found = ELEMENT_TYPES
744        .into_iter()
745        .map(|(element, _)| element)
746        .find(|element| *element as i32 == raw);
747    let _ = interp;
748    found
749}
750
751/// `new Uint8Array(...)`: from a length, from a buffer, or from an array-like.
752fn view_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
753    // A typed-array constructor cannot be called as a function: there is no receiver to
754    // take an element type from, and the spec makes that a `TypeError`.
755    // The element type comes from the *callee*, not from a receiver: a native constructor is
756    // handed `this = undefined` and builds its own instance once its arguments are valid.
757    let _ = &this;
758    let callee = interp
759        .current_native()
760        .ok_or_else(|| interp.type_error("constructor requires 'new'"))?;
761    let element = element_of_constructor(interp, &callee)
762        .ok_or_else(|| interp.type_error("constructor requires 'new'"))?;
763    if !interp.is_constructing() {
764        return Err(interp.type_error("constructor requires 'new'"));
765    }
766    let first = arg(args, 0);
767    let (buffer, offset, length) = match &first {
768        // `new X(buffer, byteOffset, length)`: a window onto existing bytes.
769        Value::Object(object) if object.array_buffer_storage().is_some() => {
770            let storage = object
771                .array_buffer_storage()
772                .expect("checked by the guard above");
773            let total = storage.borrow().bytes.len();
774            let byte_offset = to_index(interp, &arg(args, 1), "byte offset")?;
775            // Misalignment is always `invalid offset`, but the two bounds failures are not
776            // the same error and do not even happen in the same branch. Reading
777            // `js_typed_array_constructor` in the reference:
778            //
779            // * no length given  -> `offset > byte_length` is `invalid offset`;
780            // * a length given    -> the *sum* `offset + len * size` is checked, and the
781            //   failure is `invalid length`. There is no separate `offset > byte_length`
782            //   test on that path, so `(buf16, 20, 1)` says `invalid length`.
783            if byte_offset % element.size() != 0 {
784                return Err(interp.range_error("invalid offset"));
785            }
786            let available = (total - byte_offset) / element.size();
787            // No third argument means "the rest of the buffer", which is different from
788            // `undefined` meaning 0 — hence a length check rather than a nullish one.
789            let length = if args.len() < 3 || matches!(arg(args, 2), Value::Undefined) {
790                if byte_offset > total {
791                    return Err(interp.range_error("invalid offset"));
792                }
793                // The remainder of the buffer has to be a whole number of elements:
794                // `04 00 00 00 05` is not a `Uint32Array` and cannot be one.
795                if total % element.size() != 0 {
796                    return Err(interp.range_error("invalid length"));
797                }
798                available
799            } else {
800                let requested = to_index(interp, &arg(args, 2), "length")?;
801                if byte_offset + requested * element.size() > total {
802                    return Err(interp.range_error("invalid length"));
803                }
804                requested
805            };
806            (object.clone(), byte_offset, length)
807        }
808        // `new X(length)` for any *primitive* argument: the spec goes to `ToIndex` before
809        // it ever looks for `Symbol.iterator`, so `new Int32Array("3")` is three zeroes
810        // rather than the three characters. Only an object is treated as a source.
811        Value::Int(_)
812        | Value::Float(_)
813        | Value::String(_)
814        | Value::Bool(_)
815        | Value::BigInt(_)
816        | Value::Null
817        | Value::Undefined => {
818            let count = to_index(interp, &first, "typed array length")?;
819            let proto = interp
820                .realm
821                .array_buffer_proto
822                .clone()
823                .unwrap_or_else(|| interp.realm.object_proto.clone());
824            let buffer = interp.new_object(Some(proto));
825            buffer.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed(vec![
826                0;
827                count * element.size()
828            ]))));
829            (buffer, 0, count)
830        }
831        // `new X(iterable)`: a buffer sized by the source, filled from it.
832        _ => {
833            // `Symbol.iterator` wins over `length`: an object that is both iterable and
834            // array-like is read through the iterator. That is what the harness's
835            // `makeIterable` — a plain object carrying only `Symbol.iterator` — needs, and
836            // without it every such source constructed an *empty* view.
837            let values = if interp.has_iterator(&first)? {
838                interp.collect_iterable(&first)?
839            } else {
840                interp.array_like_to_args(&first)?
841            };
842            let proto = interp
843                .realm
844                .array_buffer_proto
845                .clone()
846                .unwrap_or_else(|| interp.realm.object_proto.clone());
847            let buffer = interp.new_object(Some(proto));
848            let storage = Rc::new(RefCell::new(BufferStorage::fixed(vec![
849                0;
850                values.len()
851                    * element.size()
852            ])));
853            buffer.set_array_buffer(storage);
854            let count = values.len();
855            for (index, value) in values.into_iter().enumerate() {
856                // `new BigInt64Array([1])` is a TypeError: the initialiser runs
857                // `ToBigInt` on each value, and a Number is not convertible.
858                write_element(interp, &buffer, element, 0, index, value)?;
859            }
860            (buffer, 0, count)
861        }
862    };
863    let default_proto = interp
864        .realm
865        .typed_array_protos
866        .get(element as usize)
867        .cloned()
868        .or_else(|| interp.realm.typed_array_proto.clone())
869        .unwrap_or_else(|| interp.realm.object_proto.clone());
870    let object = interp.new_ctor_instance(default_proto)?;
871    object.set_typed_array(buffer, element, offset, length);
872    Ok(Value::Object(object))
873}
874
875/// Write one element through a buffer, for the paths that do not have a view in hand.
876/// Store `value` into the element at `index`, applying `ToNumber` or `ToBigInt` first.
877///
878/// Both conversions are fallible *and* can run script — `ToPrimitive` calls `valueOf` —
879/// so they happen before the buffer's `RefCell` is borrowed. Doing it inside
880/// [`ElementType::write`] would either need the borrow held across a script call (a
881/// re-entrancy panic waiting to happen) or would silently store `NaN` for an object,
882/// which is how `new Uint8Array([{valueOf(){return 5}}])` used to produce `0` instead of
883/// `5`.
884fn write_element(
885    interp: &mut Interp<'_>,
886    buffer: &Gc<JsObject>,
887    element: ElementType,
888    offset: usize,
889    index: usize,
890    value: Value,
891) -> JsResult<()> {
892    // The conversion first, and *outside* the storage borrow: `ToPrimitive` runs
893    // `valueOf`, which is script and can reach back into this very buffer.
894    let stored = interp.element_value(element, value)?;
895    let Some(storage) = buffer.array_buffer_storage() else {
896        return Ok(());
897    };
898    let mut storage = storage.borrow_mut();
899    if storage.detached {
900        return Ok(());
901    }
902    // The bounds check inside `write` answers `Ok`, so an out-of-range index stays a
903    // no-op rather than an error.
904    element
905        .write(&mut storage.bytes, offset + index * element.size(), &stored)
906        .map_err(|reason| match reason {
907            NOT_A_BIGINT => interp.type_error("cannot convert a Number to a BigInt"),
908            other => interp.type_error(other),
909        })
910}
911
912/// Read the elements of a typed array, which `join`/`set`/`slice` all need.
913fn elements_of(interp: &Interp<'_>, this: &Value) -> JsResult<Vec<Value>> {
914    let object = this
915        .as_object()
916        .ok_or_else(|| interp.type_error("not a typed array"))?;
917    let Some(length) = object.typed_array_length() else {
918        return Err(interp.type_error("not a typed array"));
919    };
920    Ok((0..length)
921        .map(|index| {
922            object
923                .typed_array_element(index)
924                .unwrap_or(Value::Undefined)
925        })
926        .collect())
927}
928
929/// `a.join(separator)`; `toString` shares it, which is what `Array.prototype.toString` does.
930fn join(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
931    let separator = match arg(args, 0) {
932        Value::Undefined => ",".to_string(),
933        other => interp.to_js_string(&other)?,
934    };
935    let elements = elements_of(interp, &this)?;
936    let mut parts = Vec::with_capacity(elements.len());
937    for element in elements {
938        parts.push(match element {
939            Value::Undefined | Value::Null => String::new(),
940            other => interp.to_js_string(&other)?,
941        });
942    }
943    Ok(interp.string(parts.join(&separator)))
944}
945
946/// `a.set(source, offset)`.
947fn set_from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
948    let object = this
949        .as_object()
950        .ok_or_else(|| interp.type_error("not a typed array"))?;
951    let Some(length) = object.typed_array_length() else {
952        return Err(interp.type_error("not a typed array"));
953    };
954    let offset = to_index(interp, &arg(args, 1), "offset")?;
955    let values = interp.array_like_to_args(&arg(args, 0))?;
956    if offset + values.len() > length {
957        return Err(interp.range_error("source is too large"));
958    }
959    // Read every value first, so `a.set(a)` — a self-copy — sees the original contents
960    // rather than a half-overwritten array.
961    for (index, value) in values.into_iter().enumerate() {
962        if let Some(element) = object.typed_array_element_type() {
963            let (buffer, base) = object
964                .typed_array_parts()
965                .map(|(buffer, _, base, _)| (buffer, base))
966                .expect("a typed array has parts");
967            write_element(interp, &buffer, element, base, offset + index, value)?;
968        }
969    }
970    Ok(Value::Undefined)
971}
972
973/// `a.fill(value, start, end)`.
974fn fill(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
975    let object = this
976        .as_object()
977        .ok_or_else(|| interp.type_error("not a typed array"))?
978        .clone();
979    let Some(length) = object.typed_array_length() else {
980        return Err(interp.type_error("not a typed array"));
981    };
982    let value = arg(args, 0);
983    let length_i = length as i64;
984    let start = clamp_index(
985        match args.get(1) {
986            None => 0.0,
987            Some(value) => value.to_number(),
988        },
989        length_i,
990        0,
991    );
992    let end = clamp_index(
993        match args.get(2) {
994            None => length as f64,
995            Some(value) => value.to_number(),
996        },
997        length_i,
998        length_i,
999    );
1000    let Some(element) = object.typed_array_element_type() else {
1001        return Err(interp.type_error("not a typed array"));
1002    };
1003    let (buffer, base) = object
1004        .typed_array_parts()
1005        .map(|(buffer, _, base, _)| (buffer, base))
1006        .expect("a typed array has parts");
1007    for index in start as usize..end.max(start) as usize {
1008        write_element(interp, &buffer, element, base, index, value.clone())?;
1009    }
1010    Ok(Value::Object(object))
1011}
1012
1013/// `%TypedArray%`: the intrinsic every view constructor inherits from.
1014///
1015/// Absent until now, which is why `Object.getPrototypeOf(Int8Array)` answered
1016/// `Function.prototype` and `Object.getPrototypeOf(Int8Array).from` was `undefined`. It is
1017/// not a constructor — calling or `new`-ing it is a `TypeError` — it exists to hold the
1018/// shared statics and `Symbol.species`.
1019fn install_typed_array_intrinsic(interp: &mut Interp<'_>, shared: &Gc<JsObject>) -> Gc<JsObject> {
1020    let intrinsic = interp.new_native("TypedArray", 0, typed_array_intrinsic_call);
1021    // `from` and `of` go on before `prototype`, because `Object.getOwnPropertyNames` reports
1022    // insertion order and the reference lists them in this order.
1023    define_method(
1024        &intrinsic,
1025        "from",
1026        1,
1027        from as crate::object::NativeFn,
1028        interp,
1029    );
1030    define_method(&intrinsic, "of", 0, of, interp);
1031    // `%TypedArray%.prototype` is the shared prototype, and it is read-only.
1032    intrinsic.define(
1033        "prototype",
1034        Property::prototype_of(Value::Object(shared.clone()), false),
1035    );
1036    // The constructor property points back, which is what `TA.prototype.constructor === TA`
1037    // and a species lookup both rely on.
1038    shared.define(
1039        "constructor",
1040        Property {
1041            value: Some(Value::Object(intrinsic.clone())),
1042            writable: true,
1043            enumerable: false,
1044            configurable: true,
1045            ..Property::default()
1046        },
1047    );
1048    // `get %TypedArray%[Symbol.species]` answers `this`, so a subclass that does not
1049    // override it still produces instances of itself.
1050    install_species_accessor(&intrinsic, interp);
1051    intrinsic
1052}
1053
1054/// `%TypedArray%` is abstract: both forms of construction are refused.
1055fn typed_array_intrinsic_call(
1056    interp: &mut Interp<'_>,
1057    _this: Value,
1058    _args: &[Value],
1059) -> JsResult<Value> {
1060    Err(interp.type_error("Abstract class TypedArray not directly constructable"))
1061}
1062
1063/// `%TypedArray%.from(source, mapfn, thisArg)`.
1064///
1065/// The result is built by calling `this` as a constructor, which is what makes
1066/// `MyArray.from(...)` answer a `MyArray` rather than an `Int8Array`.
1067fn from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1068    let source = arg(args, 0);
1069    let mapper = match args.get(1) {
1070        None | Some(Value::Undefined) => None,
1071        Some(candidate) if matches!(candidate, Value::Object(o) if o.is_callable()) => {
1072            Some(candidate.clone())
1073        }
1074        Some(_) => return Err(interp.type_error("mapfn is not a function")),
1075    };
1076    let this_arg = arg(args, 2);
1077    // The source is read either through `Symbol.iterator` or as an array-like, the same
1078    // choice the constructor makes.
1079    let values = if interp.has_iterator(&source)? {
1080        interp.collect_iterable(&source)?
1081    } else {
1082        interp.array_like_to_args(&source)?
1083    };
1084    let mut mapped = Vec::with_capacity(values.len());
1085    for (index, value) in values.into_iter().enumerate() {
1086        match &mapper {
1087            Some(mapper) => mapped.push(interp.call_value(
1088                mapper.clone(),
1089                this_arg.clone(),
1090                vec![value, Value::Int(index as i32)],
1091            )?),
1092            None => mapped.push(value),
1093        }
1094    }
1095    typed_array_from_values(interp, &this, &mapped)
1096}
1097
1098/// `%TypedArray%.of(...items)`.
1099fn of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1100    typed_array_from_values(interp, &this, args)
1101}
1102
1103/// Build a view by calling `constructor` with a length, then filling it.
1104fn typed_array_from_values(
1105    interp: &mut Interp<'_>,
1106    constructor: &Value,
1107    values: &[Value],
1108) -> JsResult<Value> {
1109    if !matches!(constructor, Value::Object(o) if o.is_callable()) {
1110        return Err(interp.type_error("not a constructor"));
1111    }
1112    let created = interp.construct(
1113        constructor.clone(),
1114        constructor.clone(),
1115        vec![Value::Int(values.len() as i32)],
1116    )?;
1117    let Some(object) = created.as_object().cloned() else {
1118        return Err(interp.type_error("constructor did not answer an object"));
1119    };
1120    let Some(element) = object.typed_array_element_type() else {
1121        return Err(interp.type_error("constructor did not answer a typed array"));
1122    };
1123    // The constructor is arbitrary script: it may answer a shorter view than asked for,
1124    // which the spec refuses rather than writing past the end.
1125    let available = object.typed_array_length().unwrap_or(0);
1126    if values.len() > available {
1127        return Err(interp.type_error("derived typed array has an insufficient length"));
1128    }
1129    write_back(interp, &object, element, values)?;
1130    Ok(created)
1131}
1132
1133/// A new view of `element` type holding `values`, which is what `map`/`filter`/`slice`
1134/// and friends answer with.
1135///
1136/// `%TypedArray%.prototype.map` is *not* `Array.prototype.map`: the result is a typed array
1137/// of the same element type, not an ordinary array, which is why the spec goes through
1138/// `TypedArraySpeciesCreate` rather than `ArraySpeciesCreate`.
1139fn new_view(
1140    interp: &mut Interp<'_>,
1141    element: ElementType,
1142    values: &[Value],
1143) -> JsResult<Gc<JsObject>> {
1144    let proto = interp
1145        .realm
1146        .array_buffer_proto
1147        .clone()
1148        .unwrap_or_else(|| interp.realm.object_proto.clone());
1149    let buffer = interp.new_object(Some(proto));
1150    buffer.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed(vec![
1151        0;
1152        values.len() * element.size()
1153    ]))));
1154    for (index, value) in values.iter().enumerate() {
1155        write_element(interp, &buffer, element, 0, index, value.clone())?;
1156    }
1157    let proto = interp
1158        .realm
1159        .typed_array_protos
1160        .get(element as usize)
1161        .cloned()
1162        .or_else(|| interp.realm.typed_array_proto.clone())
1163        .unwrap_or_else(|| interp.realm.object_proto.clone());
1164    let fresh = interp.new_object(Some(proto));
1165    fresh.set_typed_array(buffer, element, 0, values.len());
1166    Ok(fresh)
1167}
1168
1169/// `TypedArraySpeciesCreate(receiver, len)`: the view a method answers with.
1170///
1171/// The spec does not simply build a view of the same type. It reads `receiver.constructor`,
1172/// then that function's `Symbol.species`, and calls it with the length — so a subclass can
1173/// redirect the result and a test can assert the override was honoured, or that a throwing
1174/// species propagates. Falling straight through to `new_view` made every `speciesctor` case
1175/// fail even though the elements were right.
1176fn species_create(
1177    interp: &mut Interp<'_>,
1178    receiver: &Gc<JsObject>,
1179    element: ElementType,
1180    values: &[Value],
1181) -> JsResult<Gc<JsObject>> {
1182    let constructor = interp.get_property(receiver, "constructor")?;
1183    let species = match &constructor {
1184        // `undefined` — or no `constructor` at all — means "use the default".
1185        None | Some(Value::Undefined) => None,
1186        Some(Value::Object(constructor)) => {
1187            let key = interp
1188                .realm
1189                .well_known_key(crate::interp::WellKnown::Species);
1190            interp.get_property_key(constructor, &key)?
1191        }
1192        // Anything else is neither absent nor an object, and `SpeciesConstructor` refuses
1193        // it outright: `sample.constructor = 42` makes `sample.map(f)` a `TypeError`.
1194        Some(_) => return Err(interp.type_error("constructor is not an object")),
1195    };
1196    let species = match species {
1197        Some(Value::Null) | None | Some(Value::Undefined) => {
1198            return new_view(interp, element, values);
1199        }
1200        Some(other) => other,
1201    };
1202    if !matches!(&species, Value::Object(o) if o.is_callable()) {
1203        return Err(interp.type_error("species is not a constructor"));
1204    }
1205    let created = interp.construct(
1206        species.clone(),
1207        species,
1208        vec![Value::Int(values.len() as i32)],
1209    )?;
1210    let Some(object) = created.as_object().cloned() else {
1211        return Err(interp.type_error("species constructor did not answer an object"));
1212    };
1213    let Some(actual_element) = object.typed_array_element_type() else {
1214        return Err(interp.type_error("species constructor did not answer a typed array"));
1215    };
1216    // A species is allowed to answer a *longer* view but not a shorter one: the spec
1217    // checks `srcLength <= targetLength`.
1218    let available = object.typed_array_length().unwrap_or(0);
1219    if values.len() > available {
1220        return Err(interp.type_error("derived typed array has an insufficient length"));
1221    }
1222    write_back(interp, &object, actual_element, values)?;
1223    Ok(object)
1224}
1225
1226/// The receiver as `(elements, element type)`, the shape every method here starts from.
1227///
1228/// A typed array is never a plain object: unlike `Array.prototype`'s methods, these do not
1229/// run `ToObject` on anything, they refuse a receiver that is not a view.
1230fn view_parts(interp: &mut Interp<'_>, this: &Value) -> JsResult<(Vec<Value>, ElementType)> {
1231    let Some(object) = this.as_object() else {
1232        return Err(interp.type_error("not a typed array"));
1233    };
1234    let Some(element) = object.typed_array_element_type() else {
1235        return Err(interp.type_error("not a typed array"));
1236    };
1237    // `ValidateTypedArray` runs `IsDetachedBuffer` and refuses. Without this a detached
1238    // view silently behaved like an empty one, so every `detached-buffer` test — which
1239    // expects a `TypeError` — saw a clean return instead.
1240    if is_detached(object) {
1241        return Err(interp.type_error("the buffer is detached"));
1242    }
1243    Ok((elements_of(interp, this)?, element))
1244}
1245
1246/// Whether this view's buffer has been detached.
1247fn is_detached(object: &Gc<JsObject>) -> bool {
1248    let Some((buffer, _, _, _)) = object.typed_array_parts() else {
1249        return false;
1250    };
1251    buffer
1252        .array_buffer_storage()
1253        .is_some_and(|storage| storage.borrow().detached)
1254}
1255
1256/// The callback a typed-array method requires, or a `TypeError`.
1257fn typed_callback(interp: &mut Interp<'_>, args: &[Value]) -> JsResult<Value> {
1258    let callback = arg(args, 0);
1259    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
1260        return Err(interp.type_error("callback is not a function"));
1261    }
1262    Ok(callback)
1263}
1264
1265/// Call `callback(element, index, receiver)` for every element.
1266fn call_typed(
1267    interp: &mut Interp<'_>,
1268    callback: &Value,
1269    value: Value,
1270    index: usize,
1271    receiver: &Gc<JsObject>,
1272    this_arg: Value,
1273) -> JsResult<Value> {
1274    interp.call_value(
1275        callback.clone(),
1276        this_arg,
1277        vec![
1278            value,
1279            Value::Int(index as i32),
1280            Value::Object(receiver.clone()),
1281        ],
1282    )
1283}
1284
1285/// `a.at(index)`: negative counts from the end, out of range is `undefined`.
1286fn at(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1287    let (elements, _) = view_parts(interp, &this)?;
1288    let length = elements.len() as f64;
1289    let raw = arg(args, 0).to_number().trunc();
1290    let index = if raw < 0.0 { length + raw } else { raw };
1291    if index < 0.0 || index >= length {
1292        return Ok(Value::Undefined);
1293    }
1294    Ok(elements[index as usize].clone())
1295}
1296
1297/// `a.every(f)` / `a.some(f)`.
1298fn every(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1299    quantify(interp, this, args, false)
1300}
1301
1302fn some(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1303    quantify(interp, this, args, true)
1304}
1305
1306fn quantify(
1307    interp: &mut Interp<'_>,
1308    this: Value,
1309    args: &[Value],
1310    want_any: bool,
1311) -> JsResult<Value> {
1312    let receiver = this
1313        .as_object()
1314        .cloned()
1315        .ok_or_else(|| interp.type_error("not a typed array"))?;
1316    let (elements, _) = view_parts(interp, &this)?;
1317    let callback = typed_callback(interp, args)?;
1318    let this_arg = crate::builtins::array::callback_this(args);
1319    for (index, value) in elements.into_iter().enumerate() {
1320        let answer = call_typed(interp, &callback, value, index, &receiver, this_arg.clone())?;
1321        // `every` stops on the first falsy answer, `some` on the first truthy one.
1322        if answer.to_boolean() == want_any {
1323            return Ok(Value::Bool(want_any));
1324        }
1325    }
1326    Ok(Value::Bool(!want_any))
1327}
1328
1329fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1330    let receiver = this
1331        .as_object()
1332        .cloned()
1333        .ok_or_else(|| interp.type_error("not a typed array"))?;
1334    let (elements, _) = view_parts(interp, &this)?;
1335    let callback = typed_callback(interp, args)?;
1336    let this_arg = crate::builtins::array::callback_this(args);
1337    for (index, value) in elements.into_iter().enumerate() {
1338        call_typed(interp, &callback, value, index, &receiver, this_arg.clone())?;
1339    }
1340    Ok(Value::Undefined)
1341}
1342
1343fn map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1344    let receiver = this
1345        .as_object()
1346        .cloned()
1347        .ok_or_else(|| interp.type_error("not a typed array"))?;
1348    let (elements, element_type) = view_parts(interp, &this)?;
1349    let callback = typed_callback(interp, args)?;
1350    let this_arg = crate::builtins::array::callback_this(args);
1351    let mut out = Vec::with_capacity(elements.len());
1352    for (index, value) in elements.into_iter().enumerate() {
1353        out.push(call_typed(
1354            interp,
1355            &callback,
1356            value,
1357            index,
1358            &receiver,
1359            this_arg.clone(),
1360        )?);
1361    }
1362    Ok(Value::Object(species_create(
1363        interp,
1364        &receiver,
1365        element_type,
1366        &out,
1367    )?))
1368}
1369
1370fn filter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1371    let receiver = this
1372        .as_object()
1373        .cloned()
1374        .ok_or_else(|| interp.type_error("not a typed array"))?;
1375    let (elements, element_type) = view_parts(interp, &this)?;
1376    let callback = typed_callback(interp, args)?;
1377    let this_arg = crate::builtins::array::callback_this(args);
1378    let mut out = Vec::new();
1379    for (index, value) in elements.into_iter().enumerate() {
1380        let keep = call_typed(
1381            interp,
1382            &callback,
1383            value.clone(),
1384            index,
1385            &receiver,
1386            this_arg.clone(),
1387        )?;
1388        if keep.to_boolean() {
1389            out.push(value);
1390        }
1391    }
1392    Ok(Value::Object(species_create(
1393        interp,
1394        &receiver,
1395        element_type,
1396        &out,
1397    )?))
1398}
1399
1400fn reduce(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1401    reduce_with(interp, this, args, false)
1402}
1403
1404fn reduce_right(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1405    reduce_with(interp, this, args, true)
1406}
1407
1408fn reduce_with(
1409    interp: &mut Interp<'_>,
1410    this: Value,
1411    args: &[Value],
1412    right_to_left: bool,
1413) -> JsResult<Value> {
1414    let receiver = this
1415        .as_object()
1416        .cloned()
1417        .ok_or_else(|| interp.type_error("not a typed array"))?;
1418    let (elements, _) = view_parts(interp, &this)?;
1419    let callback = typed_callback(interp, args)?;
1420    let mut indices: Vec<usize> = (0..elements.len()).collect();
1421    if right_to_left {
1422        indices.reverse();
1423    }
1424    let mut ordered = indices.into_iter();
1425    let mut accumulator = match args.get(1) {
1426        Some(value) if !matches!(value, Value::Undefined) => value.clone(),
1427        _ => match ordered.next() {
1428            Some(index) => elements[index].clone(),
1429            None => {
1430                return Err(interp.type_error("Reduce of empty array with no initial value"));
1431            }
1432        },
1433    };
1434    for index in ordered {
1435        accumulator = interp.call_value(
1436            callback.clone(),
1437            Value::Undefined,
1438            vec![
1439                accumulator,
1440                elements[index].clone(),
1441                Value::Int(index as i32),
1442                Value::Object(receiver.clone()),
1443            ],
1444        )?;
1445    }
1446    Ok(accumulator)
1447}
1448
1449fn find(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1450    find_with(interp, this, args, FindKind::Value, false)
1451}
1452
1453fn find_index(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1454    find_with(interp, this, args, FindKind::Index, false)
1455}
1456
1457fn find_last(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1458    find_with(interp, this, args, FindKind::Value, true)
1459}
1460
1461fn find_last_index(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1462    find_with(interp, this, args, FindKind::Index, true)
1463}
1464
1465#[derive(Clone, Copy)]
1466enum FindKind {
1467    Value,
1468    Index,
1469}
1470
1471fn find_with(
1472    interp: &mut Interp<'_>,
1473    this: Value,
1474    args: &[Value],
1475    kind: FindKind,
1476    from_end: bool,
1477) -> JsResult<Value> {
1478    let receiver = this
1479        .as_object()
1480        .cloned()
1481        .ok_or_else(|| interp.type_error("not a typed array"))?;
1482    let (elements, _) = view_parts(interp, &this)?;
1483    let callback = typed_callback(interp, args)?;
1484    let this_arg = crate::builtins::array::callback_this(args);
1485    let mut indices: Vec<usize> = (0..elements.len()).collect();
1486    if from_end {
1487        indices.reverse();
1488    }
1489    for index in indices {
1490        let value = elements[index].clone();
1491        let answer = call_typed(
1492            interp,
1493            &callback,
1494            value.clone(),
1495            index,
1496            &receiver,
1497            this_arg.clone(),
1498        )?;
1499        if answer.to_boolean() {
1500            return Ok(match kind {
1501                FindKind::Value => value,
1502                FindKind::Index => Value::Int(index as i32),
1503            });
1504        }
1505    }
1506    Ok(match kind {
1507        FindKind::Value => Value::Undefined,
1508        FindKind::Index => Value::Int(-1),
1509    })
1510}
1511
1512fn index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1513    search(interp, this, args, SearchKind::IndexOf, false)
1514}
1515
1516fn last_index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1517    search(interp, this, args, SearchKind::IndexOf, true)
1518}
1519
1520fn includes(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1521    search(interp, this, args, SearchKind::Includes, false)
1522}
1523
1524#[derive(Clone, Copy)]
1525enum SearchKind {
1526    /// `===`-style, so `NaN` is never found.
1527    IndexOf,
1528    /// `SameValueZero`, so `NaN` is found, and the answer is a boolean.
1529    Includes,
1530}
1531
1532fn search(
1533    interp: &mut Interp<'_>,
1534    this: Value,
1535    args: &[Value],
1536    kind: SearchKind,
1537    from_end: bool,
1538) -> JsResult<Value> {
1539    let (elements, _) = view_parts(interp, &this)?;
1540    let needle = arg(args, 0);
1541    let length = elements.len();
1542    // `fromIndex` is `ToIntegerOrInfinity`, so a Symbol here is a `TypeError` — which is
1543    // why the conversion has to happen even when the answer is already decided. Ignoring
1544    // the argument made `includes(7, Symbol())` return cleanly instead of throwing.
1545    let missing = match args.get(1) {
1546        None | Some(Value::Undefined) => true,
1547        Some(_) => false,
1548    };
1549    let start = if from_end {
1550        // `lastIndexOf`: the default is the last index, and a negative offset counts back
1551        // from the end; anything below zero means "not found".
1552        let raw = if missing {
1553            length as f64
1554        } else {
1555            to_integer_or_infinity(interp, &arg(args, 1))?
1556        };
1557        if raw < 0.0 {
1558            match (length as f64 + raw) as i64 {
1559                n if n < 0 => None,
1560                n => Some(n as usize),
1561            }
1562        } else {
1563            Some((raw.min(length as f64) as usize).min(length.saturating_sub(1)))
1564        }
1565    } else {
1566        // `indexOf`/`includes`: the default is the first index, and a negative offset
1567        // counts back from the end but clamps to zero.
1568        let raw = if missing {
1569            0.0
1570        } else {
1571            to_integer_or_infinity(interp, &arg(args, 1))?
1572        };
1573        if raw >= 0.0 {
1574            Some(raw.min(length as f64) as usize)
1575        } else {
1576            Some(((length as f64 + raw).max(0.0)) as usize)
1577        }
1578    };
1579    let mut order: Vec<usize> = match start {
1580        None => Vec::new(),
1581        Some(start) if from_end => (0..=start.min(length.saturating_sub(1))).rev().collect(),
1582        Some(start) => (start..length).collect(),
1583    };
1584    if length == 0 {
1585        order.clear();
1586    }
1587    for index in order {
1588        let value = &elements[index];
1589        let found = match kind {
1590            SearchKind::IndexOf => value.strict_equals(&needle),
1591            // `includes` uses SameValueZero, which finds a `NaN` that `indexOf` cannot.
1592            SearchKind::Includes => value.same_value_zero(&needle),
1593        };
1594        if found {
1595            return Ok(match kind {
1596                SearchKind::IndexOf => Value::Int(index as i32),
1597                SearchKind::Includes => Value::Bool(true),
1598            });
1599        }
1600    }
1601    Ok(match kind {
1602        SearchKind::IndexOf => Value::Int(-1),
1603        SearchKind::Includes => Value::Bool(false),
1604    })
1605}
1606
1607/// `a.reverse()`: in place, and it answers the receiver.
1608fn reverse(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1609    let object = this
1610        .as_object()
1611        .cloned()
1612        .ok_or_else(|| interp.type_error("not a typed array"))?;
1613    let (mut elements, element_type) = view_parts(interp, &this)?;
1614    elements.reverse();
1615    write_back(interp, &object, element_type, &elements)?;
1616    Ok(Value::Object(object))
1617}
1618
1619fn sort(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1620    let object = this
1621        .as_object()
1622        .cloned()
1623        .ok_or_else(|| interp.type_error("not a typed array"))?;
1624    let (mut elements, element_type) = view_parts(interp, &this)?;
1625    match args.first() {
1626        // The default order is numeric for a typed array, unlike `Array.prototype.sort`'s
1627        // string order — `new Int32Array([10, 9]).sort()` is `[9, 10]`.
1628        None | Some(Value::Undefined) => {
1629            if element_type.is_bigint() {
1630                elements.sort_by(compare_bigints);
1631            } else {
1632                elements.sort_by(|a, b| {
1633                    a.to_number()
1634                        .partial_cmp(&b.to_number())
1635                        .unwrap_or(std::cmp::Ordering::Equal)
1636                });
1637            }
1638        }
1639        Some(comparator) if matches!(comparator, Value::Object(o) if o.is_callable()) => {
1640            // A comparator is arbitrary script, so Rust's sort cannot be told it is a
1641            // total order; this merge sort keeps the comparison count deterministic.
1642            merge_sort_typed(interp, &mut elements, comparator)?;
1643        }
1644        Some(_) => return Err(interp.type_error("comparator is not a function")),
1645    }
1646    write_back(interp, &object, element_type, &elements)?;
1647    Ok(Value::Object(object))
1648}
1649
1650fn compare_bigints(a: &Value, b: &Value) -> std::cmp::Ordering {
1651    match (a, b) {
1652        (Value::BigInt(a), Value::BigInt(b)) => a.cmp(b),
1653        _ => std::cmp::Ordering::Equal,
1654    }
1655}
1656
1657fn merge_sort_typed(
1658    interp: &mut Interp<'_>,
1659    items: &mut Vec<Value>,
1660    comparator: &Value,
1661) -> JsResult<()> {
1662    if items.len() <= 1 {
1663        return Ok(());
1664    }
1665    let mid = items.len() / 2;
1666    let mut right = items.split_off(mid);
1667    merge_sort_typed(interp, items, comparator)?;
1668    merge_sort_typed(interp, &mut right, comparator)?;
1669    let mut merged = Vec::with_capacity(items.len() + right.len());
1670    let mut left_iter = std::mem::take(items).into_iter().peekable();
1671    let mut right_iter = right.into_iter().peekable();
1672    loop {
1673        match (left_iter.peek(), right_iter.peek()) {
1674            (Some(left), Some(right_value)) => {
1675                let answer = interp.call_value(
1676                    comparator.clone(),
1677                    Value::Undefined,
1678                    vec![left.clone(), right_value.clone()],
1679                )?;
1680                if answer.to_number() > 0.0 {
1681                    merged.push(right_iter.next().expect("peeked"));
1682                } else {
1683                    merged.push(left_iter.next().expect("peeked"));
1684                }
1685            }
1686            (Some(_), None) => merged.push(left_iter.next().expect("peeked")),
1687            (None, Some(_)) => merged.push(right_iter.next().expect("peeked")),
1688            (None, None) => break,
1689        }
1690    }
1691    *items = merged;
1692    Ok(())
1693}
1694
1695/// Store `values` back into the receiver's view, which is how the in-place methods answer.
1696fn write_back(
1697    interp: &mut Interp<'_>,
1698    object: &Gc<JsObject>,
1699    element_type: ElementType,
1700    values: &[Value],
1701) -> JsResult<()> {
1702    let Some((buffer, _, base, _)) = object.typed_array_parts() else {
1703        return Err(interp.type_error("not a typed array"));
1704    };
1705    for (index, value) in values.iter().enumerate() {
1706        write_element(interp, &buffer, element_type, base, index, value.clone())?;
1707    }
1708    Ok(())
1709}
1710
1711/// `a.copyWithin(target, start, end)`: copies a run of elements over an earlier one.
1712fn copy_within(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1713    let object = this
1714        .as_object()
1715        .cloned()
1716        .ok_or_else(|| interp.type_error("not a typed array"))?;
1717    let (mut elements, element_type) = view_parts(interp, &this)?;
1718    let length_i = elements.len() as i64;
1719    let target = clamp_index(to_integer_or_infinity(interp, &arg(args, 0))?, length_i, 0);
1720    let start = clamp_index(to_integer_or_infinity(interp, &arg(args, 1))?, length_i, 0);
1721    let end = match args.get(2) {
1722        None | Some(Value::Undefined) => length_i,
1723        Some(value) => clamp_index(to_integer_or_infinity(interp, value)?, length_i, length_i),
1724    };
1725    // The index arguments are arbitrary script through `valueOf`, and one of them may
1726    // detach the buffer: `copyWithin(0, {valueOf(){ detach() }})` must throw, not copy from
1727    // storage that is gone. `ValidateTypedArray` therefore runs again here.
1728    if is_detached(&object) {
1729        return Err(interp.type_error("the buffer is detached"));
1730    }
1731    let count = (end - start).min(length_i - target).max(0) as usize;
1732    // A temporary, because the ranges may overlap: `copyWithin(0, 1)` would otherwise read
1733    // values it had already overwritten.
1734    let source: Vec<Value> = (0..count)
1735        .map(|offset| elements[start as usize + offset].clone())
1736        .collect();
1737    for (offset, value) in source.into_iter().enumerate() {
1738        elements[target as usize + offset] = value;
1739    }
1740    write_back(interp, &object, element_type, &elements)?;
1741    Ok(Value::Object(object))
1742}
1743
1744/// `a.toLocaleString()`: each element through its own `toLocaleString`, joined by `,`.
1745fn to_locale_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1746    let elements = elements_of(interp, &this)?;
1747    let mut parts = Vec::with_capacity(elements.len());
1748    for element in elements {
1749        // `undefined` and `null` contribute an empty field, exactly as `join` does.
1750        if matches!(element, Value::Undefined | Value::Null) {
1751            parts.push(String::new());
1752            continue;
1753        }
1754        // Read `toLocaleString` off the element's own chain, so a Number reaches
1755        // `Number.prototype.toLocaleString` and a BigInt reaches `BigInt.prototype`'s.
1756        let method = match &element {
1757            Value::Object(object) => interp.get_property(object, "toLocaleString")?,
1758            primitive => {
1759                let boxed = interp.object_from(primitive)?;
1760                interp.get_property(&boxed, "toLocaleString")?
1761            }
1762        };
1763        let text = match method {
1764            Some(method) => {
1765                let result = interp.call_value(method, element.clone(), Vec::new())?;
1766                interp.to_js_string(&result)?
1767            }
1768            None => interp.to_js_string(&element)?,
1769        };
1770        parts.push(text);
1771    }
1772    Ok(interp.string(parts.join(",")))
1773}
1774
1775/// `a.with(index, value)`: a copy with one element replaced.
1776fn with(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1777    let (mut elements, element_type) = view_parts(interp, &this)?;
1778    let length = elements.len() as f64;
1779    let raw = arg(args, 0).to_number().trunc();
1780    let index = if raw < 0.0 { length + raw } else { raw };
1781    if index < 0.0 || index >= length {
1782        return Err(interp.range_error("index is out of range"));
1783    }
1784    elements[index as usize] = arg(args, 1);
1785    let receiver = this
1786        .as_object()
1787        .cloned()
1788        .ok_or_else(|| interp.type_error("not a typed array"))?;
1789    Ok(Value::Object(species_create(
1790        interp,
1791        &receiver,
1792        element_type,
1793        &elements,
1794    )?))
1795}
1796
1797fn to_reversed(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1798    let receiver = this
1799        .as_object()
1800        .cloned()
1801        .ok_or_else(|| interp.type_error("not a typed array"))?;
1802    let (mut elements, element_type) = view_parts(interp, &this)?;
1803    elements.reverse();
1804    Ok(Value::Object(species_create(
1805        interp,
1806        &receiver,
1807        element_type,
1808        &elements,
1809    )?))
1810}
1811
1812fn to_sorted(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1813    let (elements, element_type) = view_parts(interp, &this)?;
1814    // Reuse `sort` by handing it a fresh view of the same contents.
1815    let copy = new_view(interp, element_type, &elements)?;
1816    sort(interp, Value::Object(copy.clone()), args)?;
1817    Ok(Value::Object(copy))
1818}
1819
1820/// `a.values()` / `a.keys()` / `a.entries()`.
1821///
1822/// The iterator machinery is shared with `Array.prototype`: `length_of` and `element_at`
1823/// reach a typed array through its exotic `length` and index properties, so the same
1824/// `next` walks it correctly and the laziness carries over.
1825fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1826    // `%TypedArray%.prototype.values` runs `ValidateTypedArray` before building the
1827    // iterator, so a detached view throws here rather than on the first `next`.
1828    view_parts(interp, &this)?;
1829    crate::builtins::array::iterator(interp, this, crate::builtins::array::IteratorKind::Value)
1830}
1831
1832fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1833    view_parts(interp, &this)?;
1834    crate::builtins::array::iterator(interp, this, crate::builtins::array::IteratorKind::Key)
1835}
1836
1837fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1838    view_parts(interp, &this)?;
1839    crate::builtins::array::iterator(interp, this, crate::builtins::array::IteratorKind::Entry)
1840}
1841
1842/// `a.slice(begin, end)`: a new view with a buffer of its own.
1843fn slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1844    let (elements, element_type) = view_parts(interp, &this)?;
1845    let receiver = this
1846        .as_object()
1847        .cloned()
1848        .ok_or_else(|| interp.type_error("not a typed array"))?;
1849    let length_i = elements.len() as i64;
1850    let begin = clamp_index(arg(args, 0).to_number(), length_i, 0);
1851    let end = clamp_index(
1852        match args.get(1) {
1853            None | Some(Value::Undefined) => length_i as f64,
1854            Some(value) => value.to_number(),
1855        },
1856        length_i,
1857        length_i,
1858    );
1859    let count = (end - begin).max(0) as usize;
1860    // Copied into a temporary first: `slice` reads the source through `[[Get]]` and builds
1861    // the result through `TypedArraySpeciesCreate`, and a species override may resize the
1862    // source, so the two must not be interleaved.
1863    let taken: Vec<Value> = (0..count)
1864        .map(|index| elements[begin as usize + index].clone())
1865        .collect();
1866    Ok(Value::Object(species_create(
1867        interp,
1868        &receiver,
1869        element_type,
1870        &taken,
1871    )?))
1872}
1873
1874/// `a.subarray(begin, end)`: a view over the *same* buffer.
1875fn subarray(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1876    let object = this
1877        .as_object()
1878        .ok_or_else(|| interp.type_error("not a typed array"))?;
1879    let Some((buffer, element, base, length)) = object.typed_array_parts() else {
1880        return Err(interp.type_error("not a typed array"));
1881    };
1882    let length_i = length as i64;
1883    let begin = clamp_index(arg(args, 0).to_number(), length_i, 0);
1884    let end = clamp_index(
1885        match args.get(1) {
1886            None => length as f64,
1887            Some(value) => value.to_number(),
1888        },
1889        length_i,
1890        length_i,
1891    );
1892    let count = (end - begin).max(0) as usize;
1893    let fresh = interp.new_object(Some(
1894        interp
1895            .realm
1896            .typed_array_proto
1897            .clone()
1898            .unwrap_or_else(|| interp.realm.object_proto.clone()),
1899    ));
1900    fresh.set_typed_array(
1901        buffer,
1902        element,
1903        base + begin as usize * element.size(),
1904        count,
1905    );
1906    Ok(Value::Object(fresh))
1907}
1908
1909/// The `buffer` accessor.
1910fn buffer_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1911    let object = this
1912        .as_object()
1913        .ok_or_else(|| interp.type_error("not a typed array"))?;
1914    object
1915        .typed_array_parts()
1916        .map(|(buffer, _, _, _)| Value::Object(buffer))
1917        .ok_or_else(|| interp.type_error("not a typed array"))
1918}
1919
1920/// The `byteOffset` accessor.
1921fn byte_offset_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1922    let object = this
1923        .as_object()
1924        .ok_or_else(|| interp.type_error("not a typed array"))?;
1925    object
1926        .typed_array_parts()
1927        .map(|(_, _, base, _)| Value::Int(base as i32))
1928        .ok_or_else(|| interp.type_error("not a typed array"))
1929}
1930
1931/// The `byteLength` accessor.
1932fn byte_length_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1933    let object = this
1934        .as_object()
1935        .ok_or_else(|| interp.type_error("not a typed array"))?;
1936    object
1937        .typed_array_parts()
1938        .map(|(_, element, _, length)| Value::Int((length * element.size()) as i32))
1939        .ok_or_else(|| interp.type_error("not a typed array"))
1940}
1941
1942/// The `length` accessor.
1943fn length_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1944    let object = this
1945        .as_object()
1946        .ok_or_else(|| interp.type_error("not a typed array"))?;
1947    object
1948        .typed_array_length()
1949        .map(|length| Value::Int(length as i32))
1950        .ok_or_else(|| interp.type_error("not a typed array"))
1951}
1952
1953/// The `Symbol.toStringTag` accessor, which names the element type.
1954fn tag_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1955    let object = this
1956        .as_object()
1957        .ok_or_else(|| interp.type_error("not a typed array"))?;
1958    let name = object
1959        .typed_array_element_type()
1960        .map(|element| element.name());
1961    Ok(match name {
1962        Some(name) => interp.string(name),
1963        None => Value::Undefined,
1964    })
1965}
1966
1967// ---------------------------------------------------------------------------
1968// DataView
1969// ---------------------------------------------------------------------------
1970
1971/// One `get`/`set` pair per width. `NativeFn` is a bare function pointer, so the width has
1972/// to be baked into the function rather than captured: the macro below writes one pair of
1973/// thin wrappers per row.
1974macro_rules! data_view_accessors {
1975    ($($get:ident, $set:ident => $element:expr, $width:literal);* $(;)?) => {
1976        $(
1977            fn $get(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1978                data_view_get(interp, &this, args, $element)
1979            }
1980            fn $set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1981                data_view_set(interp, &this, args, $element)
1982            }
1983        )*
1984
1985        /// Every accessor, as `(name, length, body)`.
1986        const DATA_VIEW_METHODS: &[(&str, u32, crate::object::NativeFn)] = &[
1987            $(
1988                (concat!("get", $width), 1, $get as crate::object::NativeFn),
1989                (concat!("set", $width), 2, $set as crate::object::NativeFn),
1990            )*
1991        ];
1992    };
1993}
1994
1995data_view_accessors! {
1996    get_int8, set_int8 => ElementType::Int8, "Int8";
1997    get_uint8, set_uint8 => ElementType::Uint8, "Uint8";
1998    get_int16, set_int16 => ElementType::Int16, "Int16";
1999    get_uint16, set_uint16 => ElementType::Uint16, "Uint16";
2000    get_int32, set_int32 => ElementType::Int32, "Int32";
2001    get_uint32, set_uint32 => ElementType::Uint32, "Uint32";
2002    get_float16, set_float16 => ElementType::Float16, "Float16";
2003    get_float32, set_float32 => ElementType::Float32, "Float32";
2004    get_float64, set_float64 => ElementType::Float64, "Float64";
2005    get_bigint64, set_bigint64 => ElementType::BigInt64, "BigInt64";
2006    get_biguint64, set_biguint64 => ElementType::BigUint64, "BigUint64";
2007}
2008
2009/// Install `DataView` and its prototype.
2010pub fn install_data_view(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
2011    let proto = interp.new_object(Some(object_proto.clone()));
2012    let constructor = interp.new_native_ctor("DataView", 1, data_view_constructor);
2013    constructor.define(
2014        "prototype",
2015        Property::prototype_of(Value::Object(proto.clone()), false),
2016    );
2017    proto.define(
2018        "constructor",
2019        Property {
2020            value: Some(Value::Object(constructor.clone())),
2021            writable: true,
2022            enumerable: false,
2023            configurable: true,
2024            ..Property::default()
2025        },
2026    );
2027    for (name, getter) in [
2028        ("buffer", data_view_buffer as crate::object::NativeFn),
2029        ("byteOffset", data_view_byte_offset),
2030        ("byteLength", data_view_byte_length),
2031    ] {
2032        let function = interp.new_native(format!("get {name}"), 0, getter);
2033        proto.define(
2034            name,
2035            Property {
2036                getter: Some(Value::Object(function)),
2037                enumerable: false,
2038                configurable: true,
2039                ..Property::default()
2040            },
2041        );
2042    }
2043    for (name, length, body) in DATA_VIEW_METHODS {
2044        define_method(&proto, name, *length, *body, interp);
2045    }
2046    interp.realm.data_view_proto = Some(proto.clone());
2047    let global = interp.realm.global.clone();
2048    global.define(
2049        "DataView",
2050        Property::with_attributes(Value::Object(constructor), true, false),
2051    );
2052    install_tag(&proto, "DataView", interp);
2053}
2054
2055/// The receiver as `(buffer, offset, length)`, refusing anything that is not a live view.
2056///
2057/// A detached buffer is a `TypeError` from every accessor and every property read, which is
2058/// what `MakeDataViewWithBufferWitnessRecord`'s `IsDetachedBuffer` check amounts to.
2059fn data_view_parts(
2060    interp: &mut Interp<'_>,
2061    this: &Value,
2062) -> JsResult<(Gc<JsObject>, usize, usize)> {
2063    let Some(object) = this.as_object() else {
2064        return Err(interp.type_error("not a DataView"));
2065    };
2066    let Some(parts) = object.data_view_parts() else {
2067        return Err(interp.type_error("not a DataView"));
2068    };
2069    Ok(parts)
2070}
2071
2072/// Whether this view's buffer has been detached.
2073fn data_view_is_detached(object: &Gc<JsObject>) -> bool {
2074    object
2075        .data_view_parts()
2076        .and_then(|(buffer, _, _)| buffer.array_buffer_storage())
2077        .is_some_and(|storage| storage.borrow().detached)
2078}
2079
2080fn data_view_buffer(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2081    let (buffer, _, _) = data_view_parts(interp, &this)?;
2082    Ok(Value::Object(buffer))
2083}
2084
2085fn data_view_byte_offset(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2086    let (_, offset, _) = data_view_parts(interp, &this)?;
2087    // A detached view is zero-length, so its offset is 0 as well.
2088    let detached = this.as_object().is_some_and(data_view_is_detached);
2089    Ok(Value::Int(if detached { 0 } else { offset as i32 }))
2090}
2091
2092fn data_view_byte_length(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
2093    let (_, _, length) = data_view_parts(interp, &this)?;
2094    // A detached buffer has no bytes left, so the view reports 0 rather than throwing.
2095    let detached = this.as_object().is_some_and(data_view_is_detached);
2096    Ok(Value::Int(if detached { 0 } else { length as i32 }))
2097}
2098
2099/// `dv.getInt32(byteOffset, littleEndian)` and siblings.
2100fn data_view_get(
2101    interp: &mut Interp<'_>,
2102    this: &Value,
2103    args: &[Value],
2104    element: ElementType,
2105) -> JsResult<Value> {
2106    let (buffer, offset, length) = data_view_parts(interp, this)?;
2107    // `ToIndex(byteOffset)` runs before the detached check, so a `valueOf` that detaches
2108    // still runs and an `Infinity` offset is a `RangeError` either way.
2109    // `GetViewByteLength` then bounds the access.
2110    let byte_offset = to_index(interp, &arg(args, 0), "byte offset")?;
2111    if data_view_is_detached(
2112        this.as_object()
2113            .ok_or_else(|| interp.type_error("not a DataView"))?,
2114    ) {
2115        return Err(interp.type_error("the buffer is detached"));
2116    }
2117    let size = element.size();
2118    if byte_offset + size > length {
2119        return Err(interp.range_error("byte offset is out of range"));
2120    }
2121    let little_endian = arg(args, 1).to_boolean();
2122    let storage = buffer
2123        .array_buffer_storage()
2124        .ok_or_else(|| interp.type_error("not a DataView"))?;
2125    let storage = storage.borrow();
2126    let start = offset + byte_offset;
2127    // A `DataView` defaults to *big*-endian while the element types read little-endian, so
2128    // the bytes are reversed into a scratch buffer first. One-byte widths are unaffected.
2129    let mut scratch = [0u8; 8];
2130    let raw = &storage.bytes[start..start + size];
2131    if little_endian {
2132        scratch[..size].copy_from_slice(raw);
2133    } else {
2134        for (slot, byte) in scratch[..size].iter_mut().zip(raw.iter().rev()) {
2135            *slot = *byte;
2136        }
2137    }
2138    Ok(element.read(buffer.heap(), &scratch, 0))
2139}
2140
2141/// `dv.setInt32(byteOffset, value, littleEndian)` and siblings.
2142fn data_view_set(
2143    interp: &mut Interp<'_>,
2144    this: &Value,
2145    args: &[Value],
2146    element: ElementType,
2147) -> JsResult<Value> {
2148    let (buffer, offset, length) = data_view_parts(interp, this)?;
2149    // Same order as `data_view_get`: `ToIndex` first, then the detached check.
2150    let byte_offset = to_index(interp, &arg(args, 0), "byte offset")?;
2151    if data_view_is_detached(
2152        this.as_object()
2153            .ok_or_else(|| interp.type_error("not a DataView"))?,
2154    ) {
2155        return Err(interp.type_error("the buffer is detached"));
2156    }
2157    let size = element.size();
2158    if byte_offset + size > length {
2159        return Err(interp.range_error("byte offset is out of range"));
2160    }
2161    let little_endian = arg(args, 2).to_boolean();
2162    // The value conversion runs before the buffer is borrowed, for the same reason
2163    // `write_element` does it: `valueOf` is script and can reach back into this buffer.
2164    let stored = interp.element_value(element, arg(args, 1))?;
2165    // Little-endian first, into scratch, so the conversion (wrap, clamp, or BigInt modulo)
2166    // runs before any byte is reversed.
2167    let mut scratch = [0u8; 8];
2168    element
2169        .write(&mut scratch, 0, &stored)
2170        .map_err(|reason| interp.type_error(reason))?;
2171    let storage = buffer
2172        .array_buffer_storage()
2173        .ok_or_else(|| interp.type_error("not a DataView"))?;
2174    let mut storage = storage.borrow_mut();
2175    let start = offset + byte_offset;
2176    let target = &mut storage.bytes[start..start + size];
2177    if little_endian {
2178        target.copy_from_slice(&scratch[..size]);
2179    } else {
2180        for (slot, byte) in target.iter_mut().zip(scratch[..size].iter().rev()) {
2181            *slot = *byte;
2182        }
2183    }
2184    Ok(Value::Undefined)
2185}
2186
2187/// `new DataView(buffer, byteOffset, byteLength)`.
2188///
2189/// The step order is observable and follows 25.3.2.1 exactly: `ToIndex(byteOffset)` runs
2190/// *before* the detached-buffer check, so a `valueOf` that detaches is still called, and the
2191/// detached check is repeated after the prototype lookup because
2192/// `OrdinaryCreateFromConstructor` can run a getter that detaches.
2193fn data_view_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
2194    // Called as a function rather than with `new`: there is no instance to build.
2195    let _ = &this;
2196    if !interp.is_constructing() {
2197        return Err(interp.type_error("Constructor DataView requires 'new'"));
2198    }
2199    let Some(buffer) = arg(args, 0).as_object().cloned() else {
2200        return Err(interp.type_error("first argument to DataView must be an ArrayBuffer"));
2201    };
2202    if buffer.array_buffer_storage().is_none() {
2203        return Err(interp.type_error("first argument to DataView must be an ArrayBuffer"));
2204    }
2205    // Step 5 before step 6.
2206    let offset = to_index(interp, &arg(args, 1), "byte offset")?;
2207    let detached = |buffer: &Gc<JsObject>| {
2208        buffer
2209            .array_buffer_storage()
2210            .is_some_and(|storage| storage.borrow().detached)
2211    };
2212    if detached(&buffer) {
2213        return Err(interp.type_error("the buffer is detached"));
2214    }
2215    let total = buffer
2216        .array_buffer_storage()
2217        .map(|storage| storage.borrow().bytes.len())
2218        .unwrap_or(0);
2219    if offset > total {
2220        return Err(interp.range_error("byte offset is out of range"));
2221    }
2222    let length = match args.get(2) {
2223        // An absent or explicit `undefined` length means "the rest of the buffer".
2224        None | Some(Value::Undefined) => total - offset,
2225        Some(_) => {
2226            let requested = to_index(interp, &arg(args, 2), "byte length")?;
2227            if requested > total - offset {
2228                return Err(interp.range_error("byte length is out of range"));
2229            }
2230            requested
2231        }
2232    };
2233    // The prototype lookup already happened — the engine builds `this` from
2234    // `new.target.prototype` — but a getter there may have detached the buffer, so the
2235    // check is repeated.
2236    if detached(&buffer) {
2237        return Err(interp.type_error("the buffer is detached"));
2238    }
2239    // `OrdinaryCreateFromConstructor` last, so a throwing `new.target.prototype` getter is
2240    // never reached for arguments that are already refused.
2241    let proto = interp
2242        .realm
2243        .data_view_proto
2244        .clone()
2245        .unwrap_or_else(|| interp.realm.object_proto.clone());
2246    let instance = interp.new_ctor_instance(proto)?;
2247    instance.set_data_view(buffer, offset, length);
2248    Ok(Value::Object(instance))
2249}