Skip to main content

quickjs/builtins/
typedarray.rs

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