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};
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}
67
68/// The view types, in the order their prototypes are installed.
69pub const ELEMENT_TYPES: [(ElementType, &str); 10] = [
70    (ElementType::Int8, "Int8Array"),
71    (ElementType::Uint8, "Uint8Array"),
72    (ElementType::Uint8Clamped, "Uint8ClampedArray"),
73    (ElementType::Int16, "Int16Array"),
74    (ElementType::Uint16, "Uint16Array"),
75    (ElementType::Int32, "Int32Array"),
76    (ElementType::Uint32, "Uint32Array"),
77    (ElementType::Float16, "Float16Array"),
78    (ElementType::Float32, "Float32Array"),
79    (ElementType::Float64, "Float64Array"),
80];
81
82impl ElementType {
83    /// Bytes per element.
84    pub fn size(self) -> usize {
85        match self {
86            ElementType::Int8 | ElementType::Uint8 | ElementType::Uint8Clamped => 1,
87            ElementType::Int16 | ElementType::Uint16 | ElementType::Float16 => 2,
88            ElementType::Int32 | ElementType::Uint32 | ElementType::Float32 => 4,
89            ElementType::Float64 => 8,
90        }
91    }
92
93    /// The name, as `Symbol.toStringTag` and the class tag report it.
94    pub fn name(self) -> &'static str {
95        ELEMENT_TYPES
96            .into_iter()
97            .find(|(kind, _)| *kind == self)
98            .map(|(_, name)| name)
99            .unwrap_or("TypedArray")
100    }
101
102    /// Read the element at `offset`.
103    ///
104    /// A short buffer — only reachable if a view was built over a truncated one — reads as
105    /// `0` rather than panicking, because a script must not be able to make the engine abort.
106    pub fn read(self, bytes: &[u8], offset: usize) -> Value {
107        let slice = bytes.get(offset..offset + self.size());
108        let Some(slice) = slice else {
109            return Value::Int(0);
110        };
111        match self {
112            ElementType::Int8 => Value::Int(slice[0] as i8 as i32),
113            ElementType::Uint8 | ElementType::Uint8Clamped => Value::Int(slice[0] as i32),
114            ElementType::Int16 => Value::Int(i16::from_le_bytes([slice[0], slice[1]]) as i32),
115            ElementType::Uint16 => Value::Int(u16::from_le_bytes([slice[0], slice[1]]) as i32),
116            ElementType::Int32 => {
117                Value::Int(i32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
118            }
119            // An unsigned 32-bit value does not fit `i32`, so it becomes a float. The
120            // reference keeps it a number too, and the value is exact in an `f64`.
121            ElementType::Uint32 => {
122                Value::Float(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as f64)
123            }
124            ElementType::Float16 => {
125                Value::Float(f16_to_f64(u16::from_le_bytes([slice[0], slice[1]])))
126            }
127            ElementType::Float32 => {
128                Value::Float(f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as f64)
129            }
130            ElementType::Float64 => Value::Float(f64::from_le_bytes([
131                slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
132            ])),
133        }
134    }
135
136    /// Store `value` into the element at `offset`.
137    pub fn write(self, bytes: &mut [u8], offset: usize, value: Value) {
138        let size = self.size();
139        if offset + size > bytes.len() {
140            return;
141        }
142        let number = value.to_number();
143        let slice = &mut bytes[offset..offset + size];
144        match self {
145            ElementType::Int8 => slice[0] = to_integer(number) as i8 as u8,
146            ElementType::Uint8 => slice[0] = to_integer(number) as u8,
147            ElementType::Uint8Clamped => slice[0] = clamp_to_uint8(number),
148            ElementType::Int16 => slice.copy_from_slice(&(to_integer(number) as i16).to_le_bytes()),
149            ElementType::Uint16 => {
150                slice.copy_from_slice(&(to_integer(number) as u16).to_le_bytes())
151            }
152            ElementType::Int32 => slice.copy_from_slice(&(to_integer(number) as i32).to_le_bytes()),
153            ElementType::Uint32 => {
154                slice.copy_from_slice(&(to_integer(number) as u32).to_le_bytes())
155            }
156            ElementType::Float16 => slice.copy_from_slice(&f64_to_f16(number).to_le_bytes()),
157            ElementType::Float32 => slice.copy_from_slice(&(number as f32).to_le_bytes()),
158            ElementType::Float64 => slice.copy_from_slice(&number.to_le_bytes()),
159        }
160    }
161}
162
163/// `ToIntegerOrInfinity`, truncated toward zero, as the integer element types need it.
164///
165/// A cast through `i64` would be undefined for out-of-range floats in Rust (`as` saturates
166/// since 1.45, which is the behaviour wanted here anyway), so the wrap happens at the target
167/// width — `as i8` and friends keep the low bits, which is exactly the spec's modulo.
168fn to_integer(number: f64) -> i64 {
169    if number.is_nan() {
170        return 0;
171    }
172    if number.is_infinite() {
173        // The modulo of an infinity is 0 in every engine; the alternative is to wrap the
174        // saturated value, which no script expects.
175        return 0;
176    }
177    number.trunc() as i64
178}
179
180/// `ToUint8Clamp`: round half to even, then clamp into `0..=255`.
181fn clamp_to_uint8(number: f64) -> u8 {
182    if number.is_nan() || number <= 0.0 {
183        return 0;
184    }
185    if number >= 255.0 {
186        return 255;
187    }
188    // `round_ties_even` is what the spec asks for; `0.5` must land on `0`, not `1`.
189    let rounded = number.round_ties_even();
190    rounded as u8
191}
192
193/// Decode an IEEE-754 binary16 value.
194fn f16_to_f64(bits: u16) -> f64 {
195    let sign = if bits & 0x8000 == 0 { 1.0 } else { -1.0 };
196    let exponent = ((bits >> 10) & 0x1f) as i32;
197    let mantissa = (bits & 0x3ff) as f64;
198    if exponent == 0 {
199        // Zero or subnormal: no implicit leading bit, and the scale is the smallest one.
200        sign * mantissa * 2f64.powi(-24)
201    } else if exponent == 0x1f {
202        if mantissa == 0.0 {
203            sign * f64::INFINITY
204        } else {
205            f64::NAN
206        }
207    } else {
208        sign * (1.0 + mantissa / 1024.0) * 2f64.powi(exponent - 15)
209    }
210}
211
212/// Encode a value as IEEE-754 binary16, rounding to nearest even.
213fn f64_to_f16(value: f64) -> u16 {
214    if value.is_nan() {
215        return 0x7e00;
216    }
217    let sign = if value.is_sign_negative() {
218        0x8000u16
219    } else {
220        0
221    };
222    let magnitude = value.abs();
223    if magnitude == 0.0 {
224        return sign;
225    }
226    if magnitude >= 65504.0 {
227        return sign | 0x7c00; // infinity
228    }
229    if magnitude < 6.103_515_625e-5 {
230        // Subnormal: the mantissa counts in units of 2^-24, rounded to nearest even.
231        let scaled = magnitude / 2f64.powi(-24);
232        let mantissa = scaled.round_ties_even();
233        return sign | (mantissa as u16);
234    }
235    // Normal: 1.m × 2^(e-15), so the exponent field is e + 15 and the mantissa keeps 10 bits.
236    let exponent = magnitude.log2().floor() as i32;
237    let biased = exponent + 15;
238    let mantissa = (magnitude / 2f64.powi(exponent) - 1.0) * 1024.0;
239    let rounded = mantissa.round_ties_even();
240    if rounded >= 1024.0 {
241        // Rounding carried into the exponent.
242        let biased = biased + 1;
243        if biased >= 0x1f {
244            return sign | 0x7c00;
245        }
246        return sign | ((biased as u16) << 10);
247    }
248    sign | ((biased as u16) << 10) | (rounded as u16)
249}
250
251/// Install `ArrayBuffer` and every typed-array view.
252pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
253    install_array_buffer(interp, object_proto);
254    install_views(interp, object_proto);
255}
256
257fn install_array_buffer(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
258    let proto = interp.new_object(Some(object_proto.clone()));
259    let constructor = interp.new_native("ArrayBuffer", 1, buffer_constructor);
260    constructor.define(
261        "prototype",
262        Property::with_attributes(Value::Object(proto.clone()), false, false),
263    );
264    proto.define(
265        "constructor",
266        Property::with_attributes(Value::Object(constructor.clone()), true, false),
267    );
268    define_method(&proto, "transfer", 0, buffer_transfer, interp);
269    define_method(&proto, "slice", 2, buffer_slice, interp);
270    // `byteLength` is an accessor so a detached buffer reports `0` instead of a stale size.
271    let getter = interp.new_native("get byteLength", 0, buffer_byte_length);
272    proto.define(
273        "byteLength",
274        Property {
275            getter: Some(Value::Object(getter)),
276            enumerable: false,
277            configurable: true,
278            ..Property::default()
279        },
280    );
281    install_tag(&proto, "ArrayBuffer", interp);
282    interp.realm.array_buffer_proto = Some(proto);
283    let global = interp.realm.global.clone();
284    global.define(
285        "ArrayBuffer",
286        Property::with_attributes(Value::Object(constructor), true, false),
287    );
288}
289
290fn install_views(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
291    // One shared prototype carries every method and every accessor; each element type gets a
292    // prototype of its own on top of it, which is what lets `BYTES_PER_ELEMENT` and the
293    // string tag differ per type while the behaviour is written once.
294    let shared = interp.new_object(Some(object_proto.clone()));
295    define_method(&shared, "set", 1, set_from, interp);
296    define_method(&shared, "fill", 1, fill, interp);
297    define_method(&shared, "join", 1, join, interp);
298    define_method(&shared, "toString", 0, join, interp);
299    define_method(&shared, "slice", 2, slice, interp);
300    define_method(&shared, "subarray", 2, subarray, interp);
301    for (name, getter) in [
302        ("buffer", buffer_of as crate::object::NativeFn),
303        ("byteOffset", byte_offset_of),
304        ("byteLength", byte_length_of),
305        ("length", length_of),
306        ("[Symbol.toStringTag]", tag_of),
307    ] {
308        let function = interp.new_native(name, 0, getter);
309        let key = if name == "[Symbol.toStringTag]" {
310            interp
311                .realm
312                .well_known_key(crate::interp::WellKnown::ToStringTag)
313        } else {
314            crate::object::PropertyKey::from(name)
315        };
316        shared.define_key(
317            &key,
318            Property {
319                getter: Some(Value::Object(function)),
320                enumerable: false,
321                configurable: true,
322                ..Property::default()
323            },
324        );
325    }
326    interp.realm.typed_array_proto = Some(shared.clone());
327
328    let global = interp.realm.global.clone();
329    for (element, name) in ELEMENT_TYPES {
330        let proto = interp.new_object(Some(shared.clone()));
331        // The constructor reads the element type off this, so `new` is the only way in.
332        proto.define(
333            "_element",
334            Property::with_attributes(Value::Int(element as i32), false, false),
335        );
336        proto.define(
337            "BYTES_PER_ELEMENT",
338            Property::with_attributes(Value::Int(element.size() as i32), false, false),
339        );
340        let constructor = interp.new_native(name, 3, view_constructor);
341        constructor.define(
342            "_element",
343            Property::with_attributes(Value::Int(element as i32), false, false),
344        );
345        constructor.define(
346            "BYTES_PER_ELEMENT",
347            Property::with_attributes(Value::Int(element.size() as i32), false, false),
348        );
349        constructor.define(
350            "prototype",
351            Property::with_attributes(Value::Object(proto.clone()), false, false),
352        );
353        proto.define(
354            "constructor",
355            Property::with_attributes(Value::Object(constructor.clone()), true, false),
356        );
357        global.define(
358            name,
359            Property::with_attributes(Value::Object(constructor), true, false),
360        );
361    }
362}
363
364fn install_tag(proto: &Gc<JsObject>, _tag: &str, interp: &Interp<'_>) {
365    let function = interp.new_native("[Symbol.toStringTag]", 0, buffer_tag);
366    proto.define_key(
367        &interp
368            .realm
369            .well_known_key(crate::interp::WellKnown::ToStringTag),
370        Property {
371            getter: Some(Value::Object(function)),
372            enumerable: false,
373            configurable: true,
374            ..Property::default()
375        },
376    );
377}
378
379/// `ArrayBuffer.prototype[Symbol.toStringTag]`.
380fn buffer_tag(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
381    Ok(interp.string("ArrayBuffer"))
382}
383
384/// `new ArrayBuffer(length)`.
385fn buffer_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
386    let length = arg(args, 0).to_number();
387    if length < 0.0 || length.fract() != 0.0 || length > 4294967295.0 {
388        return Err(interp.range_error("invalid array buffer length"));
389    }
390    let storage = Rc::new(RefCell::new(BufferStorage {
391        bytes: vec![0; length as usize],
392        detached: false,
393    }));
394    let object = match this.as_object() {
395        Some(object) => object.clone(),
396        None => {
397            let proto = interp
398                .realm
399                .array_buffer_proto
400                .clone()
401                .unwrap_or_else(|| interp.realm.object_proto.clone());
402            interp.new_object(Some(proto))
403        }
404    };
405    object.set_array_buffer(storage);
406    Ok(Value::Object(object))
407}
408
409/// The storage of `this`, which must be an `ArrayBuffer`.
410fn buffer_storage_of(interp: &Interp<'_>, this: &Value) -> JsResult<Rc<RefCell<BufferStorage>>> {
411    this.as_object()
412        .and_then(|object| object.array_buffer_storage())
413        .ok_or_else(|| interp.type_error("not an ArrayBuffer"))
414}
415
416/// `ArrayBuffer.prototype.byteLength`.
417fn buffer_byte_length(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
418    let storage = buffer_storage_of(interp, &this)?;
419    let storage = storage.borrow();
420    Ok(Value::Int(if storage.detached {
421        0
422    } else {
423        storage.bytes.len() as i32
424    }))
425}
426
427/// `Buffer.prototype.transfer()`: hand the bytes to a new buffer and detach this one.
428fn buffer_transfer(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
429    let storage = buffer_storage_of(interp, &this)?;
430    let bytes = {
431        let mut storage = storage.borrow_mut();
432        if storage.detached {
433            return Err(interp.type_error("ArrayBuffer has already been detached"));
434        }
435        storage.detached = true;
436        std::mem::take(&mut storage.bytes)
437    };
438    let fresh_storage = Rc::new(RefCell::new(BufferStorage {
439        bytes,
440        detached: false,
441    }));
442    let proto = interp
443        .realm
444        .array_buffer_proto
445        .clone()
446        .unwrap_or_else(|| interp.realm.object_proto.clone());
447    let object = interp.new_object(Some(proto));
448    object.set_array_buffer(fresh_storage);
449    Ok(Value::Object(object))
450}
451
452/// `buffer.slice(begin, end)`: a copy, which is what keeps the two independent.
453fn buffer_slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
454    let storage = buffer_storage_of(interp, &this)?;
455    let storage = storage.borrow();
456    if storage.detached {
457        return Err(interp.type_error("ArrayBuffer has already been detached"));
458    }
459    let length = storage.bytes.len() as i64;
460    let begin = clamp_index(arg(args, 0).to_number(), length, 0);
461    let end = clamp_index(arg(args, 1).to_number(), length, length);
462    let bytes = storage.bytes[begin as usize..end.max(begin) as usize].to_vec();
463    drop(storage);
464    let proto = interp
465        .realm
466        .array_buffer_proto
467        .clone()
468        .unwrap_or_else(|| interp.realm.object_proto.clone());
469    let object = interp.new_object(Some(proto));
470    object.set_array_buffer(Rc::new(RefCell::new(BufferStorage {
471        bytes,
472        detached: false,
473    })));
474    Ok(Value::Object(object))
475}
476
477/// Resolve a `begin`/`end` argument the way every slice does: relative to the end when
478/// negative, then clamped into range.
479fn clamp_index(value: f64, length: i64, default: i64) -> i64 {
480    if value.is_nan() {
481        return default.min(length).max(0);
482    }
483    let value = if value.is_infinite() {
484        if value > 0.0 { length } else { 0 }
485    } else {
486        value.trunc() as i64
487    };
488    (if value < 0 { length + value } else { value }).clamp(0, length)
489}
490
491/// `ToIndex`: `undefined` and `NaN` are `0`, a negative or infinite value is a
492/// `RangeError`, and so is a fraction rather than being truncated.
493///
494/// This is what makes `new Uint8Array(buffer)` mean "from byte 0, to the end": the missing
495/// second argument is `undefined`, which is `0`, and a `NaN` offset must not be a failure.
496fn to_index(interp: &Interp<'_>, value: &Value, what: &str) -> JsResult<usize> {
497    let number = value.to_number();
498    if number.is_nan() {
499        return Ok(0);
500    }
501    if number < 0.0 || number.is_infinite() || number.fract() != 0.0 {
502        return Err(interp.range_error(format!("invalid {what}")));
503    }
504    Ok(number as usize)
505}
506
507/// The element type this call belongs to, read off the receiver's prototype.
508///
509/// Not off the callee: a native call does not push a frame, so `current_callee` reports
510/// whatever the *enclosing* bytecode frame was called with. The prototype is reliable —
511/// `new` builds the object from `callee.prototype` — and it is what decides the type anyway.
512fn element_of_receiver(interp: &Interp<'_>, this: &Value) -> Option<ElementType> {
513    let object = this.as_object()?;
514    let mut proto = object.proto();
515    // Walk the chain so a subclass of a typed array still finds the type.
516    while let Some(current) = proto {
517        if let Some(raw) = current
518            .own_property("_element")
519            .and_then(|property| property.value)
520        {
521            let raw = raw.to_number() as i32;
522            return ELEMENT_TYPES
523                .into_iter()
524                .map(|(element, _)| element)
525                .find(|element| *element as i32 == raw);
526        }
527        proto = current.proto();
528    }
529    let _ = interp;
530    None
531}
532
533/// `new Uint8Array(...)`: from a length, from a buffer, or from an array-like.
534fn view_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
535    // A typed-array constructor cannot be called as a function: there is no receiver to
536    // take an element type from, and the spec makes that a `TypeError`.
537    let element = element_of_receiver(interp, &this)
538        .ok_or_else(|| interp.type_error("constructor requires 'new'"))?;
539    let first = arg(args, 0);
540    let (buffer, offset, length) = match &first {
541        // `new X(buffer, byteOffset, length)`: a window onto existing bytes.
542        Value::Object(object) if object.array_buffer_storage().is_some() => {
543            let storage = object
544                .array_buffer_storage()
545                .expect("checked by the guard above");
546            let total = storage.borrow().bytes.len();
547            let byte_offset = to_index(interp, &arg(args, 1), "byte offset")?;
548            if byte_offset % element.size() != 0 {
549                return Err(interp.range_error("byte offset is not aligned"));
550            }
551            if byte_offset > total {
552                return Err(interp.range_error("byte offset is out of range"));
553            }
554            let available = (total - byte_offset) / element.size();
555            // No third argument means "the rest of the buffer", which is different from
556            // `undefined` meaning 0 — hence a length check rather than a nullish one.
557            let length = if args.len() < 3 || matches!(arg(args, 2), Value::Undefined) {
558                available
559            } else {
560                let requested = to_index(interp, &arg(args, 2), "length")?;
561                if requested > available {
562                    return Err(interp.range_error("invalid length"));
563                }
564                requested
565            };
566            (object.clone(), byte_offset, length)
567        }
568        // `new X(length)`
569        Value::Int(_) | Value::Float(_) => {
570            let count = to_index(interp, &first, "typed array length")?;
571            let proto = interp
572                .realm
573                .array_buffer_proto
574                .clone()
575                .unwrap_or_else(|| interp.realm.object_proto.clone());
576            let buffer = interp.new_object(Some(proto));
577            buffer.set_array_buffer(Rc::new(RefCell::new(BufferStorage {
578                bytes: vec![0; count * element.size()],
579                detached: false,
580            })));
581            (buffer, 0, count)
582        }
583        // `new X(iterable)`: a buffer sized by the source, filled from it.
584        _ => {
585            let values = interp.array_like_to_args(&first)?;
586            let proto = interp
587                .realm
588                .array_buffer_proto
589                .clone()
590                .unwrap_or_else(|| interp.realm.object_proto.clone());
591            let buffer = interp.new_object(Some(proto));
592            let storage = Rc::new(RefCell::new(BufferStorage {
593                bytes: vec![0; values.len() * element.size()],
594                detached: false,
595            }));
596            buffer.set_array_buffer(storage);
597            let count = values.len();
598            for (index, value) in values.into_iter().enumerate() {
599                write_element(&buffer, element, 0, index, value);
600            }
601            (buffer, 0, count)
602        }
603    };
604    let object = match this.as_object() {
605        Some(object) => object.clone(),
606        None => {
607            let proto = interp
608                .realm
609                .typed_array_proto
610                .clone()
611                .unwrap_or_else(|| interp.realm.object_proto.clone());
612            interp.new_object(Some(proto))
613        }
614    };
615    object.set_typed_array(buffer, element, offset, length);
616    Ok(Value::Object(object))
617}
618
619/// Write one element through a buffer, for the paths that do not have a view in hand.
620fn write_element(
621    buffer: &Gc<JsObject>,
622    element: ElementType,
623    offset: usize,
624    index: usize,
625    value: Value,
626) {
627    let Some(storage) = buffer.array_buffer_storage() else {
628        return;
629    };
630    let mut storage = storage.borrow_mut();
631    if storage.detached {
632        return;
633    }
634    element.write(&mut storage.bytes, offset + index * element.size(), value);
635}
636
637/// Read the elements of a typed array, which `join`/`set`/`slice` all need.
638fn elements_of(interp: &Interp<'_>, this: &Value) -> JsResult<Vec<Value>> {
639    let object = this
640        .as_object()
641        .ok_or_else(|| interp.type_error("not a typed array"))?;
642    let Some(length) = object.typed_array_length() else {
643        return Err(interp.type_error("not a typed array"));
644    };
645    Ok((0..length)
646        .map(|index| {
647            object
648                .typed_array_element(index)
649                .unwrap_or(Value::Undefined)
650        })
651        .collect())
652}
653
654/// `a.join(separator)`; `toString` shares it, which is what `Array.prototype.toString` does.
655fn join(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
656    let separator = match arg(args, 0) {
657        Value::Undefined => ",".to_string(),
658        other => interp.to_js_string(&other)?,
659    };
660    let elements = elements_of(interp, &this)?;
661    let mut parts = Vec::with_capacity(elements.len());
662    for element in elements {
663        parts.push(match element {
664            Value::Undefined | Value::Null => String::new(),
665            other => interp.to_js_string(&other)?,
666        });
667    }
668    Ok(interp.string(parts.join(&separator)))
669}
670
671/// `a.set(source, offset)`.
672fn set_from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
673    let object = this
674        .as_object()
675        .ok_or_else(|| interp.type_error("not a typed array"))?;
676    let Some(length) = object.typed_array_length() else {
677        return Err(interp.type_error("not a typed array"));
678    };
679    let offset = to_index(interp, &arg(args, 1), "offset")?;
680    let values = interp.array_like_to_args(&arg(args, 0))?;
681    if offset + values.len() > length {
682        return Err(interp.range_error("source is too large"));
683    }
684    // Read every value first, so `a.set(a)` — a self-copy — sees the original contents
685    // rather than a half-overwritten array.
686    for (index, value) in values.into_iter().enumerate() {
687        if let Some(element) = object.typed_array_element_type() {
688            let (buffer, base) = object
689                .typed_array_parts()
690                .map(|(buffer, _, base, _)| (buffer, base))
691                .expect("a typed array has parts");
692            write_element(&buffer, element, base, offset + index, value);
693        }
694    }
695    Ok(Value::Undefined)
696}
697
698/// `a.fill(value, start, end)`.
699fn fill(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
700    let object = this
701        .as_object()
702        .ok_or_else(|| interp.type_error("not a typed array"))?
703        .clone();
704    let Some(length) = object.typed_array_length() else {
705        return Err(interp.type_error("not a typed array"));
706    };
707    let value = arg(args, 0);
708    let length_i = length as i64;
709    let start = clamp_index(
710        match args.get(1) {
711            None => 0.0,
712            Some(value) => value.to_number(),
713        },
714        length_i,
715        0,
716    );
717    let end = clamp_index(
718        match args.get(2) {
719            None => length as f64,
720            Some(value) => value.to_number(),
721        },
722        length_i,
723        length_i,
724    );
725    let Some(element) = object.typed_array_element_type() else {
726        return Err(interp.type_error("not a typed array"));
727    };
728    let (buffer, base) = object
729        .typed_array_parts()
730        .map(|(buffer, _, base, _)| (buffer, base))
731        .expect("a typed array has parts");
732    for index in start as usize..end.max(start) as usize {
733        write_element(&buffer, element, base, index, value.clone());
734    }
735    Ok(Value::Object(object))
736}
737
738/// `a.slice(begin, end)`: a new view with a buffer of its own.
739fn slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
740    let object = this
741        .as_object()
742        .ok_or_else(|| interp.type_error("not a typed array"))?;
743    let Some(length) = object.typed_array_length() else {
744        return Err(interp.type_error("not a typed array"));
745    };
746    let Some(element) = object.typed_array_element_type() else {
747        return Err(interp.type_error("not a typed array"));
748    };
749    let length_i = length as i64;
750    let begin = clamp_index(arg(args, 0).to_number(), length_i, 0);
751    let end = clamp_index(
752        match args.get(1) {
753            None => length as f64,
754            Some(value) => value.to_number(),
755        },
756        length_i,
757        length_i,
758    );
759    let count = (end - begin).max(0) as usize;
760    let proto = interp
761        .realm
762        .array_buffer_proto
763        .clone()
764        .unwrap_or_else(|| interp.realm.object_proto.clone());
765    let buffer = interp.new_object(Some(proto));
766    buffer.set_array_buffer(Rc::new(RefCell::new(BufferStorage {
767        bytes: vec![0; count * element.size()],
768        detached: false,
769    })));
770    for index in 0..count {
771        if let Some(value) = object.typed_array_element(begin as usize + index) {
772            write_element(&buffer, element, 0, index, value);
773        }
774    }
775    let fresh = interp.new_object(Some(
776        interp
777            .realm
778            .typed_array_proto
779            .clone()
780            .unwrap_or_else(|| interp.realm.object_proto.clone()),
781    ));
782    fresh.set_typed_array(buffer, element, 0, count);
783    Ok(Value::Object(fresh))
784}
785
786/// `a.subarray(begin, end)`: a view over the *same* buffer.
787fn subarray(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
788    let object = this
789        .as_object()
790        .ok_or_else(|| interp.type_error("not a typed array"))?;
791    let Some((buffer, element, base, length)) = object.typed_array_parts() else {
792        return Err(interp.type_error("not a typed array"));
793    };
794    let length_i = length as i64;
795    let begin = clamp_index(arg(args, 0).to_number(), length_i, 0);
796    let end = clamp_index(
797        match args.get(1) {
798            None => length as f64,
799            Some(value) => value.to_number(),
800        },
801        length_i,
802        length_i,
803    );
804    let count = (end - begin).max(0) as usize;
805    let fresh = interp.new_object(Some(
806        interp
807            .realm
808            .typed_array_proto
809            .clone()
810            .unwrap_or_else(|| interp.realm.object_proto.clone()),
811    ));
812    fresh.set_typed_array(
813        buffer,
814        element,
815        base + begin as usize * element.size(),
816        count,
817    );
818    Ok(Value::Object(fresh))
819}
820
821/// The `buffer` accessor.
822fn buffer_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
823    let object = this
824        .as_object()
825        .ok_or_else(|| interp.type_error("not a typed array"))?;
826    object
827        .typed_array_parts()
828        .map(|(buffer, _, _, _)| Value::Object(buffer))
829        .ok_or_else(|| interp.type_error("not a typed array"))
830}
831
832/// The `byteOffset` accessor.
833fn byte_offset_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
834    let object = this
835        .as_object()
836        .ok_or_else(|| interp.type_error("not a typed array"))?;
837    object
838        .typed_array_parts()
839        .map(|(_, _, base, _)| Value::Int(base as i32))
840        .ok_or_else(|| interp.type_error("not a typed array"))
841}
842
843/// The `byteLength` accessor.
844fn byte_length_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
845    let object = this
846        .as_object()
847        .ok_or_else(|| interp.type_error("not a typed array"))?;
848    object
849        .typed_array_parts()
850        .map(|(_, element, _, length)| Value::Int((length * element.size()) as i32))
851        .ok_or_else(|| interp.type_error("not a typed array"))
852}
853
854/// The `length` accessor.
855fn length_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
856    let object = this
857        .as_object()
858        .ok_or_else(|| interp.type_error("not a typed array"))?;
859    object
860        .typed_array_length()
861        .map(|length| Value::Int(length as i32))
862        .ok_or_else(|| interp.type_error("not a typed array"))
863}
864
865/// The `Symbol.toStringTag` accessor, which names the element type.
866fn tag_of(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
867    let object = this
868        .as_object()
869        .ok_or_else(|| interp.type_error("not a typed array"))?;
870    let name = object
871        .typed_array_element_type()
872        .map(|element| element.name());
873    Ok(match name {
874        Some(name) => interp.string(name),
875        None => Value::Undefined,
876    })
877}