Skip to content

Commit 0ff568a

Browse files
committed
libcore: add an EnumerateIterator, like Python's enumerate.
1 parent d32d4d1 commit 0ff568a

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/libcore/iterator.rs

+25
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ pub trait IteratorUtil<A> {
2222
// FIXME: #5898: should be called map
2323
fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, Self>;
2424
fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> FilterIterator<'r, A, Self>;
25+
fn enumerate(self) -> EnumerateIterator<Self>;
2526
fn advance(&mut self, f: &fn(A) -> bool);
2627
}
2728

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

46+
#[inline(always)]
47+
fn enumerate(self) -> EnumerateIterator<T> {
48+
EnumerateIterator{iter: self, count: 0}
49+
}
50+
4551
/// A shim implementing the `for` loop iteration protocol for iterator objects
4652
#[inline]
4753
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> {
104110
}
105111
}
106112
}
113+
114+
pub struct EnumerateIterator<T> {
115+
priv iter: T,
116+
priv count: uint
117+
}
118+
119+
impl<A, T: Iterator<A>> Iterator<(uint, A)> for EnumerateIterator<T> {
120+
#[inline]
121+
fn next(&mut self) -> Option<(uint, A)> {
122+
match self.iter.next() {
123+
Some(a) => {
124+
let ret = Some((self.count, a));
125+
self.count += 1;
126+
ret
127+
}
128+
_ => None
129+
}
130+
}
131+
}

src/libcore/vec.rs

+10
Original file line numberDiff line numberDiff line change
@@ -4474,6 +4474,16 @@ mod tests {
44744474
i += 1;
44754475
}
44764476
}
4477+
4478+
#[test]
4479+
fn test_iterator_enumerate() {
4480+
use iterator::*;
4481+
let xs = [0u,1,2,3,4,5];
4482+
let mut it = xs.iter().enumerate();
4483+
for it.advance |(i, &x): (uint, &uint)| {
4484+
assert_eq!(i, x);
4485+
}
4486+
}
44774487
}
44784488

44794489
// Local Variables:

0 commit comments

Comments
 (0)