Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a89f75c

Browse files
pref: use Rc's for Module Instances
Signed-off-by: Henry Gressmann <[email protected]>
1 parent 55b6903 commit a89f75c

File tree

7 files changed

+27
-31
lines changed

7 files changed

+27
-31
lines changed

crates/tinywasm/src/func.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ pub trait IntoWasmValueTuple {
100100
}
101101

102102
pub trait FromWasmValueTuple {
103-
fn from_wasm_value_tuple(values: Vec<WasmValue>) -> Result<Self>
103+
fn from_wasm_value_tuple(values: &[WasmValue]) -> Result<Self>
104104
where
105105
Self: Sized;
106106
}
@@ -115,7 +115,7 @@ impl<P: IntoWasmValueTuple, R: FromWasmValueTuple> FuncHandleTyped<P, R> {
115115
let result = self.func.call(store, &wasm_values)?;
116116

117117
// Convert the Vec<WasmValue> back to R
118-
R::from_wasm_value_tuple(result)
118+
R::from_wasm_value_tuple(&result)
119119
}
120120
}
121121
macro_rules! impl_into_wasm_value_tuple {
@@ -164,14 +164,14 @@ macro_rules! impl_from_wasm_value_tuple {
164164
where
165165
$($T: TryFrom<WasmValue, Error = ()>),*
166166
{
167-
fn from_wasm_value_tuple(values: Vec<WasmValue>) -> Result<Self> {
167+
fn from_wasm_value_tuple(values: &[WasmValue]) -> Result<Self> {
168168
#[allow(unused_variables, unused_mut)]
169-
let mut iter = values.into_iter();
169+
let mut iter = values.iter();
170170

171171
Ok((
172172
$(
173173
$T::try_from(
174-
iter.next()
174+
*iter.next()
175175
.ok_or(Error::Other("Not enough values in WasmValue vector".to_string()))?
176176
)
177177
.map_err(|e| Error::Other(format!("FromWasmValueTuple: Could not convert WasmValue to expected type: {:?}", e,
@@ -186,10 +186,10 @@ macro_rules! impl_from_wasm_value_tuple {
186186
macro_rules! impl_from_wasm_value_tuple_single {
187187
($T:ident) => {
188188
impl FromWasmValueTuple for $T {
189-
fn from_wasm_value_tuple(values: Vec<WasmValue>) -> Result<Self> {
189+
fn from_wasm_value_tuple(values: &[WasmValue]) -> Result<Self> {
190190
#[allow(unused_variables, unused_mut)]
191-
let mut iter = values.into_iter();
192-
$T::try_from(iter.next().ok_or(Error::Other("Not enough values in WasmValue vector".to_string()))?)
191+
let mut iter = values.iter();
192+
$T::try_from(*iter.next().ok_or(Error::Other("Not enough values in WasmValue vector".to_string()))?)
193193
.map_err(|e| {
194194
Error::Other(format!(
195195
"FromWasmValueTupleSingle: Could not convert WasmValue to expected type: {:?}",

crates/tinywasm/src/imports.rs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use crate::{
88
};
99
use alloc::{
1010
collections::BTreeMap,
11+
rc::Rc,
1112
string::{String, ToString},
12-
sync::Arc,
1313
vec::Vec,
1414
};
1515
use tinywasm_types::*;
@@ -52,8 +52,7 @@ impl HostFunction {
5252
}
5353
}
5454

55-
pub(crate) type HostFuncInner =
56-
Arc<dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + 'static + Send + Sync>;
55+
pub(crate) type HostFuncInner = Rc<dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>>>;
5756

5857
/// The context of a host-function call
5958
#[derive(Debug)]
@@ -139,31 +138,28 @@ impl Extern {
139138
/// Create a new function import
140139
pub fn func(
141140
ty: &tinywasm_types::FuncType,
142-
func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + 'static + Send + Sync,
141+
func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + 'static,
143142
) -> Self {
144-
let inner_func = move |ctx: FuncContext<'_>, args: &[WasmValue]| {
145-
let args = args.to_vec();
146-
func(ctx, &args)
147-
};
148-
149-
Self::Function(Function::Host(HostFunction { func: Arc::new(inner_func), ty: ty.clone() }))
143+
Self::Function(Function::Host(HostFunction { func: Rc::new(func), ty: ty.clone() }))
150144
}
151145

152146
/// Create a new typed function import
153-
pub fn typed_func<P, R>(func: impl Fn(FuncContext<'_>, P) -> Result<R> + 'static + Send + Sync) -> Self
147+
// TODO: currently, this is slower than `Extern::func` because of the type conversions.
148+
// we should be able to optimize this and make it even faster than `Extern::func`.
149+
pub fn typed_func<P, R>(func: impl Fn(FuncContext<'_>, P) -> Result<R> + 'static) -> Self
154150
where
155151
P: FromWasmValueTuple + ValTypesFromTuple,
156152
R: IntoWasmValueTuple + ValTypesFromTuple + Debug,
157153
{
158154
let inner_func = move |ctx: FuncContext<'_>, args: &[WasmValue]| -> Result<Vec<WasmValue>> {
159-
let args = P::from_wasm_value_tuple(args.to_vec())?;
155+
let args = P::from_wasm_value_tuple(args)?;
160156
let result = func(ctx, args)?;
161157
Ok(result.into_wasm_value_tuple())
162158
};
163159

164160
let ty = tinywasm_types::FuncType { params: P::val_types(), results: R::val_types() };
165161

166-
Self::Function(Function::Host(HostFunction { func: Arc::new(inner_func), ty }))
162+
Self::Function(Function::Host(HostFunction { func: Rc::new(inner_func), ty }))
167163
}
168164

169165
pub(crate) fn kind(&self) -> ExternalKind {

crates/tinywasm/src/instance.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use alloc::{boxed::Box, format, string::ToString, sync::Arc};
1+
use alloc::{boxed::Box, format, rc::Rc, string::ToString};
22
use tinywasm_types::*;
33

44
use crate::{
@@ -8,11 +8,11 @@ use crate::{
88

99
/// An instanciated WebAssembly module
1010
///
11-
/// Backed by an Arc, so cloning is cheap
11+
/// Backed by an Rc, so cloning is cheap
1212
///
1313
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#module-instances>
1414
#[derive(Debug, Clone)]
15-
pub struct ModuleInstance(Arc<ModuleInstanceInner>);
15+
pub struct ModuleInstance(Rc<ModuleInstanceInner>);
1616

1717
#[allow(dead_code)]
1818
#[derive(Debug)]
@@ -69,7 +69,7 @@ impl ModuleInstance {
6969

7070
let global_addrs = store.init_globals(addrs.globals, data.globals.into(), &addrs.funcs, idx)?;
7171
let (elem_addrs, elem_trapped) =
72-
store.init_elements(&addrs.tables, &addrs.funcs, &global_addrs, data.elements.into(), idx)?;
72+
store.init_elements(&addrs.tables, &addrs.funcs, &global_addrs, &data.elements, idx)?;
7373
let (data_addrs, data_trapped) = store.init_datas(&addrs.memories, data.data.into(), idx)?;
7474

7575
let instance = ModuleInstanceInner {
@@ -126,7 +126,7 @@ impl ModuleInstance {
126126
}
127127

128128
pub(crate) fn new(inner: ModuleInstanceInner) -> Self {
129-
Self(Arc::new(inner))
129+
Self(Rc::new(inner))
130130
}
131131

132132
pub(crate) fn func_ty(&self, addr: FuncAddr) -> &FuncType {

crates/tinywasm/src/store.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ impl Store {
217217
table_addrs: &[TableAddr],
218218
func_addrs: &[FuncAddr],
219219
global_addrs: &[Addr],
220-
elements: Vec<Element>,
220+
elements: &[Element],
221221
idx: ModuleInstanceAddr,
222222
) -> Result<(Box<[Addr]>, Option<Trap>)> {
223223
let elem_count = self.data.elements.len();

crates/tinywasm/tests/testsuite/run.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ impl TestSuite {
413413

414414
AssertReturn { span, exec, results } => {
415415
info!("AssertReturn: {:?}", exec);
416-
let expected = convert_wastret(results)?;
416+
let expected = convert_wastret(results.into_iter())?;
417417

418418
let invoke = match match exec {
419419
wast::WastExecute::Wat(_) => Err(eyre!("wat not supported")),

crates/tinywasm/tests/testsuite/util.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@ pub fn convert_wastargs(args: Vec<wast::WastArg>) -> Result<Vec<tinywasm_types::
6262
args.into_iter().map(|a| wastarg2tinywasmvalue(a)).collect()
6363
}
6464

65-
pub fn convert_wastret(args: Vec<wast::WastRet>) -> Result<Vec<tinywasm_types::WasmValue>> {
66-
args.into_iter().map(|a| wastret2tinywasmvalue(a)).collect()
65+
pub fn convert_wastret<'a>(args: impl Iterator<Item = wast::WastRet<'a>>) -> Result<Vec<tinywasm_types::WasmValue>> {
66+
args.map(|a| wastret2tinywasmvalue(a)).collect()
6767
}
6868

6969
fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result<tinywasm_types::WasmValue> {

crates/types/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -480,7 +480,7 @@ pub struct Element {
480480
pub ty: ValType,
481481
}
482482

483-
#[derive(Debug, Clone, PartialEq)]
483+
#[derive(Debug, Clone, Copy, PartialEq)]
484484
pub enum ElementKind {
485485
Passive,
486486
Active { table: TableAddr, offset: ConstInstruction },

0 commit comments

Comments
 (0)