quickjs-capi 0.13.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
//! The typed-array assembly the C API needs: build a buffer, build a view over one, and
//! translate between `JSTypedArrayEnum` and the engine's [`ElementType`].
//!
//! # Why this is not just "call the constructor"
//!
//! The engine's typed-array constructors are script functions that read their arguments and
//! walk an iterable. A C caller that already *has* the bytes wants none of that: it wants a
//! buffer with those bytes and a view covering all of them. Doing it through the constructor
//! would mean building a `Value` array, which is more work and more ways to be wrong — and it
//! would run a script-visible function for an operation that has no script equivalent.
//!
//! # Why the protos come from the realm
//!
//! A view has to be `instanceof Uint8Array`, so its prototype must be the realm's
//! `Uint8Array.prototype` and its buffer's must be the realm's `ArrayBuffer.prototype`. The
//! realm is where the intrinsics were installed, and reaching for it is what keeps
//! `Object.getPrototypeOf(new Uint8Array(buf))` answering the constructor's prototype.

use std::cell::RefCell;
use std::rc::Rc;

use engine::Value;
use engine::builtins::typedarray::ElementType;
use engine::interp::{Interp, JsResult, Signal};
use engine::object::{BufferStorage, JsObject};
use js_gc::Gc;

use crate::buffers::typed_array_kind;

/// `ElementType::Uint8`, named so that a caller does not have to spell the engine's path.
pub const UINT8: ElementType = ElementType::Uint8;

/// An `ArrayBuffer` holding `bytes`.
pub fn new_array_buffer(interp: &mut Interp<'static>, bytes: Vec<u8>) -> Gc<JsObject> {
    let proto = interp
        .realm
        .array_buffer_proto
        .clone()
        .unwrap_or_else(|| interp.realm.object_proto.clone());
    let object = interp.new_object(Some(proto));
    object.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed(bytes))));
    object
}

/// [`new_array_buffer`] whose origin block is released when the buffer is collected.
///
/// The closure is the C API's `free_func`; the engine's `BufferStorage` runs it in `Drop`,
/// which happens when the last handle to the buffer goes — the same moment the reference
/// frees the block.
pub fn new_array_buffer_with_release(
    interp: &mut Interp<'static>,
    bytes: Vec<u8>,
    release: Box<dyn FnOnce()>,
) -> Gc<JsObject> {
    let proto = interp
        .realm
        .array_buffer_proto
        .clone()
        .unwrap_or_else(|| interp.realm.object_proto.clone());
    let object = interp.new_object(Some(proto));
    object.set_array_buffer(Rc::new(RefCell::new(BufferStorage::fixed_with_release(
        bytes, release,
    ))));
    object
}

/// A typed-array view of `element` over `buffer[offset .. offset + length]`.
///
/// The prototype is the realm's for that element type, which is what makes the view answer
/// `instanceof` and inherit every method.
pub fn new_view(
    interp: &mut Interp<'static>,
    buffer: &Gc<JsObject>,
    element: ElementType,
    offset: usize,
    length: usize,
) -> Gc<JsObject> {
    // `typed_array_protos` is in `ELEMENT_TYPES` order, which is the only index the engine
    // publishes for it; the position is looked up rather than assumed.
    let index = engine::builtins::typedarray::ELEMENT_TYPES
        .iter()
        .position(|(kind, _)| *kind == element)
        .unwrap_or(0);
    let proto = interp
        .realm
        .typed_array_protos
        .get(index)
        .cloned()
        .or_else(|| interp.realm.typed_array_proto.clone())
        .unwrap_or_else(|| interp.realm.object_proto.clone());
    let object = interp.new_object(Some(proto));
    object.set_typed_array(buffer.clone(), element, offset, length);
    object
}

/// `new Uint8Array(...)` and friends, from decoded arguments.
///
/// Three argument shapes, exactly as the constructor has them: a length, an iterable or
/// array-like, or `(buffer, byteOffset, length)`. Rather than reimplement the distinctions,
/// this calls the realm's constructor with the arguments C supplied — which is also what makes
/// a wrong argument a `TypeError` from the same code a script would hit.
pub fn construct_typed_array(
    interp: &mut Interp<'static>,
    element: ElementType,
    args: Vec<Value>,
) -> JsResult<Value> {
    // The constructor is a global binding, so it is read from the global object rather than
    // from a table: `Uint8Array` may legitimately have been replaced by a script.
    let global = Value::Object(interp.realm.global.clone());
    let Value::Object(constructor) = interp.read_field(&global, element.name())? else {
        return Err(Signal::Throw(interp.make_error(
            "TypeError",
            &format!("{} is not installed", element.name()),
        )));
    };
    let callee = Value::Object(constructor);
    interp.construct(callee.clone(), callee, args)
}

/// The `JSTypedArrayEnum` value for `element`.
pub fn kind_from_element(element: ElementType) -> i32 {
    match element {
        ElementType::Uint8Clamped => typed_array_kind::UINT8C,
        ElementType::Int8 => typed_array_kind::INT8,
        ElementType::Uint8 => typed_array_kind::UINT8,
        ElementType::Int16 => typed_array_kind::INT16,
        ElementType::Uint16 => typed_array_kind::UINT16,
        ElementType::Int32 => typed_array_kind::INT32,
        ElementType::Uint32 => typed_array_kind::UINT32,
        ElementType::BigInt64 => typed_array_kind::BIG_INT64,
        ElementType::BigUint64 => typed_array_kind::BIG_UINT64,
        ElementType::Float16 => typed_array_kind::FLOAT16,
        ElementType::Float32 => typed_array_kind::FLOAT32,
        ElementType::Float64 => typed_array_kind::FLOAT64,
    }
}

/// The engine element type for a `JSTypedArrayEnum` value, or `None` when out of range.
pub fn element_from_kind(kind: i32) -> Option<ElementType> {
    Some(match kind {
        typed_array_kind::UINT8C => ElementType::Uint8Clamped,
        typed_array_kind::INT8 => ElementType::Int8,
        typed_array_kind::UINT8 => ElementType::Uint8,
        typed_array_kind::INT16 => ElementType::Int16,
        typed_array_kind::UINT16 => ElementType::Uint16,
        typed_array_kind::INT32 => ElementType::Int32,
        typed_array_kind::UINT32 => ElementType::Uint32,
        typed_array_kind::BIG_INT64 => ElementType::BigInt64,
        typed_array_kind::BIG_UINT64 => ElementType::BigUint64,
        typed_array_kind::FLOAT16 => ElementType::Float16,
        typed_array_kind::FLOAT32 => ElementType::Float32,
        typed_array_kind::FLOAT64 => ElementType::Float64,
        _ => return None,
    })
}