From 9578f6aaff21dc9fcbbfbd109a385922efd2aa87 Mon Sep 17 00:00:00 2001 From: gnzlbg Date: Mon, 14 May 2018 15:18:04 +0200 Subject: [PATCH] shrink_to_fit shrinks in place --- src/liballoc/raw_vec.rs | 28 ++++++++++++++++++++-------- src/liballoc/vec.rs | 5 +---- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/liballoc/raw_vec.rs b/src/liballoc/raw_vec.rs index 5c6f6b22aae06..e4f7221f66730 100644 --- a/src/liballoc/raw_vec.rs +++ b/src/liballoc/raw_vec.rs @@ -618,8 +618,8 @@ impl RawVec { } } - /// Shrinks the allocation down to the specified amount. If the given amount - /// is 0, actually completely deallocates. + /// Non-biding request to reduce the capacity of the vector to `amount`. If the given + /// `amount` is `0` it deallocates. /// /// # Panics /// @@ -666,14 +666,26 @@ impl RawVec { let new_size = elem_size * amount; let align = mem::align_of::(); let old_layout = Layout::from_size_align_unchecked(old_size, align); - match self.a.realloc(NonNull::from(self.ptr).as_opaque(), - old_layout, - new_size) { - Ok(p) => self.ptr = p.cast().into(), - Err(_) => oom(), + // If we can shrink the allocation in place we just update + // the capacity. Otherwise, we re-allocate. + match self.a.shrink_in_place(NonNull::from(self.ptr).as_opaque(), + old_layout, new_size) { + Ok(()) => { + self.cap = amount + }, + Err(_) => { + match self.a.realloc(NonNull::from(self.ptr).as_opaque(), + old_layout, + new_size) { + Ok(ptr) => { + self.ptr = ptr.cast().into(); + self.cap = amount; + } + Err(_) => oom(), + } + } } } - self.cap = amount; } } } diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs index 690cbcb559bbf..7caf41ec63109 100644 --- a/src/liballoc/vec.rs +++ b/src/liballoc/vec.rs @@ -569,10 +569,7 @@ impl Vec { self.buf.try_reserve_exact(self.len, additional) } - /// Shrinks the capacity of the vector as much as possible. - /// - /// It will drop down as close as possible to the length but the allocator - /// may still inform the vector that there is space for a few more elements. + /// Non-binding request to reduce the capacity of the vector. /// /// # Examples ///