Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Add support for `arrayref`s to the C and C++ APIs (#12916)

Nick Fitzgeraldfc8dc5d27714
diff --git a/crates/c-api/include/wasmtime/gc.h b/crates/c-api/include/wasmtime/gc.h
index 42eba19649..486ba319bf 100644
--- a/crates/c-api/include/wasmtime/gc.h
+++ b/crates/c-api/include/wasmtime/gc.h
@@ -342,6 +342,199 @@ WASM_API_EXTERN bool wasmtime_eqref_as_struct(wasmtime_context_t *context,
const wasmtime_eqref_t *eqref,
wasmtime_structref_t *out);
+/**
+ * \brief An opaque handle to a WebAssembly array type definition.
+ *
+ * An array type describes the element type of an array. It is used to create a
+ * #wasmtime_array_ref_pre_t, which can then allocate array instances.
+ *
+ * Owned. Must be deleted with #wasmtime_array_type_delete.
+ */
+typedef struct wasmtime_array_type wasmtime_array_type_t;
+
+/**
+ * \brief Create a new array type.
+ *
+ * \param engine The engine to register the type with.
+ * \param field The element type descriptor.
+ *
+ * \return Returns a new array type.
+ */
+WASM_API_EXTERN wasmtime_array_type_t *
+wasmtime_array_type_new(const wasm_engine_t *engine,
+ const wasmtime_field_type_t *field);
+
+/**
+ * \brief Delete an array type.
+ */
+WASM_API_EXTERN void wasmtime_array_type_delete(wasmtime_array_type_t *ty);
+
+/**
+ * \brief An opaque pre-allocated array layout for fast allocation.
+ *
+ * Created from a #wasmtime_array_type_t and a store context. Reusable for
+ * allocating many array instances of the same type.
+ *
+ * Owned. Must be deleted with #wasmtime_array_ref_pre_delete.
+ */
+typedef struct wasmtime_array_ref_pre wasmtime_array_ref_pre_t;
+
+/**
+ * \brief Create a new array pre-allocator.
+ *
+ * \param context The store context.
+ * \param ty The array type (not consumed; caller retains ownership).
+ *
+ * \return Returns a new array ref pre-allocator.
+ */
+WASM_API_EXTERN wasmtime_array_ref_pre_t *
+wasmtime_array_ref_pre_new(wasmtime_context_t *context,
+ const wasmtime_array_type_t *ty);
+
+/**
+ * \brief Delete an array pre-allocator.
+ */
+WASM_API_EXTERN void
+wasmtime_array_ref_pre_delete(wasmtime_array_ref_pre_t *pre);
+
+/**
+ * \typedef wasmtime_arrayref_t
+ * \brief Convenience alias for #wasmtime_arrayref
+ *
+ * \struct wasmtime_arrayref
+ * \brief A WebAssembly `arrayref` value.
+ *
+ * This structure represents a reference to a GC array. It is a subtype of
+ * `eqref` and `anyref`.
+ *
+ * Values must be explicitly unrooted via #wasmtime_arrayref_unroot.
+ */
+typedef struct wasmtime_arrayref {
+ /// Internal metadata.
+ uint64_t store_id;
+ /// Internal to Wasmtime.
+ uint32_t __private1;
+ /// Internal to Wasmtime.
+ uint32_t __private2;
+ /// Internal to Wasmtime.
+ void *__private3;
+} wasmtime_arrayref_t;
+
+/// \brief Initialize the `ref` to a null `arrayref` value.
+static inline void wasmtime_arrayref_set_null(wasmtime_arrayref_t *ref) {
+ ref->store_id = 0;
+}
+
+/// \brief Returns whether the provided `ref` is a null `arrayref` value.
+static inline bool wasmtime_arrayref_is_null(const wasmtime_arrayref_t *ref) {
+ return ref->store_id == 0;
+}
+
+/**
+ * \brief Allocate a new array instance.
+ *
+ * All elements are initialized to the same value.
+ *
+ * \param context The store context.
+ * \param pre The array pre-allocator.
+ * \param elem The initial element value.
+ * \param len The number of elements.
+ * \param out Receives the new arrayref on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *wasmtime_arrayref_new(
+ wasmtime_context_t *context, const wasmtime_array_ref_pre_t *pre,
+ const wasmtime_val_t *elem, uint32_t len, wasmtime_arrayref_t *out);
+
+/**
+ * \brief Clone an `arrayref`, creating a new root.
+ */
+WASM_API_EXTERN void
+wasmtime_arrayref_clone(const wasmtime_arrayref_t *arrayref,
+ wasmtime_arrayref_t *out);
+
+/**
+ * \brief Unroot an `arrayref` to allow garbage collection.
+ */
+WASM_API_EXTERN void wasmtime_arrayref_unroot(wasmtime_arrayref_t *ref);
+
+/**
+ * \brief Upcast an `arrayref` to an `anyref`.
+ */
+WASM_API_EXTERN void
+wasmtime_arrayref_to_anyref(const wasmtime_arrayref_t *arrayref,
+ wasmtime_anyref_t *out);
+
+/**
+ * \brief Upcast an `arrayref` to an `eqref`.
+ */
+WASM_API_EXTERN void
+wasmtime_arrayref_to_eqref(const wasmtime_arrayref_t *arrayref,
+ wasmtime_eqref_t *out);
+
+/**
+ * \brief Get the length of an array.
+ *
+ * \param context The store context.
+ * \param arrayref The array (not consumed).
+ * \param out Receives the length on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_arrayref_len(wasmtime_context_t *context,
+ const wasmtime_arrayref_t *arrayref, uint32_t *out);
+
+/**
+ * \brief Read an element from an array.
+ *
+ * \param context The store context.
+ * \param arrayref The array (not consumed).
+ * \param index The element index.
+ * \param out Receives the element value on success.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_arrayref_get(wasmtime_context_t *context,
+ const wasmtime_arrayref_t *arrayref, uint32_t index,
+ wasmtime_val_t *out);
+
+/**
+ * \brief Set an element of an array.
+ *
+ * \param context The store context.
+ * \param arrayref The array (not consumed).
+ * \param index The element index.
+ * \param val The value to write.
+ *
+ * \return NULL on success, or a #wasmtime_error_t on failure.
+ */
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_arrayref_set(wasmtime_context_t *context,
+ const wasmtime_arrayref_t *arrayref, uint32_t index,
+ const wasmtime_val_t *val);
+
+/**
+ * \brief Test whether an `eqref` is an `arrayref`.
+ *
+ * Returns `false` for null references.
+ */
+WASM_API_EXTERN bool wasmtime_eqref_is_array(wasmtime_context_t *context,
+ const wasmtime_eqref_t *eqref);
+
+/**
+ * \brief Downcast an `eqref` to an `arrayref`.
+ *
+ * If the given `eqref` is an `arrayref`, a new root for it is stored in `out`
+ * and `true` is returned. Otherwise `false` is returned and `out` is set to
+ * null.
+ */
+WASM_API_EXTERN bool wasmtime_eqref_as_array(wasmtime_context_t *context,
+ const wasmtime_eqref_t *eqref,
+ wasmtime_arrayref_t *out);
+
#ifdef __cplusplus
} // extern "C"
#endif
diff --git a/crates/c-api/include/wasmtime/gc.hh b/crates/c-api/include/wasmtime/gc.hh
index d92445e59c..aa0eb68c9d 100644
--- a/crates/c-api/include/wasmtime/gc.hh
+++ b/crates/c-api/include/wasmtime/gc.hh
@@ -14,6 +14,7 @@
namespace wasmtime {
class StructRef;
+class ArrayRef;
/**
* \brief Representation of a WebAssembly `eqref` value.
@@ -95,6 +96,11 @@ public:
return wasmtime_eqref_is_struct(cx.capi(), &val);
}
+ /// Returns `true` if this eqref is an arrayref.
+ bool is_array(Store::Context cx) const {
+ return wasmtime_eqref_is_array(cx.capi(), &val);
+ }
+
/// Upcast this `eqref` to an `anyref`.
AnyRef to_anyref() const {
wasmtime_anyref_t out;
@@ -106,6 +112,11 @@ public:
//
// as_struct() defined after StructRef below.
inline StructRef as_struct(Store::Context cx) const;
+
+ /// Downcast this `eqref` into an `arrayref`.
+ //
+ // as_array() defined after ArrayRef below.
+ inline ArrayRef as_array(Store::Context cx) const;
};
/**
@@ -282,6 +293,158 @@ inline StructRef EqRef::as_struct(Store::Context cx) const {
return StructRef(out);
}
+/**
+ * \brief Owned handle to a WebAssembly array type definition.
+ */
+class ArrayType {
+ struct Deleter {
+ void operator()(wasmtime_array_type_t *p) const {
+ wasmtime_array_type_delete(p);
+ }
+ };
+ std::unique_ptr<wasmtime_array_type_t, Deleter> ptr;
+
+public:
+ /// Create a new array type with the given element type.
+ static ArrayType create(const Engine &engine, const FieldType &field) {
+ static_assert(sizeof(FieldType) == sizeof(wasmtime_field_type_t));
+ auto *raw = wasmtime_array_type_new(
+ engine.capi(), reinterpret_cast<const wasmtime_field_type_t *>(&field));
+ ArrayType ty;
+ ty.ptr.reset(raw);
+ return ty;
+ }
+
+ /// Get the underlying C pointer (non-owning).
+ const wasmtime_array_type_t *capi() const { return ptr.get(); }
+
+private:
+ ArrayType() = default;
+ friend class ArrayRefPre;
+};
+
+/**
+ * \brief Pre-allocated array layout for fast allocation of array instances.
+ *
+ * Created from a ArrayType and a store context. Reusable for allocating
+ * many array instances of the same type.
+ */
+class ArrayRefPre {
+ friend class ArrayRef;
+ WASMTIME_OWN_WRAPPER(ArrayRefPre, wasmtime_array_ref_pre)
+
+public:
+ /// Create a new array pre-allocator.
+ static ArrayRefPre create(Store::Context cx, const ArrayType &ty) {
+ auto *raw = wasmtime_array_ref_pre_new(cx.capi(), ty.capi());
+ ArrayRefPre pre(raw);
+ return pre;
+ }
+};
+
+/**
+ * \brief Representation of a WebAssembly `arrayref` value.
+ *
+ * An `arrayref` is a reference to a GC array instance. It is a subtype
+ * of `eqref` and `anyref`.
+ */
+class ArrayRef {
+ friend class EqRef;
+ friend class Val;
+ friend class AnyRef;
+
+ wasmtime_arrayref_t val;
+
+public:
+ /// Create a `ArrayRef` from its C-API representation.
+ explicit ArrayRef(wasmtime_arrayref_t val) : val(val) {}
+
+ /// Clone a `ArrayRef`.
+ ArrayRef(const ArrayRef &other) { wasmtime_arrayref_clone(&other.val, &val); }
+
+ /// Clone a `ArrayRef` into this one.
+ ArrayRef &operator=(const ArrayRef &other) {
+ wasmtime_arrayref_unroot(&val);
+ wasmtime_arrayref_clone(&other.val, &val);
+ return *this;
+ }
+
+ /// Move a `ArrayRef`.
+ ArrayRef(ArrayRef &&other) {
+ val = other.val;
+ wasmtime_arrayref_set_null(&other.val);
+ }
+
+ /// Move a `ArrayRef` into this one.
+ ArrayRef &operator=(ArrayRef &&other) {
+ wasmtime_arrayref_unroot(&val);
+ val = other.val;
+ wasmtime_arrayref_set_null(&other.val);
+ return *this;
+ }
+
+ /// Unroot this `ArrayRef`.
+ ~ArrayRef() { wasmtime_arrayref_unroot(&val); }
+
+ /// Allocate a new array with all elements set to the same value.
+ static Result<ArrayRef> create(Store::Context cx, const ArrayRefPre &pre,
+ const Val &elem, uint32_t len) {
+ wasmtime_arrayref_t out;
+ auto *err =
+ wasmtime_arrayref_new(cx.capi(), pre.capi(), &elem.val, len, &out);
+ if (err)
+ return Result<ArrayRef>(Error(err));
+ return Result<ArrayRef>(ArrayRef(out));
+ }
+
+ /// Get the length of the array.
+ Result<uint32_t> len(Store::Context cx) const {
+ uint32_t out;
+ auto *err = wasmtime_arrayref_len(cx.capi(), &val, &out);
+ if (err)
+ return Result<uint32_t>(Error(err));
+ return Result<uint32_t>(out);
+ }
+
+ /// Read an element from the array.
+ Result<Val> get(Store::Context cx, uint32_t index) const {
+ wasmtime_val_t out;
+ auto *err = wasmtime_arrayref_get(cx.capi(), &val, index, &out);
+ if (err)
+ return Result<Val>(Error(err));
+ return Result<Val>(Val(out));
+ }
+
+ /// Set an element of the array.
+ Result<std::monostate> set(Store::Context cx, uint32_t index,
+ const Val &value) const {
+ auto *err = wasmtime_arrayref_set(cx.capi(), &val, index, &value.val);
+ if (err)
+ return Result<std::monostate>(Error(err));
+ return Result<std::monostate>(std::monostate{});
+ }
+
+ /// Upcast to anyref.
+ AnyRef to_anyref() const {
+ wasmtime_anyref_t out;
+ wasmtime_arrayref_to_anyref(&val, &out);
+ return AnyRef(out);
+ }
+
+ /// Upcast to eqref.
+ EqRef to_eqref() const {
+ wasmtime_eqref_t out;
+ wasmtime_arrayref_to_eqref(&val, &out);
+ return EqRef(out);
+ }
+};
+
+inline ArrayRef EqRef::as_array(Store::Context cx) const {
+ wasmtime_arrayref_t out;
+ wasmtime_eqref_as_array(cx.capi(), &val, &out);
+ return ArrayRef(out);
+}
+
} // namespace wasmtime
#endif // WASMTIME_GC_HH
diff --git a/crates/c-api/include/wasmtime/val.hh b/crates/c-api/include/wasmtime/val.hh
index 4885e9702f..1d49cfe2c0 100644
--- a/crates/c-api/include/wasmtime/val.hh
+++ b/crates/c-api/include/wasmtime/val.hh
@@ -215,6 +215,7 @@ class Val {
friend class Func;
friend class Exn;
friend class StructRef;
+ friend class ArrayRef;
wasmtime_val_t val;
diff --git a/crates/c-api/src/ref.rs b/crates/c-api/src/ref.rs
index 17e494b624..e75870a167 100644
--- a/crates/c-api/src/ref.rs
+++ b/crates/c-api/src/ref.rs
@@ -2,8 +2,8 @@ use crate::{WasmtimeStoreContextMut, abort};
use std::mem::{ManuallyDrop, MaybeUninit};
use std::{num::NonZeroU64, os::raw::c_void, ptr};
use wasmtime::{
- AnyRef, EqRef, ExnRef, ExternRef, FieldType, I31, Mutability, OwnedRooted, Ref, RootScope,
- StorageType, StructRef, StructRefPre, StructType, Val, ValType,
+ AnyRef, ArrayRef, ArrayRefPre, ArrayType, EqRef, ExnRef, ExternRef, FieldType, I31, Mutability,
+ OwnedRooted, Ref, RootScope, StorageType, StructRef, StructRefPre, StructType, Val, ValType,
};
/// `*mut wasm_ref_t` is a reference type (`externref` or `funcref`), as seen by
@@ -282,6 +282,18 @@ pub struct wasmtime_struct_ref_pre_t {
}
wasmtime_c_api_macros::declare_own!(wasmtime_struct_ref_pre_t);
+ref_wrapper!(ArrayRef => wasmtime_arrayref_t);
+
+pub struct wasmtime_array_type_t {
+ ty: ArrayType,
+}
+wasmtime_c_api_macros::declare_own!(wasmtime_array_type_t);
+
+pub struct wasmtime_array_ref_pre_t {
+ pre: ArrayRefPre,
+}
+wasmtime_c_api_macros::declare_own!(wasmtime_array_ref_pre_t);
+
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasmtime_anyref_clone(
anyref: Option<&wasmtime_anyref_t>,
@@ -754,3 +766,174 @@ pub unsafe extern "C" fn wasmtime_eqref_as_struct(
crate::initialize(out, None::<OwnedRooted<StructRef>>.into());
false
}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_array_type_new(
+ engine: &crate::wasm_engine_t,
+ field: &wasmtime_field_type_t,
+) -> Box<wasmtime_array_type_t> {
+ let ft = field_type_from_c(field);
+ let ty = ArrayType::new(&engine.engine, ft);
+ Box::new(wasmtime_array_type_t { ty })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn wasmtime_array_ref_pre_new(
+ cx: WasmtimeStoreContextMut<'_>,
+ ty: &wasmtime_array_type_t,
+) -> Box<wasmtime_array_ref_pre_t> {
+ let pre = ArrayRefPre::new(cx, ty.ty.clone());
+ Box::new(wasmtime_array_ref_pre_t { pre })
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_new(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ pre: &wasmtime_array_ref_pre_t,
+ elem: &crate::wasmtime_val_t,
+ len: u32,
+ out: &mut MaybeUninit<wasmtime_arrayref_t>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let mut scope = RootScope::new(&mut cx);
+ let val = elem.to_val(&mut scope);
+ match ArrayRef::new(&mut scope, &pre.pre, &val, len) {
+ Ok(arrayref) => {
+ let owned = arrayref
+ .to_owned_rooted(&mut scope)
+ .expect("just allocated");
+ crate::initialize(out, Some(owned).into());
+ None
+ }
+ Err(e) => {
+ crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
+ Some(Box::new(e.into()))
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_clone(
+ arrayref: Option<&wasmtime_arrayref_t>,
+ out: &mut MaybeUninit<wasmtime_arrayref_t>,
+) {
+ let arrayref = arrayref.and_then(|a| a.as_wasmtime());
+ crate::initialize(out, arrayref.into());
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_unroot(
+ arrayref: Option<&mut ManuallyDrop<wasmtime_arrayref_t>>,
+) {
+ if let Some(arrayref) = arrayref {
+ ManuallyDrop::drop(arrayref);
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_to_anyref(
+ arrayref: Option<&wasmtime_arrayref_t>,
+ out: &mut MaybeUninit<wasmtime_anyref_t>,
+) {
+ let anyref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .map(|a| a.to_anyref());
+ crate::initialize(out, anyref.into());
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_to_eqref(
+ arrayref: Option<&wasmtime_arrayref_t>,
+ out: &mut MaybeUninit<wasmtime_eqref_t>,
+) {
+ let eqref = arrayref.and_then(|a| a.as_wasmtime()).map(|a| a.to_eqref());
+ crate::initialize(out, eqref.into());
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_len(
+ cx: WasmtimeStoreContextMut<'_>,
+ arrayref: Option<&wasmtime_arrayref_t>,
+ out: &mut MaybeUninit<u32>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let arrayref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .expect("non-null arrayref required");
+ match arrayref.len(&cx) {
+ Ok(len) => {
+ crate::initialize(out, len);
+ None
+ }
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_get(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ arrayref: Option<&wasmtime_arrayref_t>,
+ index: u32,
+ out: &mut MaybeUninit<crate::wasmtime_val_t>,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let arrayref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .expect("non-null arrayref required");
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = arrayref.to_rooted(&mut scope);
+ match rooted.get(&mut scope, index) {
+ Ok(val) => {
+ let c_val = crate::wasmtime_val_t::from_val(&mut scope, val);
+ crate::initialize(out, c_val);
+ None
+ }
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_arrayref_set(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ arrayref: Option<&wasmtime_arrayref_t>,
+ index: u32,
+ val: &crate::wasmtime_val_t,
+) -> Option<Box<crate::wasmtime_error_t>> {
+ let arrayref = arrayref
+ .and_then(|a| a.as_wasmtime())
+ .expect("non-null arrayref required");
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = arrayref.to_rooted(&mut scope);
+ let rust_val = val.to_val(&mut scope);
+ match rooted.set(&mut scope, index, rust_val) {
+ Ok(()) => None,
+ Err(e) => Some(Box::new(e.into())),
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_eqref_is_array(
+ cx: WasmtimeStoreContextMut<'_>,
+ eqref: Option<&wasmtime_eqref_t>,
+) -> bool {
+ match eqref.and_then(|e| e.as_wasmtime()) {
+ Some(eqref) => eqref.is_array(&cx).expect("OwnedRooted always in scope"),
+ None => false,
+ }
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasmtime_eqref_as_array(
+ mut cx: WasmtimeStoreContextMut<'_>,
+ eqref: Option<&wasmtime_eqref_t>,
+ out: &mut MaybeUninit<wasmtime_arrayref_t>,
+) -> bool {
+ if let Some(eqref) = eqref.and_then(|e| e.as_wasmtime()) {
+ let mut scope = RootScope::new(&mut cx);
+ let rooted = eqref.to_rooted(&mut scope);
+ if let Ok(Some(arrayref)) = rooted.as_array(&scope) {
+ let owned = arrayref.to_owned_rooted(&mut scope).expect("just created");
+ crate::initialize(out, Some(owned).into());
+ return true;
+ }
+ }
+ crate::initialize(out, None::<OwnedRooted<ArrayRef>>.into());
+ false
+}
diff --git a/crates/c-api/tests/gc.cc b/crates/c-api/tests/gc.cc
index 896f68c757..71629c48d7 100644
--- a/crates/c-api/tests/gc.cc
+++ b/crates/c-api/tests/gc.cc
@@ -160,3 +160,75 @@ TEST(StructRef, UpcastAndDowncast) {
AnyRef any = s.to_anyref();
EXPECT_FALSE(any.is_i31(cx));
}
+
+TEST(ArrayRef, CreateAndReadElements) {
+ Config config;
+ config.wasm_gc(true);
+ Engine engine(std::move(config));
+ Store store(engine);
+ auto cx = store.context();
+
+ // Create an array type with mutable i32 elements.
+ auto ty = ArrayType::create(engine, FieldType::mut_(WASMTIME_I32));
+ auto pre = ArrayRefPre::create(cx, ty);
+
+ // Allocate an array of 5 elements, all initialized to 7.
+ auto result = ArrayRef::create(cx, pre, Val(int32_t(7)), 5);
+ ASSERT_TRUE(result);
+ ArrayRef arr = result.ok();
+
+ // Check length.
+ auto len_result = arr.len(cx);
+ ASSERT_TRUE(len_result);
+ EXPECT_EQ(len_result.ok(), 5u);
+
+ // Read elements.
+ for (uint32_t i = 0; i < 5; i++) {
+ auto v = arr.get(cx, i);
+ ASSERT_TRUE(v);
+ EXPECT_EQ(v.ok().i32(), 7);
+ }
+
+ // Write element 2 to 42, read back.
+ auto set_result = arr.set(cx, 2, Val(int32_t(42)));
+ ASSERT_TRUE(set_result);
+
+ auto v2 = arr.get(cx, 2);
+ ASSERT_TRUE(v2);
+ EXPECT_EQ(v2.ok().i32(), 42);
+}
+
+TEST(ArrayRef, UpcastAndDowncast) {
+ Config config;
+ config.wasm_gc(true);
+ Engine engine(std::move(config));
+ Store store(engine);
+ auto cx = store.context();
+
+ auto ty = ArrayType::create(engine, FieldType::const_(WASMTIME_I32));
+ auto pre = ArrayRefPre::create(cx, ty);
+
+ auto result = ArrayRef::create(cx, pre, Val(int32_t(99)), 3);
+ ASSERT_TRUE(result);
+ ArrayRef arr = result.ok();
+
+ // Upcast to eqref.
+ EqRef eq = arr.to_eqref();
+ EXPECT_TRUE(eq.is_array(cx));
+ EXPECT_FALSE(eq.is_struct(cx));
+ EXPECT_FALSE(eq.is_i31(cx));
+
+ // Downcast back to arrayref.
+ ArrayRef arr2 = eq.as_array(cx);
+ auto len = arr2.len(cx);
+ ASSERT_TRUE(len);
+ EXPECT_EQ(len.ok(), 3u);
+
+ auto v = arr2.get(cx, 0);
+ ASSERT_TRUE(v);
+ EXPECT_EQ(v.ok().i32(), 99);
+
+ // Upcast to anyref.
+ AnyRef any = arr.to_anyref();
+ EXPECT_FALSE(any.is_i31(cx));
+}