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