[go: up one dir, main page]

failure/
compat.rs

1use core::fmt::{self, Display};
2
3/// A compatibility wrapper around an error type from this crate.
4///
5/// `Compat` implements `std::error::Error`, allowing the types from this
6/// crate to be passed to interfaces that expect a type of that trait.
7#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
8pub struct Compat<E> {
9    pub(crate) error: E,
10}
11
12impl<E: Display> Display for Compat<E> {
13    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
14        Display::fmt(&self.error, f)
15    }
16}
17
18impl<E> Compat<E> {
19    /// Unwraps this into the inner error.
20    pub fn into_inner(self) -> E {
21        self.error
22    }
23
24    /// Gets a reference to the inner error.
25    pub fn get_ref(&self) -> &E {
26        &self.error
27    }
28}
29
30with_std! {
31    use std::fmt::Debug;
32    use std::error::Error as StdError;
33
34    use Error;
35
36    impl<E: Display + Debug> StdError for Compat<E> {
37        fn description(&self) -> &'static str {
38            "An error has occurred."
39        }
40    }
41
42    impl From<Error> for Box<dyn StdError> {
43        fn from(error: Error) -> Box<dyn StdError> {
44            Box::new(Compat { error })
45        }
46    }
47
48    impl From<Error> for Box<dyn StdError + Send + Sync> {
49        fn from(error: Error) -> Box<dyn StdError + Send + Sync> {
50            Box::new(Compat { error })
51        }
52    }
53}