Skip to content

Commit

Permalink
feat: result ok and err methods
Browse files Browse the repository at this point in the history
  • Loading branch information
enitrat committed May 15, 2024
1 parent 000b834 commit 026f8ef
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
42 changes: 42 additions & 0 deletions corelib/src/result.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,46 @@ pub impl ResultTraitImpl<T, E> of ResultTrait<T, E> {
Result::Err(_) => false,
}
}

/// Converts from `Result<T, E>` to `Option<T>`.
///
/// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the error, if any.
///
/// # Examples
///
/// ```
/// let x: Result<u32, ByteArray> = Result::Ok(2);
/// assert_eq!(x.ok(), Option::Some(2));
///
/// let x: Result<u32, ByteArray> = Result::Err("Nothing here");
/// assert!(x.ok().is_none());
/// ```
fn ok<+Drop<T>, +Drop<E>>(self: Result<T, E>) -> Option<T> {
match self {
Result::Ok(x) => Option::Some(x),
Result::Err(_) => Option::None,
}
}

/// Converts from `Result<T, E>` to `Option<E>`.
///
/// Converts `self` into an `Option<E>`, consuming `self`,
/// and discarding the success value, if any.
///
/// # Examples
///
/// ```
/// let x: Result<u32, ByteArray> = Result::Err("Nothing here");
/// assert_eq!(x.err(), Option::Some("Nothing here"));
///
/// let x: Result<u32, ByteArray> = Result::Ok(2);
/// assert!(x.err().is_none());
/// ```
fn err<+Drop<T>, +Drop<E>>(self: Result<T, E>) -> Option<E> {
match self {
Result::Ok(_) => Option::None,
Result::Err(x) => Option::Some(x),
}
}
}
24 changes: 24 additions & 0 deletions corelib/src/test/result_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,27 @@ fn test_result_err_into_is_ok() {
let result: Result<u32, felt252> = 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<u32, ByteArray> = Result::Ok(2);
assert_eq!(x.ok(), Option::Some(2));
}

#[test]
fn test_result_err_ok_should_return_none() {
let x: Result<u32, ByteArray> = Result::Err("Nothing here");
assert!(x.ok().is_none());
}

#[test]
fn test_result_err_err_should_return_error_value() {
let x: Result<u32, ByteArray> = Result::Err("Nothing here");
assert_eq!(x.err(), Option::Some("Nothing here"));
}

#[test]
fn test_result_ok_err_should_return_none() {
let x: Result<u32, ByteArray> = Result::Ok(2);
assert!(x.err().is_none());
}

0 comments on commit 026f8ef

Please sign in to comment.