wasmtime_types/prelude.rs
1//! Rust module prelude for Wasmtime crates.
2//!
3//! Wasmtime crates that use `no_std` use `core::prelude::*` by default which
4//! does not include `alloc`-related functionality such as `String` and `Vec`.
5//! To have similar ergonomics to `std` and additionally group up some common
6//! functionality this module is intended to be imported at the top of all
7//! modules with:
8//!
9//! ```rust,ignore
10//! use crate::*;
11//! ```
12//!
13//! Externally for crates that depend on `wasmtime-types` they should have this
14//! in the root of the crate:
15//!
16//! ```rust,ignore
17//! use wasmtime_types::prelude;
18//! ```
19//!
20//! and then `use crate::*` works as usual.
21
22pub use alloc::borrow::ToOwned;
23pub use alloc::boxed::Box;
24pub use alloc::format;
25pub use alloc::string::{String, ToString};
26pub use alloc::vec;
27pub use alloc::vec::Vec;
28pub use wasmparser::collections::{IndexMap, IndexSet};
29
30/// Convenience trait for converting `Result<T, E>` into `anyhow::Result<T>`
31///
32/// Typically this is automatically done with the `?` operator in Rust and
33/// by default this trait isn't necessary. With the `anyhow` crate's `std`
34/// feature disabled, however, the `?` operator won't work because the `Error`
35/// trait is not defined. This trait helps to bridge this gap.
36///
37/// This does the same thing as `?` when the `std` feature is enabled, and when
38/// `std` is disabled it'll use different trait bounds to create an
39/// `anyhow::Error`.
40///
41/// This trait is not suitable as a public interface because features change
42/// what implements the trait. It's good enough for a wasmtime internal
43/// implementation detail, however.
44pub trait Err2Anyhow<T> {
45 /// Convert `self` to `anyhow::Result<T>`.
46 fn err2anyhow(self) -> anyhow::Result<T>;
47}
48
49impl<T, E: IntoAnyhow> Err2Anyhow<T> for Result<T, E> {
50 fn err2anyhow(self) -> anyhow::Result<T> {
51 match self {
52 Ok(e) => Ok(e),
53 Err(e) => Err(e.into_anyhow()),
54 }
55 }
56}
57
58/// Convenience trait to convert a value into `anyhow::Error`
59///
60/// This trait is not a suitable public interface of Wasmtime so it's just an
61/// internal implementation detail for now. This trait is conditionally
62/// implemented on the `std` feature with different bounds.
63pub trait IntoAnyhow {
64 /// Converts `self` into an `anyhow::Error`.
65 fn into_anyhow(self) -> anyhow::Error;
66}
67
68#[cfg(feature = "std")]
69impl<T> IntoAnyhow for T
70where
71 T: Into<anyhow::Error>,
72{
73 fn into_anyhow(self) -> anyhow::Error {
74 self.into()
75 }
76}
77
78#[cfg(not(feature = "std"))]
79impl<T> IntoAnyhow for T
80where
81 T: core::fmt::Display + core::fmt::Debug + Send + Sync + 'static,
82{
83 fn into_anyhow(self) -> anyhow::Error {
84 anyhow::Error::msg(self)
85 }
86}