From 026f8ef2593bb3a0cba7d9d711f67361b641224a Mon Sep 17 00:00:00 2001 From: enitrat Date: Wed, 15 May 2024 14:20:38 +0200 Subject: [PATCH] feat: result ok and err methods --- corelib/src/result.cairo | 42 ++++++++++++++++++++++++++++++ corelib/src/test/result_test.cairo | 24 +++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/corelib/src/result.cairo b/corelib/src/result.cairo index b9eb9aa2286..5534d7f2533 100644 --- a/corelib/src/result.cairo +++ b/corelib/src/result.cairo @@ -81,4 +81,46 @@ pub impl ResultTraitImpl of ResultTrait { Result::Err(_) => false, } } + + /// Converts from `Result` to `Option`. + /// + /// Converts `self` into an `Option`, consuming `self`, + /// and discarding the error, if any. + /// + /// # Examples + /// + /// ``` + /// let x: Result = Result::Ok(2); + /// assert_eq!(x.ok(), Option::Some(2)); + /// + /// let x: Result = Result::Err("Nothing here"); + /// assert!(x.ok().is_none()); + /// ``` + fn ok<+Drop, +Drop>(self: Result) -> Option { + match self { + Result::Ok(x) => Option::Some(x), + Result::Err(_) => Option::None, + } + } + + /// Converts from `Result` to `Option`. + /// + /// Converts `self` into an `Option`, consuming `self`, + /// and discarding the success value, if any. + /// + /// # Examples + /// + /// ``` + /// let x: Result = Result::Err("Nothing here"); + /// assert_eq!(x.err(), Option::Some("Nothing here")); + /// + /// let x: Result = Result::Ok(2); + /// assert!(x.err().is_none()); + /// ``` + fn err<+Drop, +Drop>(self: Result) -> Option { + match self { + Result::Ok(_) => Option::None, + Result::Err(x) => Option::Some(x), + } + } } diff --git a/corelib/src/test/result_test.cairo b/corelib/src/test/result_test.cairo index 4d4fa83bbc6..e151fdd92c0 100644 --- a/corelib/src/test/result_test.cairo +++ b/corelib/src/test/result_test.cairo @@ -123,3 +123,27 @@ fn test_result_err_into_is_ok() { let result: Result = Result::Err('no'); assert(!result.into_is_ok(), 'result_err_into_is_ok'); } + +#[test] +fn test_result_ok_ok_should_return_ok_value() { + let x: Result = Result::Ok(2); + assert_eq!(x.ok(), Option::Some(2)); +} + +#[test] +fn test_result_err_ok_should_return_none() { + let x: Result = Result::Err("Nothing here"); + assert!(x.ok().is_none()); +} + +#[test] +fn test_result_err_err_should_return_error_value() { + let x: Result = Result::Err("Nothing here"); + assert_eq!(x.err(), Option::Some("Nothing here")); +} + +#[test] +fn test_result_ok_err_should_return_none() { + let x: Result = Result::Ok(2); + assert!(x.err().is_none()); +}