rama_error/ext/
wrapper.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use crate::BoxError;
use std::fmt::{self, Debug, Display};

#[repr(transparent)]
/// A type-erased error type that can be used as a trait object.
///
/// Note this type is not intended to be used directly,
/// it is used by `rama` to hide the concrete error type.
///
/// See the [module level documentation](crate::error) for more information.
pub struct OpaqueError(BoxError);

impl OpaqueError {
    /// create an [`OpaqueError`] from an std error
    pub fn from_std(error: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self(Box::new(error))
    }

    /// create an [`OpaqueError`] from a display object
    pub fn from_display(msg: impl Display + Debug + Send + Sync + 'static) -> Self {
        Self::from_std(MessageError(msg))
    }

    /// create an [`OpaqueError`] from a boxed error
    pub fn from_boxed(inner: BoxError) -> Self {
        Self(inner)
    }

    /// Returns true if the underlying error is of type `T`.
    pub fn is<T>(&self) -> bool
    where
        T: std::error::Error + 'static,
    {
        self.0.is::<T>()
    }

    /// Consumes the [`OpaqueError`] and returns it as a [`BoxError`].
    pub fn into_boxed(self) -> BoxError {
        self.0
    }

    /// Attempts to downcast the error to the concrete type `T`.
    pub fn downcast<T>(self) -> Result<T, Self>
    where
        T: std::error::Error + 'static,
    {
        match self.0.downcast::<T>() {
            Ok(error) => Ok(*error),
            Err(inner) => Err(Self(inner)),
        }
    }

    /// Attempts to downcast the error to a shared reference
    /// of the concrete type `T`.
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: std::error::Error + 'static,
    {
        self.0.downcast_ref()
    }

    /// Attempts to downcast the error to the exclusive reference
    /// of the concrete type `T`.
    pub fn downcast_mut<T>(&mut self) -> Option<&mut T>
    where
        T: std::error::Error + 'static,
    {
        self.0.downcast_mut()
    }
}

impl Debug for OpaqueError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl Display for OpaqueError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl std::error::Error for OpaqueError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        if let Some(err) = self.0.source() {
            return Some(err);
        }
        let err = self.0.as_ref();
        Some(err as &(dyn std::error::Error + 'static))
    }
}

impl From<BoxError> for OpaqueError {
    fn from(error: BoxError) -> Self {
        Self(error)
    }
}

#[repr(transparent)]
/// An error type that wraps a message.
pub(crate) struct MessageError<M>(pub(crate) M);

impl<M> Debug for MessageError<M>
where
    M: Display + Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl<M> Display for MessageError<M>
where
    M: Display + Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<M> std::error::Error for MessageError<M> where M: Display + Debug + 'static {}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug)]
    struct CustomError(usize);

    impl Display for CustomError {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "Custom error ({})", self.0)
        }
    }

    impl std::error::Error for CustomError {}

    #[test]
    fn opaque_error_is() {
        let error = OpaqueError::from_std(CustomError(1));
        assert!(error.is::<CustomError>());
    }

    #[test]
    fn opaque_error_is_not() {
        let error = OpaqueError::from_display("hello");
        assert!(!error.is::<CustomError>());
    }

    #[test]
    fn opaque_error_downcast() {
        let error = OpaqueError::from_std(CustomError(2));
        let custom_error = error.downcast::<CustomError>().unwrap();
        assert_eq!(custom_error.0, 2);
    }

    #[test]
    fn opaque_error_downcast_fail() {
        let error = OpaqueError::from_display("hello");
        assert!(error.downcast::<CustomError>().is_err());
    }

    #[test]
    fn opaque_error_downcast_ref() {
        let error = OpaqueError::from_std(CustomError(3));
        let custom_error = error.downcast_ref::<CustomError>().unwrap();
        assert_eq!(custom_error.0, 3);
    }

    #[test]
    fn opaque_error_downcast_ref_fail() {
        let error = OpaqueError::from_display("hello");
        assert!(error.downcast_ref::<CustomError>().is_none());
    }

    #[test]
    fn opaque_error_downcast_mut() {
        let error = {
            let mut error = OpaqueError::from_std(CustomError(4));
            error.downcast_mut::<CustomError>().unwrap().0 = 42;
            error
        };

        let custom_error = error.downcast_ref::<CustomError>().unwrap();
        assert_eq!(custom_error.0, 42);
    }

    #[test]
    fn opaque_error_downcast_mut_fail() {
        let mut error = OpaqueError::from_display("hello");
        assert!(error.downcast_mut::<CustomError>().is_none());
    }
}