@@ -19,6 +19,7 @@ implementing the `Iterator` trait.
19
19
20
20
use cmp;
21
21
use iter;
22
+ use iter:: FromIter ;
22
23
use num:: { Zero , One } ;
23
24
use prelude:: * ;
24
25
@@ -255,6 +256,20 @@ pub trait IteratorUtil<A> {
255
256
/// ~~~
256
257
fn to_vec ( & mut self ) -> ~[ A ] ;
257
258
259
+ /// Loops through the entire iterator, collecting all of the elements into
260
+ /// a container implementing `FromIter`.
261
+ ///
262
+ /// # Example
263
+ ///
264
+ /// ~~~ {.rust}
265
+ /// use std::iterator::*;
266
+ ///
267
+ /// let a = [1, 2, 3, 4, 5];
268
+ /// let b: ~[int] = a.iter().transform(|&x| x).collect();
269
+ /// assert!(a == b);
270
+ /// ~~~
271
+ fn collect < B : FromIter < A > > ( & mut self ) -> B ;
272
+
258
273
/// Loops through `n` iterations, returning the `n`th element of the
259
274
/// iterator.
260
275
///
@@ -419,6 +434,11 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
419
434
iter:: to_vec :: < A > ( |f| self . advance ( f) )
420
435
}
421
436
437
+ #[ inline( always) ]
438
+ fn collect < B : FromIter < A > > ( & mut self ) -> B {
439
+ FromIter :: from_iter :: < A , B > ( |f| self . advance ( f) )
440
+ }
441
+
422
442
/// Return the `n`th item yielded by an iterator.
423
443
#[ inline( always) ]
424
444
fn nth ( & mut self , mut n : uint ) -> Option < A > {
@@ -1062,6 +1082,13 @@ mod tests {
1062
1082
assert_eq ! ( v. slice( 0 , 0 ) . iter( ) . transform( |& x| x) . min( ) , None ) ;
1063
1083
}
1064
1084
1085
+ #[ test]
1086
+ fn test_collect( ) {
1087
+ let a = [ 1 , 2 , 3 , 4 , 5 ] ;
1088
+ let b: ~[ int] = a. iter( ) . transform( |& x| x) . collect( ) ;
1089
+ assert_eq ! ( a, b) ;
1090
+ }
1091
+
1065
1092
#[ test]
1066
1093
fn test_all( ) {
1067
1094
let v = ~& [ 1 , 2 , 3 , 4 , 5 ] ;
0 commit comments