@@ -50,6 +50,8 @@ pub trait IteratorUtil<A> {
50
50
fn nth ( & mut self , n : uint ) -> A ;
51
51
fn first ( & mut self ) -> A ;
52
52
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 ;
53
55
}
54
56
55
57
/// 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 {
184
186
for self . advance |e| { elm = e; }
185
187
return elm;
186
188
}
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 ) }
187
206
}
188
207
189
208
pub struct ChainIterator < T , U > {
@@ -648,4 +667,12 @@ mod tests {
648
667
let v: & [ uint ] = & [ ] ;
649
668
v. iter ( ) . last ( ) ;
650
669
}
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
+ }
651
678
}
0 commit comments