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