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: Iterator::count #7094

Merged
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
40 changes: 40 additions & 0 deletions corelib/src/iter/traits/iterator.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,46 @@ pub trait Iterator<T> {
/// ```
fn next(ref self: T) -> Option<Self::Item>;

/// Consumes the iterator, counting the number of iterations and returning it.
///
/// This method will call [`next`] repeatedly until [`None`] is encountered,
/// returning the number of times it saw [`Some`]. Note that [`next`] has to be
/// called at least once even if the iterator does not have any elements.
///
/// [`next`]: Iterator::next
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so counting elements of
/// an iterator with more than [`Bounded::<usize>::MAX`] elements either produces the
/// wrong result or panics.
///
/// [`Bounded::<usize>::MAX`]: core::num::traits::Bounded
///
/// # Panics
///
/// This function might panic if the iterator has more than [`Bounded::<usize>::MAX`]
/// elements.
///
/// # Examples
///
/// ```
/// let mut a = array![1, 2, 3].into_iter();
/// assert_eq!(a.count(), 3);
///
/// let mut a = array![1, 2, 3, 4, 5].into_iter();
/// assert_eq!(a.count(), 5);
/// ```
#[inline]
fn count<+Destruct<T>, +Destruct<Self::Item>>(
self: T,
) -> usize {
let mut self = self;
Self::fold(ref self, 0_usize, |count, _x| {
count + 1
})
}

/// Advances the iterator by `n` elements.
///
/// This method will eagerly skip `n` elements by calling [`next`] up to `n`
Expand Down
12 changes: 12 additions & 0 deletions corelib/src/test/iter_test.cairo
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
#[test]
fn test_iter_count() {
let mut empty_iter = ArrayTrait::<usize>::new().into_iter();
let count = empty_iter.count();
assert_eq!(count, 0);

let mut iter = array![1, 2, 3].into_iter();
let count = iter.count();

assert_eq!(count, 3);
}

#[test]
fn test_advance_by() {
let mut iter = array![1_u8, 2, 3, 4].into_iter();
Expand Down
Loading