diff --git a/corelib/src/result.cairo b/corelib/src/result.cairo index d68a369c4ed..026b2bc1bd4 100644 --- a/corelib/src/result.cairo +++ b/corelib/src/result.cairo @@ -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}; @@ -686,3 +696,30 @@ pub impl ResultTraitImpl of ResultTrait { } } } + + +impl ResultIntoIterator< + T, E, +Destruct, +Destruct, +> of crate::iter::IntoIterator> { + type IntoIter = crate::option::OptionIter; + + /// 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 = Result::Ok(5); + /// let mut x_iter = x.into_iter(); + /// assert!(x_iter.next() == Option::Some(5)); + /// + /// let x: Result = Result::Err("nothing!"); + /// let mut x_iter = x.into_iter(); + /// assert!(x_iter.next() == Option::None); + /// ``` + #[inline] + fn into_iter(self: Result) -> crate::option::OptionIter { + self.ok().into_iter() + } +} diff --git a/corelib/src/test/result_test.cairo b/corelib/src/test/result_test.cairo index e54aec921c9..e77315f60aa 100644 --- a/corelib/src/test/result_test.cairo +++ b/corelib/src/test/result_test.cairo @@ -312,3 +312,18 @@ fn test_result_err_map_err() { let x: Result = Result::Err(13); assert!(x.map_err(stringify) == Result::Err("error code: 13")); } + +#[test] +fn test_result_ok_iter_next() { + let x: Result = 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 = Result::Err("nothing!"); + let mut x_iter = x.into_iter(); + assert!(x_iter.next() == Option::None); +}