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