try_unwrap/
lib.rs

1/// Trait for implementing `try_unwrap()` on the generic `Result<T, E>` type.
2pub trait TryUnwrapResult {
3    type T;
4    type E;
5    fn try_unwrap(self) -> Result<Self::T, Self::E>;
6}
7
8impl<T, E> TryUnwrapResult for Result<T, E> {
9    type T = T;
10    type E = E;
11
12    /// Unwraps and returns the contained value if it is an `Ok`. 
13    /// Otherwise, it returns an `Err`.
14    /// ```
15    /// let ok: Result<i32, ()> = Ok(3);
16    /// assert_eq!(ok.try_unwrap(), Ok(3));
17    /// let err: Result<(), i32> = Err(2);
18    /// assert_eq!(err.try_unwrap(), Err(2));
19    /// ```
20    fn try_unwrap(self) -> Result<T, E> {
21        if self.is_ok() {
22            unsafe { Ok(self.unwrap_unchecked()) }
23        } else {
24            unsafe { Err(self.unwrap_err_unchecked()) }
25        }
26    }
27}
28
29/// Trait for implementing `try_unwrap()` on the generic `Option<T>` type.
30pub trait TryUnwrapOption {
31    type T;
32    fn try_unwrap(self) -> Option<Self::T>;
33}
34
35impl<T> TryUnwrapOption for Option<T> {
36    type T = T;
37
38    /// Unwraps and returns the contained value if it is a `Some`. 
39    /// Otherwise, it returns a `None`.
40    /// ```
41    /// let some: Option<i32> = Some(4);
42    /// assert_eq!(some.try_unwrap(), Some(4));
43    /// let none: Option<i32> = None;
44    /// assert_eq!(none.try_unwrap(), None);
45    /// ````
46    fn try_unwrap(self) -> Option<T> {
47        if self.is_some() {
48            unsafe { Some(self.unwrap_unchecked()) }
49        } else {
50            None
51        }
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_result() {
61        let ok: Result<i32, ()> = Ok(3);
62        assert_eq!(ok.try_unwrap(), Ok(3));
63
64        let err: Result<(), i32> = Err(2);
65        assert_eq!(err.try_unwrap(), Err(2));
66    }
67
68    #[test]
69    fn test_option() {
70        let some: Option<i32> = Some(4);
71        assert_eq!(some.try_unwrap(), Some(4));
72
73        let none: Option<i32> = None;
74        assert_eq!(none.try_unwrap(), None);
75    }
76}