1 use crate::{wasm_name_t, wasm_trap_t};
2 use anyhow::{anyhow, Error, Result};
3 use wasmtime::{Store, Trap};
4 
5 #[repr(C)]
6 pub struct wasmtime_error_t {
7     error: Error,
8 }
9 
10 wasmtime_c_api_macros::declare_own!(wasmtime_error_t);
11 
12 impl wasmtime_error_t {
to_trap(self, store: &Store) -> Box<wasm_trap_t>13     pub(crate) fn to_trap(self, store: &Store) -> Box<wasm_trap_t> {
14         Box::new(wasm_trap_t::new(store, Trap::from(self.error)))
15     }
16 }
17 
18 impl From<Error> for wasmtime_error_t {
from(error: Error) -> wasmtime_error_t19     fn from(error: Error) -> wasmtime_error_t {
20         wasmtime_error_t { error }
21     }
22 }
23 
handle_result<T>( result: Result<T>, ok: impl FnOnce(T), ) -> Option<Box<wasmtime_error_t>>24 pub(crate) fn handle_result<T>(
25     result: Result<T>,
26     ok: impl FnOnce(T),
27 ) -> Option<Box<wasmtime_error_t>> {
28     match result {
29         Ok(value) => {
30             ok(value);
31             None
32         }
33         Err(error) => Some(Box::new(wasmtime_error_t { error })),
34     }
35 }
36 
bad_utf8() -> Option<Box<wasmtime_error_t>>37 pub(crate) fn bad_utf8() -> Option<Box<wasmtime_error_t>> {
38     Some(Box::new(wasmtime_error_t {
39         error: anyhow!("input was not valid utf-8"),
40     }))
41 }
42 
43 #[no_mangle]
wasmtime_error_message(error: &wasmtime_error_t, message: &mut wasm_name_t)44 pub extern "C" fn wasmtime_error_message(error: &wasmtime_error_t, message: &mut wasm_name_t) {
45     message.set_buffer(format!("{:?}", error.error).into_bytes());
46 }
47