1 use crate::error::Result;
2 
3 /// Extension trait for easily converting `anyhow::Result`s into
4 /// `wasmtime::Result`s.
5 ///
6 /// This is a small convenience helper to replace
7 /// `anyhow_result.map_err(wasmtime::Error::from_anyhow)` with
8 /// `anyhow_result.to_wasmtime_result()`.
9 ///
10 /// Requires that the `"anyhow"` cargo feature is enabled.
11 ///
12 /// # Example
13 ///
14 /// ```
15 /// # fn _foo() {
16 /// #![cfg(feature = "anyhow")]
17 /// # use wasmtime_internal_core::error as wasmtime;
18 /// use wasmtime::ToWasmtimeResult as _;
19 ///
20 /// fn returns_anyhow_result() -> anyhow::Result<u32> {
21 ///     anyhow::bail!("eep")
22 /// }
23 ///
24 /// fn returns_wasmtime_result() -> wasmtime::Result<()> {
25 ///     // The following is equivalent to
26 ///     //
27 ///     //     returns_anyhow_result()
28 ///     //         .map_err(wasmtime::Error::from_anyhow)?;
29 ///     returns_anyhow_result().to_wasmtime_result()?;
30 ///     Ok(())
31 /// }
32 ///
33 /// let error: wasmtime::Error = returns_wasmtime_result().unwrap_err();
34 /// assert!(error.is::<anyhow::Error>());
35 /// assert_eq!(error.to_string(), "eep");
36 /// # }
37 /// ```
38 pub trait ToWasmtimeResult<T> {
39     /// Convert this `anyhow::Result<T>` into a `wasmtime::Result<T>`.
to_wasmtime_result(self) -> Result<T>40     fn to_wasmtime_result(self) -> Result<T>;
41 }
42 
43 #[cfg(feature = "anyhow")]
44 impl<T> ToWasmtimeResult<T> for anyhow::Result<T> {
45     #[inline]
to_wasmtime_result(self) -> Result<T>46     fn to_wasmtime_result(self) -> Result<T> {
47         match self {
48             Ok(x) => Ok(x),
49             Err(e) => Err(crate::error::Error::from_anyhow(e)),
50         }
51     }
52 }
53 
54 impl<T> ToWasmtimeResult<T> for Result<T> {
55     #[inline]
to_wasmtime_result(self) -> Result<T>56     fn to_wasmtime_result(self) -> Result<T> {
57         self
58     }
59 }
60