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"), unsafe(no_mangle))]
35#[allow(clippy::not_unsafe_ptr_arg_deref)] pub extern "C" fn wasmi_error_new(msg: *const ffi::c_char) -> Option<Box<wasmi_error_t>> {
37 if msg.is_null() {
38 return None;
39 }
40 let msg_bytes = unsafe { ffi::CStr::from_ptr(msg) };
41 let msg_string = String::from_utf8_lossy(msg_bytes.to_bytes()).into_owned();
42 Some(Box::new(wasmi_error_t::from(Error::new(msg_string))))
43}
44
45pub(crate) fn handle_result<T>(
47 result: Result<T>,
48 ok_then: impl FnOnce(T),
49) -> Option<Box<wasmi_error_t>> {
50 match result {
51 Ok(value) => {
52 ok_then(value);
53 None
54 }
55 Err(error) => Some(Box::new(wasmi_error_t::from(error))),
56 }
57}