Add wasm extern type trait

This commit is contained in:
Lachlan Sneff
2019-02-01 13:10:59 -08:00
parent 73125edd61
commit c0a17f73bf
2 changed files with 28 additions and 31 deletions

View File

@ -17,49 +17,21 @@ macro_rules! func {
($func:ident, [ $( $params:ident ),* ] -> [ $( $returns:ident ),* ] ) => {{
use $crate::{
export::{Context, Export, FuncPointer},
types::{FuncSig, Type},
types::{FuncSig, Type, WasmExternType},
vm,
};
let func: extern fn( $( $params, )* &mut vm::Ctx) -> ($( $returns )*) = $func;
Export::Function {
func: unsafe { FuncPointer::new(func as _) },
ctx: Context::Internal,
signature: FuncSig::new(
&[$($crate::__export_func_convert_type!($params),)*] as &[Type],
&[$($crate::__export_func_convert_type!($returns),)*] as &[Type],
&[ $( <$params as WasmExternType>::TYPE, )* ] as &[Type],
&[ $( <$returns as WasmExternType>::TYPE, )* ] as &[Type],
).into(),
}
}};
}
#[macro_export]
#[doc(hidden)]
macro_rules! __export_func_convert_type {
(i32) => {
Type::I32
};
(u32) => {
Type::I32
};
(i64) => {
Type::I64
};
(u64) => {
Type::I64
};
(f32) => {
Type::F32
};
(f64) => {
Type::F64
};
($x:ty) => {
compile_error!("Only `i32`, `u32`, `i64`, `u64`, `f32`, and `f64` are supported for argument and return types")
};
}
/// Generate an [`ImportObject`] safely.
///
/// [`ImportObject`]: struct.ImportObject.html

View File

@ -65,6 +65,31 @@ impl From<f64> for Value {
}
}
pub unsafe trait WasmExternType: Copy + Clone
where
Self: Sized,
{
const TYPE: Type;
}
unsafe impl WasmExternType for i32 {
const TYPE: Type = Type::I32;
}
unsafe impl WasmExternType for u32 {
const TYPE: Type = Type::I32;
}
unsafe impl WasmExternType for i64 {
const TYPE: Type = Type::I64;
}
unsafe impl WasmExternType for u64 {
const TYPE: Type = Type::I64;
}
unsafe impl WasmExternType for f32 {
const TYPE: Type = Type::F32;
}
unsafe impl WasmExternType for f64 {
const TYPE: Type = Type::F64;
}
pub enum ValueError {
BufferTooSmall,
}