Skip to main content

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/// Returns `None` if `msg` is `null`.
32///
33/// Wraps [`wasmi::Error::new`].
34#[cfg_attr(not(feature = "prefix-symbols"), unsafe(no_mangle))]
35#[allow(clippy::not_unsafe_ptr_arg_deref)] // clippy 0.1.79 (129f3b99 2024-06-10): incorrectly reports a bug here
36pub 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
45/// Convenience method, applies `ok_then(T)` if `result` is `Ok` and otherwise returns a [`wasmi_error_t`].
46pub(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}