@@ -1161,6 +1161,7 @@ pub trait OwnedVector<T> {
1161
1161
fn reserve ( & mut self , n : uint ) ;
1162
1162
fn reserve_at_least ( & mut self , n : uint ) ;
1163
1163
fn capacity ( & self ) -> uint ;
1164
+ fn shrink_to_fit ( & mut self ) ;
1164
1165
1165
1166
fn push ( & mut self , t : T ) ;
1166
1167
unsafe fn push_fast ( & mut self , t : T ) ;
@@ -1254,6 +1255,7 @@ impl<T> OwnedVector<T> for ~[T] {
1254
1255
*
1255
1256
* * n - The number of elements to reserve space for
1256
1257
*/
1258
+ #[ inline]
1257
1259
fn reserve_at_least ( & mut self , n : uint ) {
1258
1260
self . reserve ( uint:: next_power_of_two ( n) ) ;
1259
1261
}
@@ -1272,6 +1274,17 @@ impl<T> OwnedVector<T> for ~[T] {
1272
1274
}
1273
1275
}
1274
1276
1277
+ /// Shrink the capacity of the vector to match the length
1278
+ fn shrink_to_fit ( & mut self ) {
1279
+ unsafe {
1280
+ let ptr: * mut * mut Vec < ( ) > = cast:: transmute ( self ) ;
1281
+ let alloc = ( * * ptr) . fill ;
1282
+ let size = alloc + sys:: size_of :: < Vec < ( ) > > ( ) ;
1283
+ * ptr = realloc_raw ( * ptr as * mut c_void , size) as * mut Vec < ( ) > ;
1284
+ ( * * ptr) . alloc = alloc;
1285
+ }
1286
+ }
1287
+
1275
1288
/// Append an element to a vector
1276
1289
#[ inline]
1277
1290
fn push ( & mut self , t : T ) {
@@ -2327,6 +2340,7 @@ mod tests {
2327
2340
use sys;
2328
2341
use vec:: * ;
2329
2342
use cmp:: * ;
2343
+ use prelude:: * ;
2330
2344
2331
2345
fn square ( n : uint ) -> uint { n * n }
2332
2346
@@ -3600,6 +3614,18 @@ mod tests {
3600
3614
}
3601
3615
assert ! ( cnt == 3 ) ;
3602
3616
}
3617
+
3618
+ #[ test]
3619
+ fn test_shrink_to_fit ( ) {
3620
+ let mut xs = ~[ 0 , 1 , 2 , 3 ] ;
3621
+ for i in range ( 4 , 100 ) {
3622
+ xs. push ( i)
3623
+ }
3624
+ assert_eq ! ( xs. capacity( ) , 128 ) ;
3625
+ xs. shrink_to_fit ( ) ;
3626
+ assert_eq ! ( xs. capacity( ) , 100 ) ;
3627
+ assert_eq ! ( xs, range( 0 , 100 ) . to_owned_vec( ) ) ;
3628
+ }
3603
3629
}
3604
3630
3605
3631
#[ cfg( test) ]
0 commit comments