Skip to main content

ps_util/conversions/
result.rs

1/// Convenience constructors for `Result` and `Option` values.
2#[allow(clippy::missing_errors_doc)]
3pub trait ToResult {
4    /// Wraps `self` in `Ok(self)`.
5    #[inline]
6    fn ok<Err>(self) -> Result<Self, Err>
7    where
8        Self: Sized,
9    {
10        Ok(self)
11    }
12
13    /// Wraps `self` in `Err(self)`.
14    #[inline]
15    fn err<Any>(self) -> Result<Any, Self>
16    where
17        Self: Sized,
18    {
19        Err(self)
20    }
21
22    /// Wraps `self` in `Some(self)`.
23    #[inline]
24    fn some(self) -> Option<Self>
25    where
26        Self: Sized,
27    {
28        Some(self)
29    }
30}
31
32impl<T> ToResult for T {}
33
34/// Conversions between `Result` and `Option` with optional value transformation.
35pub trait ResConv<T, E> {
36    /// Converts into `Option<T>`, dropping any error information.
37    fn into_option(self) -> Option<T>;
38
39    /// Converts into `Result<T, E>`.
40    ///
41    /// # Errors
42    /// Returns `Err(E)` when the source value represents an absent or failed state.
43    fn into_result(self) -> Result<T, E>;
44}
45
46impl<Input, Output, Err> ResConv<Output, Err> for Result<Input, Err>
47where
48    Input: Into<Output>,
49{
50    #[inline]
51    fn into_option(self) -> Option<Output> {
52        self.map(Into::into).ok()
53    }
54
55    #[inline]
56    fn into_result(self) -> Result<Output, Err> {
57        self.map(Into::into)
58    }
59}
60
61impl<Input, Output, Err: Default> ResConv<Output, Err> for Option<Input>
62where
63    Input: Into<Output>,
64{
65    #[inline]
66    fn into_option(self) -> Option<Output> {
67        self.map(Into::into)
68    }
69
70    /// - Transforms `Some(T)` into `Ok(T)`.
71    /// - Transforms `None` into `Err(Err::Default())`
72    ///
73    /// # Errors
74    /// - Returns `Err(Err::Default())` if `self` is `None`.
75    #[inline]
76    fn into_result(self) -> Result<Output, Err> {
77        self.map(Into::into).ok_or_else(Err::default)
78    }
79}