Skip to content

Commit

Permalink
feat(corelib): Result iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
cairolover committed Dec 26, 2024
1 parent d6f6e5d commit 85008e0
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
46 changes: 46 additions & 0 deletions corelib/src/result.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@
use crate::array::{ArrayTrait, SpanTrait};
#[allow(unused_imports)]
use crate::serde::Serde;
#[allow(unused_imports)]
use crate::iter::{IntoIterator, Iterator};

/// The type used for returning and propagating errors. It is an enum with the variants `Ok: T`,
/// representing success and containing a value, and `Err: E`, representing error and containing an
Expand Down Expand Up @@ -541,3 +543,47 @@ pub impl ResultTraitImpl<T, E> of ResultTrait<T, E> {
}
}
}

/// An iterator over the value in a [`Ok`] variant of a [`Result`].
///
/// The iterator yields one value if the result is [`Ok`], otherwise none.
///
/// This struct is created by the [`into_iter`] method on [`Result`] (provided by the
/// [`IntoIterator`] trait).
///
/// [`into_iter`]: IntoIterator::into_iter
#[derive(Drop)]
pub struct ResultIter<T> {
inner: Option<T>,
}

impl ResultIterator<T, +Copy<T>> of Iterator<ResultIter<T>> {
type Item = T;
fn next(ref self: ResultIter<T>) -> Option<T> {
self.inner
}
}

impl ResultIntoIterator<T, E, +Copy<T>, +Destruct<T>, +Destruct<E>> of IntoIterator<Result<T, E>> {
type IntoIter = ResultIter<T>;

/// Returns a consuming iterator over the possibly contained value.
///
/// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
///
/// # Examples
///
/// ```
/// let x: Result<u32, ByteArray> = Result::Ok(5);
/// let mut x_iter = x.into_iter();
/// assert!(x_iter.next() == Option::Some(5));
///
/// let x: Result<u32, ByteArray> = Result::Err("nothing!");
/// let mut x_iter = x.into_iter();
/// assert!(x_iter.next() == Option::None);
/// ```
#[inline]
fn into_iter(self: Result<T, E>) -> ResultIter<T> {
ResultIter { inner: self.ok() }
}
}
15 changes: 15 additions & 0 deletions corelib/src/test/result_test.cairo
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::result::{Result, ResultTraitImpl};
use crate::iter::{IntoIterator, Iterator};

#[test]
fn test_result_ok_expect() {
Expand Down Expand Up @@ -256,3 +257,17 @@ fn test_result_ok_err_should_return_none() {
let x: Result<u32, ByteArray> = Result::Ok(2);
assert!(x.err().is_none());
}

#[test]
fn test_result_ok_iter_next() {
let x: Result<u32, ByteArray> = Result::Ok(5);
let mut x_iter = x.into_iter();
assert!(x_iter.next() == Option::Some(5));
}

#[test]
fn test_result_err_iter_next() {
let x: Result<u32, ByteArray> = Result::Err("nothing!");
let mut x_iter = x.into_iter();
assert!(x_iter.next() == Option::None);
}

0 comments on commit 85008e0

Please sign in to comment.