diff --git a/core/lib/src/outcome.rs b/core/lib/src/outcome.rs index 8a150306..5b08eca9 100644 --- a/core/lib/src/outcome.rs +++ b/core/lib/src/outcome.rs @@ -597,6 +597,61 @@ impl Outcome { } } + /// Converts `Outcome` to `Result` by identity mapping + /// `Success(S)` and `Failure(E)` to `Result` and mapping `Forward(F)` + /// to `Result` using `f`. + /// + /// ```rust + /// # use rocket::outcome::Outcome; + /// # use rocket::outcome::Outcome::*; + /// # + /// let x: Outcome = Success(10); + /// assert_eq!(x.ok_map_forward(|x| Ok(x as i32 + 1)), Ok(10)); + /// + /// let x: Outcome = Failure("hello"); + /// assert_eq!(x.ok_map_forward(|x| Ok(x as i32 + 1)), Err("hello")); + /// + /// let x: Outcome = Forward(0); + /// assert_eq!(x.ok_map_forward(|x| Ok(x as i32 + 1)), Ok(1)); + /// ``` + #[inline] + pub fn ok_map_forward(self, f: M) -> Result + where M: FnOnce(F) -> Result + { + match self { + Outcome::Success(s) => Ok(s), + Outcome::Failure(e) => Err(e), + Outcome::Forward(v) => f(v), + } + } + + /// Converts `Outcome` to `Result` by identity mapping + /// `Success(S)` and `Forward(F)` to `Result` and mapping `Failure(E)` + /// to `Result` using `f`. + /// + /// ```rust + /// # use rocket::outcome::Outcome; + /// # use rocket::outcome::Outcome::*; + /// # + /// let x: Outcome = Success(10); + /// assert_eq!(x.ok_map_failure(|s| Ok(123)), Ok(10)); + /// + /// let x: Outcome = Failure("hello"); + /// assert_eq!(x.ok_map_failure(|s| Ok(123)), Ok(123)); + /// + /// let x: Outcome = Forward(0); + /// assert_eq!(x.ok_map_failure(|s| Ok(123)), Err(0)); + /// ``` + #[inline] + pub fn ok_map_failure(self, f: M) -> Result + where M: FnOnce(E) -> Result + { + match self { + Outcome::Success(s) => Ok(s), + Outcome::Failure(e) => f(e), + Outcome::Forward(v) => Err(v), + } + } #[inline] fn formatting(&self) -> (Color, &'static str) {