Skip to content

Commit 25bac77

Browse files
committed
vec: add shrink_to_fit
Closes #4960
1 parent 0ba8ccd commit 25bac77

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/libstd/vec.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1161,6 +1161,7 @@ pub trait OwnedVector<T> {
11611161
fn reserve(&mut self, n: uint);
11621162
fn reserve_at_least(&mut self, n: uint);
11631163
fn capacity(&self) -> uint;
1164+
fn shrink_to_fit(&mut self);
11641165

11651166
fn push(&mut self, t: T);
11661167
unsafe fn push_fast(&mut self, t: T);
@@ -1254,6 +1255,7 @@ impl<T> OwnedVector<T> for ~[T] {
12541255
*
12551256
* * n - The number of elements to reserve space for
12561257
*/
1258+
#[inline]
12571259
fn reserve_at_least(&mut self, n: uint) {
12581260
self.reserve(uint::next_power_of_two(n));
12591261
}
@@ -1272,6 +1274,17 @@ impl<T> OwnedVector<T> for ~[T] {
12721274
}
12731275
}
12741276

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+
12751288
/// Append an element to a vector
12761289
#[inline]
12771290
fn push(&mut self, t: T) {
@@ -2327,6 +2340,7 @@ mod tests {
23272340
use sys;
23282341
use vec::*;
23292342
use cmp::*;
2343+
use prelude::*;
23302344

23312345
fn square(n: uint) -> uint { n * n }
23322346

@@ -3600,6 +3614,18 @@ mod tests {
36003614
}
36013615
assert!(cnt == 3);
36023616
}
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+
}
36033629
}
36043630

36053631
#[cfg(test)]

0 commit comments

Comments
 (0)