|
| 1 | +/// A stable version of [`core::ops::Try`]. |
| 2 | +pub trait Try { |
| 3 | + /// The type of this value when viewed as successful. |
| 4 | + type Ok; |
| 5 | + /// The type of this value when viewed as failed. |
| 6 | + type Error; |
| 7 | + |
| 8 | + /// A return of `Ok(t)` means that the |
| 9 | + /// execution should continue normally, and the result of `?` is the |
| 10 | + /// value `t`. A return of `Err(e)` means that execution should branch |
| 11 | + /// to the innermost enclosing `catch`, or return from the function. |
| 12 | + fn into_result(self) -> Result<Self::Ok, Self::Error>; |
| 13 | + |
| 14 | + /// Wrap an error value to construct the composite result. For example, |
| 15 | + /// `Result::Err(x)` and `Result::from_error(x)` are equivalent. |
| 16 | + fn from_error(v: Self::Error) -> Self; |
| 17 | + |
| 18 | + /// Wrap an OK value to construct the composite result. For example, |
| 19 | + /// `Result::Ok(x)` and `Result::from_ok(x)` are equivalent. |
| 20 | + fn from_ok(v: Self::Ok) -> Self; |
| 21 | +} |
| 22 | + |
| 23 | +impl<T, E> Try for Result<T, E> { |
| 24 | + type Ok = T; |
| 25 | + type Error = E; |
| 26 | + |
| 27 | + fn into_result(self) -> Result<<Self as Try>::Ok, <Self as Try>::Error> { |
| 28 | + self |
| 29 | + } |
| 30 | + fn from_error(v: <Self as Try>::Error) -> Self { |
| 31 | + Err(v) |
| 32 | + } |
| 33 | + fn from_ok(v: <Self as Try>::Ok) -> Self { |
| 34 | + Ok(v) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/// The error type that results from applying the try operator (`?`) to a `None` value. |
| 39 | +pub struct NoneError; |
| 40 | + |
| 41 | +impl<T> Try for Option<T> { |
| 42 | + type Ok = T; |
| 43 | + type Error = NoneError; |
| 44 | + |
| 45 | + fn into_result(self) -> Result<<Self as Try>::Ok, <Self as Try>::Error> { |
| 46 | + self.ok_or(NoneError) |
| 47 | + } |
| 48 | + fn from_error(_v: <Self as Try>::Error) -> Self { |
| 49 | + None |
| 50 | + } |
| 51 | + fn from_ok(v: <Self as Try>::Ok) -> Self { |
| 52 | + Some(v) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +/// Unwraps a result or propagates its error. |
| 57 | +#[macro_export] |
| 58 | +macro_rules! r#try { |
| 59 | + ($expr:expr) => { |
| 60 | + match $crate::Try::into_result($expr) { |
| 61 | + Ok(val) => val, |
| 62 | + Err(err) => return $crate::Try::from_error(::core::convert::From::from(err)), |
| 63 | + } |
| 64 | + }; |
| 65 | + ($expr:expr,) => { |
| 66 | + $crate::r#try!($expr) |
| 67 | + }; |
| 68 | +} |
0 commit comments