Skip to content

shrink_to_fit shrinks in place #50742

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions src/liballoc/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,8 +618,8 @@ impl<T, A: Alloc> RawVec<T, A> {
}
}

/// 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
///
Expand Down Expand Up @@ -666,14 +666,26 @@ impl<T, A: Alloc> RawVec<T, A> {
let new_size = elem_size * amount;
let align = mem::align_of::<T>();
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;
}
}
}
Expand Down
5 changes: 1 addition & 4 deletions src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,10 +569,7 @@ impl<T> Vec<T> {
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
///
Expand Down