Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(corelib): Result iterator #6933

Merged
merged 6 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions corelib/src/result.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,16 @@
//! [`Ok`]: Result::Ok
//! [`Err`]: Result::Err
//!
//! ## Iterating over `Result`
//!
//! A [`Result`] can be iterated over. This can be helpful if you need an
//! iterator that is conditionally empty. The iterator will either produce
//! a single value (when the [`Result`] is [`Ok`]), or produce no values
//! (when the [`Result`] is [`Err`]). For example, [`into_iter`]
//! contains [`Some(v)`] if the [`Result`] is [`Ok(v)`], and [`None`] if the
//! [`Result`] is [`Err`].
//!
//! [`into_iter`]: IntoIterator::into_iter

#[allow(unused_imports)]
use crate::array::{ArrayTrait, SpanTrait};
Expand Down Expand Up @@ -686,3 +696,30 @@ pub impl ResultTraitImpl<T, E> of ResultTrait<T, E> {
}
}
}


impl ResultIntoIterator<
T, E, +Destruct<T>, +Destruct<E>,
> of crate::iter::IntoIterator<Result<T, E>> {
type IntoIter = crate::option::OptionIter<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>) -> crate::option::OptionIter<T> {
self.ok().into_iter()
}
}
15 changes: 15 additions & 0 deletions corelib/src/test/result_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -312,3 +312,18 @@ fn test_result_err_map_err() {
let x: Result<u32, u32> = Result::Err(13);
assert!(x.map_err(stringify) == Result::Err("error code: 13"));
}

#[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));
assert!(x_iter.next() == Option::None);
}

#[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);
}
Loading