wasmi_c_api/
table.rs

1use crate::{wasm_extern_t, wasm_ref_t, wasm_store_t, wasm_tabletype_t, WasmRef};
2use alloc::boxed::Box;
3use core::hint;
4use wasmi::{Extern, ExternRef, Func, Ref, Table, TableType};
5
6/// A Wasm table.
7///
8/// Wraps [`Table`].
9#[derive(Clone)]
10#[repr(transparent)]
11pub struct wasm_table_t {
12    inner: wasm_extern_t,
13}
14
15wasmi_c_api_macros::declare_ref!(wasm_table_t);
16
17/// Type specifying the number of cells of a Wasm table.
18pub type wasm_table_size_t = u32;
19
20impl wasm_table_t {
21    pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_table_t> {
22        match &e.which {
23            Extern::Table(_) => Some(unsafe { &*(e as *const _ as *const _) }),
24            _ => None,
25        }
26    }
27
28    pub(crate) fn try_from_mut(e: &mut wasm_extern_t) -> Option<&mut wasm_table_t> {
29        match &mut e.which {
30            Extern::Table(_) => Some(unsafe { &mut *(e as *mut _ as *mut _) }),
31            _ => None,
32        }
33    }
34
35    /// Returns the underlying [`Table`] of the [`wasm_table_t`].
36    fn table(&self) -> Table {
37        match self.inner.which {
38            Extern::Table(t) => t,
39            _ => unsafe { hint::unreachable_unchecked() },
40        }
41    }
42}
43
44/// Returns the [`WasmRef`] respective to the optional [`wasm_ref_t`].
45///
46/// Returns a `null` [`WasmRef`] if [`wasm_ref_t`] is `None`.
47fn option_wasm_ref_t_to_ref(r: Option<&wasm_ref_t>, table_ty: &TableType) -> WasmRef {
48    r.map(|r| r.inner.clone())
49        .unwrap_or_else(|| match table_ty.element() {
50            wasmi::ValType::FuncRef => WasmRef::Func(<Ref<Func>>::Null),
51            wasmi::ValType::ExternRef => WasmRef::Extern(<Ref<ExternRef>>::Null),
52            invalid => panic!("encountered invalid table type: {invalid:?}"),
53        })
54}
55
56/// Creates a new [`wasm_table_t`] from the given [`wasm_tabletype_t`].
57///
58/// Wraps [`Table::new`].
59///
60/// # Safety
61///
62/// It is the caller's responsibility not to alias the [`wasm_table_t`]
63/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
64#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
65#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
66pub unsafe extern "C" fn wasm_table_new(
67    store: &mut wasm_store_t,
68    tt: &wasm_tabletype_t,
69    init: Option<&wasm_ref_t>,
70) -> Option<Box<wasm_table_t>> {
71    let tt = tt.ty().ty;
72    let init = option_wasm_ref_t_to_ref(init, &tt);
73    let table = Table::new(store.inner.context_mut(), tt, init.into()).ok()?;
74    Some(Box::new(wasm_table_t {
75        inner: wasm_extern_t {
76            store: store.inner.clone(),
77            which: table.into(),
78        },
79    }))
80}
81
82/// Returns the [`wasm_tabletype_t`] of the [`wasm_table_t`].
83///
84/// Wraps [`Table::ty`].
85///
86/// # Safety
87///
88/// It is the caller's responsibility not to alias the [`wasm_table_t`]
89/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
90#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
91#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
92pub unsafe extern "C" fn wasm_table_type(t: &wasm_table_t) -> Box<wasm_tabletype_t> {
93    let table = t.table();
94    let store = t.inner.store.context();
95    Box::new(wasm_tabletype_t::new(table.ty(store)))
96}
97
98/// Returns the element at `index` of [`wasm_table_t`] `t`.
99///
100/// Wraps [`Table::get`].
101///
102/// # Safety
103///
104/// It is the caller's responsibility not to alias the [`wasm_table_t`]
105/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
106#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
107#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
108pub unsafe extern "C" fn wasm_table_get(
109    t: &mut wasm_table_t,
110    index: wasm_table_size_t,
111) -> Option<Box<wasm_ref_t>> {
112    let table = t.table();
113    let value = table.get(t.inner.store.context_mut(), u64::from(index))?;
114    let wasm_ref = match value {
115        wasmi::Val::FuncRef(r) => WasmRef::Func(r),
116        wasmi::Val::ExternRef(r) => WasmRef::Extern(r),
117        invalid => panic!("encountered invalid value in table at {index}: {invalid:?}"),
118    };
119    wasm_ref_t::new(wasm_ref)
120}
121
122/// Sets the value of the element at `index` of [`wasm_table_t`] to `new_value`.
123///
124/// Wraps [`Table::set`].
125///
126/// # Safety
127///
128/// It is the caller's responsibility not to alias the [`wasm_table_t`]
129/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
130#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
131#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
132pub unsafe extern "C" fn wasm_table_set(
133    t: &mut wasm_table_t,
134    index: wasm_table_size_t,
135    new_value: Option<&wasm_ref_t>,
136) -> bool {
137    let table = t.table();
138    let new_value = option_wasm_ref_t_to_ref(new_value, &table.ty(t.inner.store.context()));
139    table
140        .set(
141            t.inner.store.context_mut(),
142            u64::from(index),
143            new_value.into(),
144        )
145        .is_ok()
146}
147
148/// Returns the number of cells of the [`wasm_table_t`].
149///
150/// Wraps [`Table::size`].
151///
152/// # Safety
153///
154/// It is the caller's responsibility not to alias the [`wasm_table_t`]
155/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
156#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
157#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
158pub unsafe extern "C" fn wasm_table_size(t: &wasm_table_t) -> wasm_table_size_t {
159    let table = t.table();
160    let store = t.inner.store.context();
161    let size = table.size(store);
162    u32::try_from(size).unwrap()
163}
164/// Grows the number of cells of the [`wasm_table_t`] by `delta`.
165///
166/// Returns `true` if the operation was successful.
167///
168/// Wraps [`Table::grow`].
169///
170/// # Safety
171///
172/// It is the caller's responsibility not to alias the [`wasm_table_t`]
173/// with its underlying, internal [`WasmStoreRef`](crate::WasmStoreRef).
174#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
175#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
176pub unsafe extern "C" fn wasm_table_grow(
177    t: &mut wasm_table_t,
178    delta: wasm_table_size_t,
179    init: Option<&wasm_ref_t>,
180) -> bool {
181    let table = t.table();
182    let init = option_wasm_ref_t_to_ref(init, &table.ty(t.inner.store.context()));
183    table
184        .grow(t.inner.store.context_mut(), u64::from(delta), init.into())
185        .is_ok()
186}
187
188/// Returns the [`wasm_table_t`] as mutable reference to [`wasm_extern_t`].
189#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
190#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
191pub extern "C" fn wasm_table_as_extern(t: &mut wasm_table_t) -> &mut wasm_extern_t {
192    &mut t.inner
193}
194
195/// Returns the [`wasm_table_t`] as shared reference to [`wasm_extern_t`].
196#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
197#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
198pub extern "C" fn wasm_table_as_extern_const(t: &wasm_table_t) -> &wasm_extern_t {
199    &t.inner
200}