Skip to content

Commit 483eba1

Browse files
committed
---
yaml --- r: 61437 b: refs/heads/try c: b4cea35 h: refs/heads/master i: 61435: e83e568 v: v3
1 parent 7fae5de commit 483eba1

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
refs/heads/master: 2d28d645422c1617be58c8ca7ad9a457264ca850
33
refs/heads/snap-stage1: e33de59e47c5076a89eadeb38f4934f58a3618a6
44
refs/heads/snap-stage3: 2d28d645422c1617be58c8ca7ad9a457264ca850
5-
refs/heads/try: 02945f1cb1524f5791dd244e63a8d9bb2d61ac77
5+
refs/heads/try: b4cea351ba9df84efbff56d7bd79cd52704592d6
66
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
77
refs/heads/ndm: f3868061cd7988080c30d6d5bf352a5a5fe2460b
88
refs/heads/try2: 147ecfdd8221e4a4d4e090486829a06da1e0ca3c

branches/try/src/libcore/iterator.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ pub trait IteratorUtil<A> {
5050
fn nth(&mut self, n: uint) -> A;
5151
fn first(&mut self) -> A;
5252
fn last(&mut self) -> A;
53+
fn fold<B>(&mut self, start: B, f: &fn(B, A) -> B) -> B;
54+
fn count(&mut self) -> uint;
5355
}
5456

5557
/// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
@@ -184,6 +186,23 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
184186
for self.advance |e| { elm = e; }
185187
return elm;
186188
}
189+
190+
/// Reduce an iterator to an accumulated value
191+
#[inline]
192+
fn fold<B>(&mut self, init: B, f: &fn(B, A) -> B) -> B {
193+
let mut accum = init;
194+
loop {
195+
match self.next() {
196+
Some(x) => { accum = f(accum, x); }
197+
None => { break; }
198+
}
199+
}
200+
return accum;
201+
}
202+
203+
/// Count the number of an iterator elemenrs
204+
#[inline(always)]
205+
fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) }
187206
}
188207

189208
pub struct ChainIterator<T, U> {
@@ -648,4 +667,12 @@ mod tests {
648667
let v: &[uint] = &[];
649668
v.iter().last();
650669
}
670+
671+
#[test]
672+
fn test_iterator_count() {
673+
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
674+
assert_eq!(v.slice(0, 4).iter().count(), 4);
675+
assert_eq!(v.slice(0, 10).iter().count(), 10);
676+
assert_eq!(v.slice(0, 0).iter().count(), 0);
677+
}
651678
}

0 commit comments

Comments
 (0)