From 553d4e346e4a70e32d5904dc75c2aaddcb1c1869 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Wed, 19 May 2021 08:21:46 -0700 Subject: [PATCH 1/2] Fix the types in the FromResidual implementation And while I was there, tweak the code to remove the need for some `#[allow]`s. --- core/lib/src/outcome.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/core/lib/src/outcome.rs b/core/lib/src/outcome.rs index 171c18605b..992f4fad80 100644 --- a/core/lib/src/outcome.rs +++ b/core/lib/src/outcome.rs @@ -603,11 +603,10 @@ impl Outcome { } } -impl, F> FromResidual> for Outcome { - fn from_residual(r: Result) -> Self { - #[allow(unreachable_code)] +impl, F> FromResidual> for Outcome { + fn from_residual(r: Result) -> Self { match r { - Ok(v) => Outcome::Success(v), + Ok(never) => match never {}, Err(y) => Outcome::Failure(y.into()), } } @@ -615,9 +614,8 @@ impl, F> FromResidual> for Outcome { impl, Y, F: From> FromResidual> for Outcome { fn from_residual(r: Outcome) -> Self { - #[allow(unreachable_code)] match r { - Outcome::Success(s) => Outcome::Success(s), + Outcome::Success(never) => match never {}, Outcome::Failure(x) => Outcome::Failure(x.into()), Outcome::Forward(y) => Outcome::Forward(y.into()), } @@ -654,3 +652,17 @@ impl fmt::Display for Outcome { write!(f, "{}", Paint::default(string).fg(color)) } } + +#[cfg(test)] +mod test { + use super::Outcome::{self, *}; + + #[test] + fn can_use_question_mark_on_result_in_function_returning_outcome() { + fn demo() -> Outcome { + Err("problem")?; + unreachable!() + } + assert_eq!(demo(), Failure(String::from("problem"))); + } +} From e5018f3e036a121e412faf20fcbf8b017d07f6e9 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Wed, 19 May 2021 09:10:37 -0700 Subject: [PATCH 2/2] Test all the Outcome variants with ? --- core/lib/src/outcome.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/core/lib/src/outcome.rs b/core/lib/src/outcome.rs index 992f4fad80..bce210b0b8 100644 --- a/core/lib/src/outcome.rs +++ b/core/lib/src/outcome.rs @@ -657,6 +657,26 @@ impl fmt::Display for Outcome { mod test { use super::Outcome::{self, *}; + macro_rules! fake_try { + ($e:block) => { + (||{ + std::ops::Try::from_output($e) + })() + } + } + + #[test] + fn outcome_try_trait() { + let r: Outcome = fake_try! {{ 3 }}; + assert_eq!(r, Success(3)); + let r: Outcome = fake_try! {{ Success::<_, &'static str, f32>(3)? }}; + assert_eq!(r, Success(3)); + let r: Outcome = fake_try! {{ Failure::("oops")?; 7 }}; + assert_eq!(r, Failure(String::from("oops"))); + let r: Outcome = fake_try! {{ Forward::(1234.5_f32)?; 7 }}; + assert_eq!(r, Forward(1234.5)); + } + #[test] fn can_use_question_mark_on_result_in_function_returning_outcome() { fn demo() -> Outcome {