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

This commit is contained in:
Huon Wilson
2013-04-18 19:34:07 +10:00
parent d32d4d1209
commit 0ff568a3c1
2 changed files with 35 additions and 0 deletions

View File

@@ -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);
}
@@ -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) {
@@ -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
}
}
}