wasmi_c_api/
error.rs

1use alloc::{boxed::Box, string::String};
2use core::ffi;
3use wasmi::Error;
4
5type Result<T> = core::result::Result<T, wasmi::Error>;
6
7/// An error that may occur when operating with Wasmi.
8///
9/// Wraps [`wasmi::Error`].
10#[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/// Creates a new [`wasmi_error_t`] with the given error message.
30///
31/// Wraps [`wasmi::Error::new`].
32#[cfg_attr(not(feature = "prefix-symbols"), no_mangle)]
33#[allow(clippy::not_unsafe_ptr_arg_deref)] // clippy 0.1.79 (129f3b99 2024-06-10): incorrectly reports a bug here
34pub 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
40/// Convenience method, applies `ok_then(T)` if `result` is `Ok` and otherwise returns a [`wasmi_error_t`].
41pub(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}