ps_util/conversions/
result.rs

1#[allow(clippy::missing_errors_doc)]
2pub trait ToResult {
3    #[inline]
4    fn ok<Err>(self) -> Result<Self, Err>
5    where
6        Self: Sized,
7    {
8        Ok(self)
9    }
10
11    #[inline]
12    fn err<Any>(self) -> Result<Any, Self>
13    where
14        Self: Sized,
15    {
16        Err(self)
17    }
18
19    #[inline]
20    fn some(self) -> Option<Self>
21    where
22        Self: Sized,
23    {
24        Some(self)
25    }
26}
27
28impl<T> ToResult for T {}
29
30#[allow(clippy::missing_errors_doc)]
31pub trait ResConv<T, E> {
32    fn into_option(self) -> Option<T>;
33    fn into_result(self) -> Result<T, E>;
34}
35
36impl<Input, Output, Err> ResConv<Output, Err> for Result<Input, Err>
37where
38    Input: Into<Output>,
39{
40    #[inline]
41    fn into_option(self) -> Option<Output> {
42        self.map_or_else(|_| None, |value| value.into().some())
43    }
44
45    #[inline]
46    fn into_result(self) -> Result<Output, Err> {
47        match self {
48            Ok(value) => value.into().ok(),
49            Err(err) => err.err(),
50        }
51    }
52}
53
54impl<Input, Output, Err: Default> ResConv<Output, Err> for Option<Input>
55where
56    Input: Into<Output>,
57{
58    #[inline]
59    fn into_option(self) -> Option<Output> {
60        self.map_or_else(|| None, |value| value.into().some())
61    }
62
63    /// - Transforms `Some(T)` into `Ok(T)`.
64    /// - Transforms `None` into `Err(Err::Default())`
65    ///
66    /// # Errors
67    /// - Returns `Err(Err::Default())` if `self` is `None`.
68    #[inline]
69    fn into_result(self) -> Result<Output, Err> {
70        self.map_or_else(|| Err::default().err(), |value| value.into().ok())
71    }
72}