Skip to main content

quickjs/
builtins_typed.rs

1//! The typed-array assembly the C API needs: build a buffer, build a view over one, and
2//! translate between `JSTypedArrayEnum` and the engine's [`ElementType`].
3//!
4//! # Why this is not just "call the constructor"
5//!
6//! The engine's typed-array constructors are script functions that read their arguments and
7//! walk an iterable. A C caller that already *has* the bytes wants none of that: it wants a
8//! buffer with those bytes and a view covering all of them. Doing it through the constructor
9//! would mean building a `Value` array, which is more work and more ways to be wrong — and it
10//! would run a script-visible function for an operation that has no script equivalent.
11//!
12//! # Why the protos come from the realm
13//!
14//! A view has to be `instanceof Uint8Array`, so its prototype must be the realm's
15//! `Uint8Array.prototype` and its buffer's must be the realm's `ArrayBuffer.prototype`. The
16//! realm is where the intrinsics were installed, and reaching for it is what keeps
17//! `Object.getPrototypeOf(new Uint8Array(buf))` answering the constructor's prototype.
18
19use std::cell::RefCell;
20use std::rc::Rc;
21
22use engine::Value;
23use engine::builtins::typedarray::ElementType;
24use engine::interp::{Interp, JsResult, Signal};
25use engine::object::{BufferStorage, JsObject};
26use js_gc::Gc;
27
28use crate::buffers::typed_array_kind;
29
30/// `ElementType::Uint8`, named so that a caller does not have to spell the engine's path.
31pub const UINT8: ElementType = ElementType::Uint8;
32
33/// An `ArrayBuffer` holding `bytes`.
34pub fn new_array_buffer(interp: &mut Interp<'static>, bytes: Vec<u8>) -> Gc<JsObject> {
35    let proto = interp
36        .realm
37        .array_buffer_proto
38        .clone()
39        .unwrap_or_else(|| interp.realm.object_proto.clone());
40    let object = interp.new_object(Some(proto));
41    object.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed(bytes))));
42    object
43}
44
45/// [`new_array_buffer`] whose origin block is released when the buffer is collected.
46///
47/// The closure is the C API's `free_func`; the engine's `BufferStorage` runs it in `Drop`,
48/// which happens when the last handle to the buffer goes — the same moment the reference
49/// frees the block.
50pub fn new_array_buffer_with_release(
51    interp: &mut Interp<'static>,
52    bytes: Vec<u8>,
53    release: Box<dyn FnOnce()>,
54) -> Gc<JsObject> {
55    let proto = interp
56        .realm
57        .array_buffer_proto
58        .clone()
59        .unwrap_or_else(|| interp.realm.object_proto.clone());
60    let object = interp.new_object(Some(proto));
61    object.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed_with_release(
62        bytes, release,
63    ))));
64    object
65}
66
67/// A typed-array view of `element` over `buffer[offset .. offset + length]`.
68///
69/// The prototype is the realm's for that element type, which is what makes the view answer
70/// `instanceof` and inherit every method.
71pub fn new_view(
72    interp: &mut Interp<'static>,
73    buffer: &Gc<JsObject>,
74    element: ElementType,
75    offset: usize,
76    length: usize,
77) -> Gc<JsObject> {
78    // `typed_array_protos` is in `ELEMENT_TYPES` order, which is the only index the engine
79    // publishes for it; the position is looked up rather than assumed.
80    let index = engine::builtins::typedarray::ELEMENT_TYPES
81        .iter()
82        .position(|(kind, _)| *kind == element)
83        .unwrap_or(0);
84    let proto = interp
85        .realm
86        .typed_array_protos
87        .get(index)
88        .cloned()
89        .or_else(|| interp.realm.typed_array_proto.clone())
90        .unwrap_or_else(|| interp.realm.object_proto.clone());
91    let object = interp.new_object(Some(proto));
92    object.set_typed_array(buffer.clone(), element, offset, length);
93    object
94}
95
96/// `new Uint8Array(...)` and friends, from decoded arguments.
97///
98/// Three argument shapes, exactly as the constructor has them: a length, an iterable or
99/// array-like, or `(buffer, byteOffset, length)`. Rather than reimplement the distinctions,
100/// this calls the realm's constructor with the arguments C supplied — which is also what makes
101/// a wrong argument a `TypeError` from the same code a script would hit.
102pub fn construct_typed_array(
103    interp: &mut Interp<'static>,
104    element: ElementType,
105    args: Vec<Value>,
106) -> JsResult<Value> {
107    // The constructor is a global binding, so it is read from the global object rather than
108    // from a table: `Uint8Array` may legitimately have been replaced by a script.
109    let global = Value::Object(interp.realm.global.clone());
110    let Value::Object(constructor) = interp.read_field(&global, element.name())? else {
111        return Err(Signal::Throw(interp.make_error(
112            "TypeError",
113            &format!("{} is not installed", element.name()),
114        )));
115    };
116    let callee = Value::Object(constructor);
117    interp.construct(callee.clone(), callee, args)
118}
119
120/// The `JSTypedArrayEnum` value for `element`.
121pub fn kind_from_element(element: ElementType) -> i32 {
122    match element {
123        ElementType::Uint8Clamped => typed_array_kind::UINT8C,
124        ElementType::Int8 => typed_array_kind::INT8,
125        ElementType::Uint8 => typed_array_kind::UINT8,
126        ElementType::Int16 => typed_array_kind::INT16,
127        ElementType::Uint16 => typed_array_kind::UINT16,
128        ElementType::Int32 => typed_array_kind::INT32,
129        ElementType::Uint32 => typed_array_kind::UINT32,
130        ElementType::BigInt64 => typed_array_kind::BIG_INT64,
131        ElementType::BigUint64 => typed_array_kind::BIG_UINT64,
132        ElementType::Float16 => typed_array_kind::FLOAT16,
133        ElementType::Float32 => typed_array_kind::FLOAT32,
134        ElementType::Float64 => typed_array_kind::FLOAT64,
135    }
136}
137
138/// The engine element type for a `JSTypedArrayEnum` value, or `None` when out of range.
139pub fn element_from_kind(kind: i32) -> Option<ElementType> {
140    Some(match kind {
141        typed_array_kind::UINT8C => ElementType::Uint8Clamped,
142        typed_array_kind::INT8 => ElementType::Int8,
143        typed_array_kind::UINT8 => ElementType::Uint8,
144        typed_array_kind::INT16 => ElementType::Int16,
145        typed_array_kind::UINT16 => ElementType::Uint16,
146        typed_array_kind::INT32 => ElementType::Int32,
147        typed_array_kind::UINT32 => ElementType::Uint32,
148        typed_array_kind::BIG_INT64 => ElementType::BigInt64,
149        typed_array_kind::BIG_UINT64 => ElementType::BigUint64,
150        typed_array_kind::FLOAT16 => ElementType::Float16,
151        typed_array_kind::FLOAT32 => ElementType::Float32,
152        typed_array_kind::FLOAT64 => ElementType::Float64,
153        _ => return None,
154    })
155}