pyodide_webassembly_runtime_layer/
table.rs

1use pyo3::{intern, prelude::*, sync::GILOnceCell};
2use wasm_runtime_layer::{
3    backend::{AsContext, AsContextMut, Value, WasmTable},
4    TableType, ValueType,
5};
6
7use crate::{
8    conversion::{create_js_object, instanceof, ToPy, ValueExt, ValueTypeExt},
9    Engine,
10};
11
12#[derive(Debug)]
13/// A WASM table.
14///
15/// This type wraps a [`WebAssembly.Table`] from the JavaScript API.
16///
17/// [`WebAssembly.Table`]: https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Table
18pub struct Table {
19    /// Table reference
20    table: Py<PyAny>,
21    /// The table signature
22    ty: TableType,
23}
24
25impl Clone for Table {
26    fn clone(&self) -> Self {
27        Python::with_gil(|py| Self {
28            table: self.table.clone_ref(py),
29            ty: self.ty,
30        })
31    }
32}
33
34impl WasmTable<Engine> for Table {
35    fn new(
36        _ctx: impl AsContextMut<Engine>,
37        ty: TableType,
38        init: Value<Engine>,
39    ) -> anyhow::Result<Self> {
40        Python::with_gil(|py| -> anyhow::Result<Self> {
41            #[cfg(feature = "tracing")]
42            tracing::debug!(?ty, ?init, "Table::new");
43
44            let desc = create_js_object(py)?;
45            desc.setattr(intern!(py, "element"), ty.element().as_js_descriptor())?;
46            desc.setattr(intern!(py, "initial"), ty.minimum())?;
47            if let Some(max) = ty.maximum() {
48                desc.setattr(intern!(py, "maximum"), max)?;
49            }
50
51            let init = init.to_py(py);
52
53            let table = web_assembly_table_new(py)?.call1((desc, init))?;
54
55            Ok(Self {
56                table: table.unbind(),
57                ty,
58            })
59        })
60    }
61
62    /// Returns the type and limits of the table.
63    fn ty(&self, _ctx: impl AsContext<Engine>) -> TableType {
64        self.ty
65    }
66
67    /// Returns the current size of the table.
68    fn size(&self, _ctx: impl AsContext<Engine>) -> u32 {
69        Python::with_gil(|py| -> Result<u32, PyErr> {
70            let table = self.table.bind(py);
71
72            #[cfg(feature = "tracing")]
73            tracing::debug!(table = %table, ?self.ty, "Table::size");
74
75            table.getattr(intern!(py, "length"))?.extract()
76        })
77        .expect("Table::size should not fail")
78    }
79
80    /// Grows the table by the given amount of elements.
81    fn grow(
82        &self,
83        _ctx: impl AsContextMut<Engine>,
84        delta: u32,
85        init: Value<Engine>,
86    ) -> anyhow::Result<u32> {
87        Python::with_gil(|py| {
88            let table = self.table.bind(py);
89
90            #[cfg(feature = "tracing")]
91            tracing::debug!(table = %table, ?self.ty, delta, ?init, "Table::grow");
92
93            let init = init.to_py(py);
94
95            let old_len = table
96                .call_method1(intern!(py, "grow"), (delta, init))?
97                .extract()?;
98
99            Ok(old_len)
100        })
101    }
102
103    /// Returns the table element value at `index`.
104    fn get(&self, _ctx: impl AsContextMut<Engine>, index: u32) -> Option<Value<Engine>> {
105        Python::with_gil(|py| {
106            let table = self.table.bind(py);
107
108            #[cfg(feature = "tracing")]
109            tracing::debug!(table = %table, ?self.ty, index, "Table::get");
110
111            let value = table.call_method1(intern!(py, "get"), (index,)).ok()?;
112
113            Some(
114                Value::from_py_typed(value, self.ty.element()).expect("Table::get should not fail"),
115            )
116        })
117    }
118
119    /// Sets the value of this table at `index`.
120    fn set(
121        &self,
122        _ctx: impl AsContextMut<Engine>,
123        index: u32,
124        value: Value<Engine>,
125    ) -> anyhow::Result<()> {
126        Python::with_gil(|py| {
127            let table = self.table.bind(py);
128
129            #[cfg(feature = "tracing")]
130            tracing::debug!(table = %table, ?self.ty, index, ?value, "Table::set");
131
132            let value = value.to_py(py);
133
134            table.call_method1(intern!(py, "set"), (index, value))?;
135
136            Ok(())
137        })
138    }
139}
140
141impl ToPy for Table {
142    fn to_py(&self, py: Python) -> Py<PyAny> {
143        #[cfg(feature = "tracing")]
144        tracing::trace!(table = %self.table, ?self.ty, "Table::to_py");
145
146        self.table.clone_ref(py)
147    }
148}
149
150impl Table {
151    /// Creates a new table from a Python value
152    pub(crate) fn from_exported_table(table: Bound<PyAny>, ty: TableType) -> anyhow::Result<Self> {
153        if !instanceof(&table, web_assembly_table(table.py())?)? {
154            anyhow::bail!("expected WebAssembly.Table but found {table}");
155        }
156
157        #[cfg(feature = "tracing")]
158        tracing::debug!(table = %table, ?ty, "Table::from_exported_table");
159
160        let table_length: u32 = table.getattr(intern!(table.py(), "length"))?.extract()?;
161
162        assert!(table_length >= ty.minimum());
163        assert_eq!(ty.element(), ValueType::FuncRef);
164
165        Ok(Self {
166            table: table.unbind(),
167            ty,
168        })
169    }
170}
171
172fn web_assembly_table(py: Python) -> Result<&Bound<PyAny>, PyErr> {
173    static WEB_ASSEMBLY_TABLE: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
174    WEB_ASSEMBLY_TABLE.import(py, "js.WebAssembly", "Table")
175}
176
177fn web_assembly_table_new(py: Python) -> Result<&Bound<PyAny>, PyErr> {
178    static WEB_ASSEMBLY_TABLE_NEW: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
179    WEB_ASSEMBLY_TABLE_NEW.import(py, "js.WebAssembly.Table", "new")
180}