Skip to content
Merged
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
31 changes: 29 additions & 2 deletions library/alloc/src/raw_vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,21 @@ impl<T, A: Allocator> RawVec<T, A> {
// SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout
unsafe { self.inner.shrink_to_fit(cap, T::LAYOUT) }
}

/// Shrinks the buffer down to the specified capacity. If the given amount
/// is 0, actually completely deallocates.
///
/// # Errors
///
/// This function returns an error if the allocator cannot shrink the allocation.
///
/// # Panics
///
/// Panics if the given amount is *larger* than the current capacity.
#[inline]
pub(crate) fn try_shrink_to_fit(&mut self, cap: usize) -> Result<(), TryReserveError> {
unsafe { self.inner.try_shrink_to_fit(cap, T::LAYOUT) }
}
}

unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec<T, A> {
Expand Down Expand Up @@ -731,6 +746,20 @@ impl<A: Allocator> RawVecInner<A> {
}
}

/// # Safety
///
/// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
/// initially construct `self`
/// - `elem_layout`'s size must be a multiple of its alignment
/// - `cap` must be less than or equal to `self.capacity(elem_layout.size())`
unsafe fn try_shrink_to_fit(
&mut self,
cap: usize,
elem_layout: Layout,
) -> Result<(), TryReserveError> {
unsafe { self.shrink(cap, elem_layout) }
}

#[inline]
const fn needs_to_grow(&self, len: usize, additional: usize, elem_layout: Layout) -> bool {
additional > self.capacity(elem_layout.size()).wrapping_sub(len)
Expand Down Expand Up @@ -778,7 +807,6 @@ impl<A: Allocator> RawVecInner<A> {
/// initially construct `self`
/// - `elem_layout`'s size must be a multiple of its alignment
/// - `cap` must be less than or equal to `self.capacity(elem_layout.size())`
#[cfg(not(no_global_oom_handling))]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was this just added by accident? Seems like it already returned TryReserveError?

#[inline]
unsafe fn shrink(&mut self, cap: usize, elem_layout: Layout) -> Result<(), TryReserveError> {
assert!(cap <= self.capacity(elem_layout.size()), "Tried to shrink to a larger capacity");
Expand All @@ -796,7 +824,6 @@ impl<A: Allocator> RawVecInner<A> {
///
/// # Safety
/// `cap <= self.capacity()`
#[cfg(not(no_global_oom_handling))]
unsafe fn shrink_unchecked(
&mut self,
cap: usize,
Expand Down
71 changes: 68 additions & 3 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@

#[cfg(not(no_global_oom_handling))]
use core::clone::TrivialClone;
#[cfg(not(no_global_oom_handling))]
use core::cmp;
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};
#[cfg(not(no_global_oom_handling))]
Expand All @@ -88,7 +86,7 @@ use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, Tr
use core::ops::{self, Index, IndexMut, Range, RangeBounds};
use core::ptr::{self, NonNull};
use core::slice::{self, SliceIndex};
use core::{fmt, hint, intrinsics, ub_checks};
use core::{cmp, fmt, hint, intrinsics, ub_checks};

#[stable(feature = "extract_if", since = "1.87.0")]
pub use self::extract_if::ExtractIf;
Expand Down Expand Up @@ -1613,6 +1611,73 @@ impl<T, A: Allocator> Vec<T, A> {
}
}

/// Tries to shrink the capacity of the vector as much as possible
///
/// The behavior of this method depends on the allocator, which may either shrink the vector
/// in-place or reallocate. The resulting vector might still have some excess capacity, just as
/// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details.
///
/// [`with_capacity`]: Vec::with_capacity
///
/// # Errors
///
/// This function returns an error if the allocator fails to shrink the allocation,
/// the vector thereafter is still safe to use, the capacity remains unchanged
/// however. See [`Allocator::shrink`].
///
/// # Examples
///
/// ```
/// #![feature(vec_fallible_shrink)]
///
/// let mut vec = Vec::with_capacity(10);
/// vec.extend([1, 2, 3]);
/// assert!(vec.capacity() >= 10);
/// vec.try_shrink_to_fit().expect("why is the test harness failing to shrink to 12 bytes");
/// assert!(vec.capacity() >= 3);
/// ```
#[unstable(feature = "vec_fallible_shrink", issue = "152350")]
#[inline]
pub fn try_shrink_to_fit(&mut self) -> Result<(), TryReserveError> {
if self.capacity() > self.len { self.buf.try_shrink_to_fit(self.len) } else { Ok(()) }
}

/// Shrinks the capacity of the vector with a lower bound.
///
/// The capacity will remain at least as large as both the length
/// and the supplied value.
///
/// If the current capacity is less than the lower limit, this is a no-op.
///
/// # Errors
///
/// This function returns an error if the allocator fails to shrink the allocation,
/// the vector thereafter is still safe to use, the capacity remains unchanged
/// however. See [`Allocator::shrink`].
///
/// # Examples
///
/// ```
/// #![feature(vec_fallible_shrink)]
///
/// let mut vec = Vec::with_capacity(10);
/// vec.extend([1, 2, 3]);
/// assert!(vec.capacity() >= 10);
/// vec.try_shrink_to(4).expect("why is the test harness failing to shrink to 12 bytes");
/// assert!(vec.capacity() >= 4);
/// vec.try_shrink_to(0).expect("this is a no-op and thus the allocator isn't involved.");
/// assert!(vec.capacity() >= 3);
/// ```
#[unstable(feature = "vec_fallible_shrink", issue = "152350")]
#[inline]
pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), TryReserveError> {
if self.capacity() > min_capacity {
self.buf.try_shrink_to_fit(cmp::max(self.len, min_capacity))
} else {
Ok(())
}
}

/// Converts the vector into [`Box<[T]>`][owned slice].
///
/// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
Expand Down
Loading