@@ -2427,6 +2427,7 @@ impl<T:Eq> OwnedEqVector<T> for ~[T] {
2427
2427
#[ allow( missing_doc) ]
2428
2428
pub trait MutableVector < ' self , T > {
2429
2429
fn mut_slice ( self , start : uint , end : uint ) -> & ' self mut [ T ] ;
2430
+ fn mut_iter ( self ) -> MutVecIterator < ' self , T > ;
2430
2431
2431
2432
unsafe fn unsafe_mut_ref ( & self , index : uint ) -> * mut T ;
2432
2433
unsafe fn unsafe_set ( & self , index : uint , val : T ) ;
@@ -2438,6 +2439,15 @@ impl<'self,T> MutableVector<'self, T> for &'self mut [T] {
2438
2439
mut_slice ( self , start, end)
2439
2440
}
2440
2441
2442
+ #[ inline]
2443
+ fn mut_iter ( self ) -> MutVecIterator < ' self , T > {
2444
+ unsafe {
2445
+ let p = vec:: raw:: to_mut_ptr ( self ) ;
2446
+ MutVecIterator { ptr : p, end : p. offset ( self . len ( ) ) ,
2447
+ lifetime : cast:: transmute ( p) }
2448
+ }
2449
+ }
2450
+
2441
2451
#[ inline( always) ]
2442
2452
unsafe fn unsafe_mut_ref ( & self , index : uint ) -> * mut T {
2443
2453
let pair_ptr: & ( * mut T , uint ) = transmute ( self ) ;
@@ -2962,6 +2972,30 @@ impl<'self, T> Iterator<&'self T> for VecIterator<'self, T> {
2962
2972
}
2963
2973
}
2964
2974
2975
+ /// An external iterator for vectors with the possibility of mutating
2976
+ /// elements. (use with the std::iterator module)
2977
+ pub struct MutVecIterator < ' self , T > {
2978
+ priv ptr: * mut T ,
2979
+ priv end: * mut T ,
2980
+ priv lifetime : & ' self mut T // FIXME: #5922
2981
+ }
2982
+
2983
+ // could be implemented with &[T] with .slice(), but this avoids bounds checks
2984
+ impl < ' self , T > Iterator < & ' self mut T > for MutVecIterator < ' self , T > {
2985
+ #[ inline]
2986
+ fn next ( & mut self ) -> Option < & ' self mut T > {
2987
+ unsafe {
2988
+ if self . ptr == self . end {
2989
+ None
2990
+ } else {
2991
+ let old = self . ptr ;
2992
+ self . ptr = self . ptr . offset ( 1 ) ;
2993
+ Some ( cast:: transmute ( old) )
2994
+ }
2995
+ }
2996
+ }
2997
+ }
2998
+
2965
2999
#[ cfg( test) ]
2966
3000
mod tests {
2967
3001
use option:: { None , Option , Some } ;
@@ -4669,6 +4703,16 @@ mod tests {
4669
4703
}
4670
4704
}
4671
4705
4706
+ #[ test]
4707
+ fn test_mut_iterator( ) {
4708
+ use iterator:: * ;
4709
+ let mut xs = [ 1 , 2 , 3 , 4 , 5 ] ;
4710
+ for xs. mut_iter( ) . advance |x| {
4711
+ * x += 1 ;
4712
+ }
4713
+ assert_eq ! ( xs, [ 2 , 3 , 4 , 5 , 6 ] )
4714
+ }
4715
+
4672
4716
#[ test]
4673
4717
fn test_reverse_part( ) {
4674
4718
let mut values = [ 1 , 2 , 3 , 4 , 5 ] ;
0 commit comments