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

libcore: add an EnumerateIterator, like Python's enumerate. #5927

Closed
wants to merge 1 commit into from
Closed
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
25 changes: 25 additions & 0 deletions src/libcore/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub trait IteratorUtil<A> {
// FIXME: #5898: should be called map
fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, Self>;
fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> FilterIterator<'r, A, Self>;
fn enumerate(self) -> EnumerateIterator<Self>;
fn advance(&mut self, f: &fn(A) -> bool);
}

Expand All @@ -42,6 +43,11 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
FilterIterator{iter: self, predicate: predicate}
}

#[inline(always)]
fn enumerate(self) -> EnumerateIterator<T> {
EnumerateIterator{iter: self, count: 0}
}

/// A shim implementing the `for` loop iteration protocol for iterator objects
#[inline]
fn advance(&mut self, f: &fn(A) -> bool) {
Expand Down Expand Up @@ -104,3 +110,22 @@ impl<'self, A, B, T: Iterator<A>> Iterator<B> for MapIterator<'self, A, B, T> {
}
}
}

pub struct EnumerateIterator<T> {
priv iter: T,
priv count: uint
}

impl<A, T: Iterator<A>> Iterator<(uint, A)> for EnumerateIterator<T> {
#[inline]
fn next(&mut self) -> Option<(uint, A)> {
match self.iter.next() {
Some(a) => {
let ret = Some((self.count, a));
self.count += 1;
ret
}
_ => None
}
}
}
10 changes: 10 additions & 0 deletions src/libcore/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4474,6 +4474,16 @@ mod tests {
i += 1;
}
}

#[test]
fn test_iterator_enumerate() {
use iterator::*;
let xs = [0u,1,2,3,4,5];
let mut it = xs.iter().enumerate();
for it.advance |(i, &x): (uint, &uint)| {
assert_eq!(i, x);
}
}
}

// Local Variables:
Expand Down