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