A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add an extension trait for converting `anyhow::Result<T>` into `wasmtime::Result<T>` (#12255)
Nick Fitzgerald3604f54c5ff8
diff --git a/crates/error/src/lib.rs b/crates/error/src/lib.rsindex c6b5ff1d81..8d1ad4c6c1 100644--- a/crates/error/src/lib.rs+++ b/crates/error/src/lib.rs@@ -60,6 +60,8 @@ mod context;mod error;mod oom;mod ptr;+#[cfg(feature = "anyhow")]+mod to_wasmtime_result;mod vtable;#[doc(hidden)]@@ -70,6 +72,8 @@ pub use backtrace::disable_backtrace;pub use context::Context;pub use error::*;pub use oom::OutOfMemory;+#[cfg(feature = "anyhow")]+pub use to_wasmtime_result::ToWasmtimeResult;/// A result of either `Ok(T)` or an [`Err(Error)`][Error].pub type Result<T, E = Error> = core::result::Result<T, E>;diff --git a/crates/error/src/to_wasmtime_result.rs b/crates/error/src/to_wasmtime_result.rsnew file mode 100644index 0000000000..3f19ef8392--- /dev/null+++ b/crates/error/src/to_wasmtime_result.rs@@ -0,0 +1,51 @@+use crate::Result;++/// Extension trait for easily converting `anyhow::Result`s into+/// `wasmtime::Result`s.+///+/// This is a small convenience helper to replace+/// `anyhow_result.map_err(wasmtime::Error::from_anyhow)` with+/// `anyhow_result.to_wasmtime_result()`.+///+/// Requires that the `"anyhow"` cargo feature is enabled.+///+/// # Example+///+/// ```+/// # fn _foo() {+/// #![cfg(feature = "anyhow")]+/// # use wasmtime_internal_error as wasmtime;+/// use wasmtime::ToWasmtimeResult as _;+///+/// fn returns_anyhow_result() -> anyhow::Result<u32> {+/// anyhow::bail!("eep")+/// }+///+/// fn returns_wasmtime_result() -> wasmtime::Result<()> {+/// // The following is equivalent to+/// //+/// // returns_anyhow_result()+/// // .map_err(wasmtime::Error::from_anyhow)?;+/// returns_anyhow_result().to_wasmtime_result()?;+/// Ok(())+/// }+///+/// let error: wasmtime::Error = returns_wasmtime_result().unwrap_err();+/// assert!(error.is::<anyhow::Error>());+/// assert_eq!(error.to_string(), "eep");+/// # }+/// ```+pub trait ToWasmtimeResult<T> {+ /// Convert this `anyhow::Result<T>` into a `wasmtime::Result<T>`.+ fn to_wasmtime_result(self) -> Result<T>;+}++impl<T> ToWasmtimeResult<T> for anyhow::Result<T> {+ #[inline]+ fn to_wasmtime_result(self) -> Result<T> {+ match self {+ Ok(x) => Ok(x),+ Err(e) => out_of_line_slow_path! { Err(crate::Error::from_anyhow(e)) },+ }+ }+}