Skip to main content

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