From 1ae1bfc101354019b5db3e45e025e5a0976112fe Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Sat, 23 Dec 2017 20:23:03 -0800 Subject: [PATCH] Add 'success_or' methods to 'Outcome'. --- lib/src/outcome.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/lib/src/outcome.rs b/lib/src/outcome.rs index 9e8c8f52..fa572e31 100644 --- a/lib/src/outcome.rs +++ b/lib/src/outcome.rs @@ -342,6 +342,61 @@ impl Outcome { } } + /// Converts from `Outcome` to `Result` for a given `T`. + /// + /// Returns `Ok` with the `Success` value if this is a `Success`, otherwise + /// returns an `Err` with the provided value. `self` is consumed, and all + /// other values are discarded. + /// + /// ```rust + /// # use rocket::outcome::Outcome; + /// # use rocket::outcome::Outcome::*; + /// # + /// let x: Outcome = Success(10); + /// assert_eq!(x.success_or(false), Ok(10)); + /// + /// let x: Outcome = Failure("Hi! I'm an error."); + /// assert_eq!(x.success_or(false), Err(false)); + /// + /// let x: Outcome = Forward(25); + /// assert_eq!(x.success_or("whoops"), Err("whoops")); + /// ``` + #[inline] + pub fn success_or(self, value: T) -> Result { + match self { + Success(val) => Ok(val), + _ => Err(value) + } + } + + /// Converts from `Outcome` to `Result` for a given `T` + /// produced from a supplied function or closure. + /// + /// Returns `Ok` with the `Success` value if this is a `Success`, otherwise + /// returns an `Err` with the result of calling `f`. `self` is consumed, and + /// all other values are discarded. + /// + /// ```rust + /// # use rocket::outcome::Outcome; + /// # use rocket::outcome::Outcome::*; + /// # + /// let x: Outcome = Success(10); + /// assert_eq!(x.success_or_else(|| false), Ok(10)); + /// + /// let x: Outcome = Failure("Hi! I'm an error."); + /// assert_eq!(x.success_or_else(|| false), Err(false)); + /// + /// let x: Outcome = Forward(25); + /// assert_eq!(x.success_or_else(|| "whoops"), Err("whoops")); + /// ``` + #[inline] + pub fn success_or_else T>(self, f: V) -> Result { + match self { + Success(val) => Ok(val), + _ => Err(f()) + } + } + /// Converts from `Outcome` to `Outcome<&S, &E, &F>`. /// /// ```rust