@@ -15,7 +15,7 @@ use cmp::{Ord, Eq, Ordering, TotalEq, TotalOrd};
1515use container:: { Container , Mutable } ;
1616use default:: Default ;
1717use fmt;
18- use iter:: { DoubleEndedIterator , FromIterator , Extendable , Iterator } ;
18+ use iter:: { DoubleEndedIterator , FromIterator , Extendable , Iterator , range } ;
1919use libc:: { free, c_void} ;
2020use mem:: { size_of, move_val_init} ;
2121use mem;
@@ -1135,6 +1135,56 @@ impl<T> Vec<T> {
11351135 pub fn as_mut_ptr ( & mut self ) -> * mut T {
11361136 self . as_mut_slice ( ) . as_mut_ptr ( )
11371137 }
1138+
1139+ /// Retains only the elements specified by the predicate.
1140+ ///
1141+ /// In other words, remove all elements `e` such that `f(&e)` returns false.
1142+ /// This method operates in place and preserves the order the retained elements.
1143+ ///
1144+ /// # Example
1145+ ///
1146+ /// ```rust
1147+ /// let mut vec = vec!(1i, 2, 3, 4);
1148+ /// vec.retain(|x| x%2 == 0);
1149+ /// assert_eq!(vec, vec!(2, 4));
1150+ /// ```
1151+ pub fn retain ( & mut self , f: |& T | -> bool) {
1152+ let len = self . len ( ) ;
1153+ let mut del = 0 u;
1154+ {
1155+ let v = self . as_mut_slice ( ) ;
1156+
1157+ for i in range ( 0 u, len) {
1158+ if !f ( & v[ i] ) {
1159+ del += 1 ;
1160+ } else if del > 0 {
1161+ v. swap ( i-del, i) ;
1162+ }
1163+ }
1164+ }
1165+ if del > 0 {
1166+ self . truncate ( len - del) ;
1167+ }
1168+ }
1169+
1170+ /// Expands a vector in place, initializing the new elements to the result of a function.
1171+ ///
1172+ /// The vector is grown by `n` elements. The i-th new element are initialized to the value
1173+ /// returned by `f(i)` where `i` is in the range [0, n).
1174+ ///
1175+ /// # Example
1176+ ///
1177+ /// ```rust
1178+ /// let mut vec = vec!(0u, 1);
1179+ /// vec.grow_fn(3, |i| i);
1180+ /// assert_eq!(vec, vec!(0, 1, 0, 1, 2));
1181+ /// ```
1182+ pub fn grow_fn ( & mut self , n : uint , f: |uint| -> T ) {
1183+ self . reserve_additional ( n) ;
1184+ for i in range ( 0 u, n) {
1185+ self . push ( f ( i) ) ;
1186+ }
1187+ }
11381188}
11391189
11401190impl < T : TotalOrd > Vec < T > {
@@ -1523,4 +1573,17 @@ mod tests {
15231573 v. clone_from ( & three) ;
15241574 assert_eq ! ( v, three)
15251575 }
1576+
1577+ fn test_grow_fn ( ) {
1578+ let mut v = Vec :: from_slice ( [ 0 u, 1 ] ) ;
1579+ v. grow_fn ( 3 , |i| i) ;
1580+ assert ! ( v == Vec :: from_slice( [ 0 u, 1 , 0 , 1 , 2 ] ) ) ;
1581+ }
1582+
1583+ #[ test]
1584+ fn test_retain ( ) {
1585+ let mut vec = Vec :: from_slice ( [ 1 u, 2 , 3 , 4 ] ) ;
1586+ vec. retain ( |x| x%2 == 0 ) ;
1587+ assert ! ( vec == Vec :: from_slice( [ 2 u, 4 ] ) ) ;
1588+ }
15261589}
0 commit comments