|
| 1 | +extern crate eel_wasm; |
| 2 | + |
| 3 | +use wasmi::nan_preserving_float::F64; |
| 4 | +use wasmi::RuntimeValue; |
| 5 | +use wasmi::{ |
| 6 | + Error as WasmiError, Externals, FuncInstance, FuncRef, GlobalDescriptor, GlobalInstance, |
| 7 | + GlobalRef, ModuleImportResolver, RuntimeArgs, Signature, Trap, ValueType, |
| 8 | +}; |
| 9 | + |
| 10 | +pub struct GlobalPool {} |
| 11 | + |
| 12 | +impl GlobalPool { |
| 13 | + fn check_signature(&self, index: usize, signature: &Signature) -> bool { |
| 14 | + let (params, ret_ty): (&[ValueType], Option<ValueType>) = match index { |
| 15 | + SIN_FUNC_INDEX => (&[ValueType::F64], Some(ValueType::F64)), |
| 16 | + _ => return false, |
| 17 | + }; |
| 18 | + signature.params() == params && signature.return_type() == ret_ty |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +impl ModuleImportResolver for GlobalPool { |
| 23 | + fn resolve_global( |
| 24 | + &self, |
| 25 | + _field_name: &str, |
| 26 | + _global_type: &GlobalDescriptor, |
| 27 | + ) -> Result<GlobalRef, WasmiError> { |
| 28 | + let global = GlobalInstance::alloc(RuntimeValue::F64(F64::from_float(0.0)), true); |
| 29 | + Ok(global) |
| 30 | + } |
| 31 | + fn resolve_func(&self, field_name: &str, signature: &Signature) -> Result<FuncRef, WasmiError> { |
| 32 | + let index = match field_name { |
| 33 | + "sin" => SIN_FUNC_INDEX, |
| 34 | + _ => { |
| 35 | + return Err(WasmiError::Instantiation(format!( |
| 36 | + "Export {} not found", |
| 37 | + field_name |
| 38 | + ))) |
| 39 | + } |
| 40 | + }; |
| 41 | + |
| 42 | + if !self.check_signature(index, signature) { |
| 43 | + return Err(WasmiError::Instantiation(format!( |
| 44 | + "Export {} has a bad signature", |
| 45 | + field_name |
| 46 | + ))); |
| 47 | + } |
| 48 | + |
| 49 | + Ok(FuncInstance::alloc_host( |
| 50 | + Signature::new(&[ValueType::F64][..], Some(ValueType::F64)), |
| 51 | + index, |
| 52 | + )) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +const SIN_FUNC_INDEX: usize = 0; |
| 57 | + |
| 58 | +impl Externals for GlobalPool { |
| 59 | + fn invoke_index( |
| 60 | + &mut self, |
| 61 | + index: usize, |
| 62 | + args: RuntimeArgs, |
| 63 | + ) -> Result<Option<RuntimeValue>, Trap> { |
| 64 | + match index { |
| 65 | + SIN_FUNC_INDEX => { |
| 66 | + let a: F64 = args.nth_checked(0)?; |
| 67 | + |
| 68 | + let result = a.to_float().sin(); |
| 69 | + |
| 70 | + Ok(Some(RuntimeValue::F64(F64::from(result)))) |
| 71 | + } |
| 72 | + _ => panic!("Unimplemented function at {}", index), |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments