rspace_core/
error.rs

1/*
2    appellation: error <module>
3    authors: @FL03
4*/
5//! this module defines the core error type for the crate
6
7/// a type alias for a [`Result`](core::result::Result) configured to use the custom [`Error`] type.
8pub type Result<T> = core::result::Result<T, Error>;
9
10/// The custom error type for the crate.
11#[derive(Debug, thiserror::Error)]
12pub enum Error {
13    #[error("The impossible has occurred...")]
14    Infalliable(core::convert::Infallible),
15    #[cfg(feature = "alloc")]
16    #[error(transparent)]
17    BoxError(#[from] alloc::boxed::Box<dyn core::error::Error + Send + Sync + 'static>),
18    #[error(transparent)]
19    FmtError(#[from] core::fmt::Error),
20    #[cfg(feature = "std")]
21    #[error(transparent)]
22    IOError(#[from] std::io::Error),
23    #[cfg(feature = "alloc")]
24    #[error("Unknown Error: {0}")]
25    Unknown(alloc::string::String),
26}
27
28#[cfg(feature = "alloc")]
29mod impl_alloc {
30    use super::Error;
31    use alloc::boxed::Box;
32    use alloc::string::{String, ToString};
33
34    impl Error {
35        pub fn box_error<E>(error: E) -> Self
36        where
37            E: core::error::Error + Send + Sync + 'static,
38        {
39            Self::BoxError(Box::new(error))
40        }
41
42        pub fn unknown<E: ToString>(error: E) -> Self {
43            Self::Unknown(error.to_string())
44        }
45    }
46
47    impl From<&str> for Error {
48        fn from(value: &str) -> Self {
49            Self::Unknown(String::from(value))
50        }
51    }
52
53    impl From<String> for Error {
54        fn from(value: String) -> Self {
55            Self::Unknown(value)
56        }
57    }
58}