1use alloc::{boxed::Box, string::String};
2use core::ffi;
3use wasmi::Error;
4
5type Result<T> = core::result::Result<T, wasmi::Error>;
6
7#[repr(C)]
11pub struct wasmi_error_t {
12 inner: Error,
13}
14
15wasmi_c_api_macros::declare_own!(wasmi_error_t);
16
17impl From<Error> for wasmi_error_t {
18 fn from(error: Error) -> wasmi_error_t {
19 Self { inner: error }
20 }
21}
22
23impl From<wasmi_error_t> for Error {
24 fn from(error: wasmi_error_t) -> Error {
25 error.inner
26 }
27}
28
29#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
33#[allow(clippy::not_unsafe_ptr_arg_deref)] pub extern "C" fn wasmi_error_new(msg: *const ffi::c_char) -> Option<Box<wasmi_error_t>> {
35 let msg_bytes = unsafe { ffi::CStr::from_ptr(msg) };
36 let msg_string = String::from_utf8_lossy(msg_bytes.to_bytes()).into_owned();
37 Some(Box::new(wasmi_error_t::from(Error::new(msg_string))))
38}
39
40pub(crate) fn handle_result<T>(
42 result: Result<T>,
43 ok_then: impl FnOnce(T),
44) -> Option<Box<wasmi_error_t>> {
45 match result {
46 Ok(value) => {
47 ok_then(value);
48 None
49 }
50 Err(error) => Some(Box::new(wasmi_error_t::from(error))),
51 }
52}