Skip to main content

rama_error/ext/
opaque.rs

1use core::{convert::Infallible, fmt};
2
3use crate::{BoxError, std::Box};
4
5/// Rarely will you need [`OpaqueError`],
6/// it can however be a useful last-resort in case you
7/// get weird higher-rank Lifetime issues...
8///
9/// Such lifetime issues often arise when using [`BoxError`]
10/// directly as the error for a `BoxService`.
11pub struct OpaqueError(BoxError);
12
13impl OpaqueError {
14    #[inline(always)]
15    pub(super) fn from_box_error(e: impl Into<BoxError>) -> Self {
16        Self(e.into())
17    }
18
19    #[inline(always)]
20    /// Create an opaque error from a static str.
21    ///
22    /// Use this instead of `"msg".context()` or
23    /// some other method that turns it into a BoxError...
24    /// Because the std rust library turns this into a `String` otherwise...
25    pub fn from_static_str(e: &'static str) -> Self {
26        Self(Box::new(StaticStrError(e)))
27    }
28
29    #[inline(always)]
30    /// Unwrap into the inner [`BoxError`].
31    ///
32    /// [`OpaqueError`] is a transparent [`BoxError`] wrapper, so this is free.
33    /// This shadows the generic `into_box_error` added by `ErrorExt` trait.
34    pub fn into_box_error(self) -> BoxError {
35        self.0
36    }
37}
38
39impl fmt::Debug for OpaqueError {
40    #[inline(always)]
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        self.0.fmt(f)
43    }
44}
45
46impl fmt::Display for OpaqueError {
47    #[inline(always)]
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        self.0.fmt(f)
50    }
51}
52
53impl core::error::Error for OpaqueError {
54    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
55        Some(self.0.as_ref())
56    }
57}
58
59impl From<Infallible> for OpaqueError {
60    fn from(infallible: Infallible) -> Self {
61        match infallible {}
62    }
63}
64
65#[derive(Clone, Copy)]
66struct StaticStrError(&'static str);
67
68impl fmt::Debug for StaticStrError {
69    #[inline(always)]
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        self.0.fmt(f)
72    }
73}
74
75impl fmt::Display for StaticStrError {
76    #[inline(always)]
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        self.0.fmt(f)
79    }
80}
81
82impl core::error::Error for StaticStrError {}