diff options
| author | bors <bors@rust-lang.org> | 2013-04-18 03:42:53 -0700 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2013-04-18 03:42:53 -0700 |
| commit | d29ef7ad255ba61a67047e8d3825feb3a6827444 (patch) | |
| tree | 02f665927d6e66fd67c9b65f019a9281623494ce | |
| parent | d32d4d12096dc39ff428f606e2242eaae0c6a0de (diff) | |
| parent | 0ff568a3c1d4cc51109aacc88a598e6d3cfe5ea0 (diff) | |
| download | rust-d29ef7ad255ba61a67047e8d3825feb3a6827444.tar.gz rust-d29ef7ad255ba61a67047e8d3825feb3a6827444.zip | |
auto merge of #5927 : huonw/rust/core-enumerate-iterator, r=thestinger
| -rw-r--r-- | src/libcore/iterator.rs | 25 | ||||
| -rw-r--r-- | src/libcore/vec.rs | 10 |
2 files changed, 35 insertions, 0 deletions
diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index fcb5102d4c0..8a9f2d3e994 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -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 + } + } +} diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 0403ae64f02..eebe6a7a37f 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -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: |
