Skip to main content

error_kind/traits/
option_ext.rs

1// =============================================================================
2// USES
3// =============================================================================
4
5// -----------------------------------------------------------------------------
6use crate::{Context, Error, ErrorKind, TrivialError};
7
8// =============================================================================
9// SEALED
10// =============================================================================
11
12// -----------------------------------------------------------------------------
13mod sealed {
14    pub trait Sealed {}
15    impl<E: super::Error> Sealed for Option<E> {}
16}
17
18// =============================================================================
19// TRAITS
20// =============================================================================
21
22/// Extension functions for `Option<T>` when `T` is an [`Error`].
23pub trait OptionExt: sealed::Sealed {
24    /// The error type associated with this option (`Some(_)`).
25    type Error: Error;
26
27    /// Convert an option from some foreign error, capturing the error context.
28    ///
29    /// This is equivalent to the following code:
30    ///
31    /// ```
32    /// # use error_kind::{Error, ErrorContext, ErrorKind, ResultExt, TrivialError};
33    /// # #[derive(Clone, Copy, Debug, ErrorKind)]
34    /// # enum MyErrorKind { Variant }
35    /// # #[derive(Clone, Copy, Debug, Error)]
36    /// # struct TargetError(MyErrorKind);
37    /// # let option = Option::<std::io::Error>::None;
38    /// # let error_kind = MyErrorKind::Variant;
39    /// # let end_option: Option<TargetError> =
40    /// match option {
41    ///     Some(error) => Some(
42    ///         TargetError::new(error_kind.into()).with_context(|| error)
43    ///     ),
44    ///     None => None,
45    /// }
46    /// # ;
47    /// ```
48    fn capture<E, K>(error_kind: K, option: Option<E>) -> Self
49    where
50        E: Context,
51        K: ErrorKind + Into<<Self::Error as Error>::Kind>,
52        Self::Error: TrivialError;
53
54    /// Convert an option from some foreign error.
55    ///
56    /// This is equivalent to the following code:
57    ///
58    /// ```
59    /// # use error_kind::{Error, ErrorContext, ErrorKind, ResultExt, TrivialError};
60    /// # #[derive(Clone, Copy, Debug, ErrorKind)]
61    /// # enum MyErrorKind { Variant }
62    /// # #[derive(Clone, Copy, Debug, Error)]
63    /// # struct TargetError(MyErrorKind);
64    /// # let option = Option::<std::io::Error>::None;
65    /// # let error_kind = MyErrorKind::Variant;
66    /// # let end_option: Option<TargetError> =
67    /// match option {
68    ///     Some(error) => Some(TargetError::new(error_kind.into())),
69    ///     None => None,
70    /// }
71    /// # ;
72    /// ```
73    fn convert<E, K>(error_kind: K, option: Option<E>) -> Self
74    where
75        E: Context,
76        K: ErrorKind + Into<<Self::Error as Error>::Kind>,
77        Self::Error: TrivialError;
78
79    /// Provide human-readable information about why an error occurred.
80    ///
81    /// This is a wrapper which redirects to [`ErrorContext::with_context`] for
82    /// the wrapped `Some(value)`. If the `Option` is `None`, this information
83    /// is discarded.
84    ///
85    /// [`ErrorContext::with_context`]: crate::ErrorContext::with_context
86    fn with_context<C, F>(self, context: F) -> Self
87    where
88        C: Context,
89        F: FnOnce() -> C;
90}
91
92// =============================================================================
93// TRAIT IMPLS
94// =============================================================================
95
96// -----------------------------------------------------------------------------
97impl<E> OptionExt for Option<E>
98where
99    E: Error,
100{
101    type Error = E;
102
103    #[allow(clippy::manual_map)] // Messes with #[track_caller]
104    #[track_caller]
105    #[inline]
106    fn capture<E2, K>(error_kind: K, option: Option<E2>) -> Self
107    where
108        E2: Context,
109        K: ErrorKind + Into<<Self::Error as Error>::Kind>,
110        Self::Error: TrivialError,
111    {
112        match option {
113            Some(err) => Some(Self::Error::new(error_kind.into()).with_context(|| err)),
114            None => None,
115        }
116    }
117
118    #[allow(clippy::manual_map)] // Messes with #[track_caller]
119    #[track_caller]
120    #[inline]
121    fn convert<E2, K>(error_kind: K, option: Option<E2>) -> Self
122    where
123        E2: Context,
124        K: ErrorKind + Into<<Self::Error as Error>::Kind>,
125        Self::Error: TrivialError,
126    {
127        match option {
128            Some(_) => Some(Self::Error::new(error_kind.into())),
129            None => None,
130        }
131    }
132
133    #[allow(clippy::manual_map)] // Messes with #[track_caller]
134    #[track_caller]
135    #[inline]
136    fn with_context<C, F>(self, context: F) -> Self
137    where
138        C: Context,
139        F: FnOnce() -> C,
140    {
141        match self {
142            None => None,
143            Some(err) => Some(err.with_context(context)),
144        }
145    }
146}