Skip to main content

quickjs/builtins/
typedarray.rs

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