Skip to content
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

update doc for Vec::into_boxed_slice #137546

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
21 changes: 15 additions & 6 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1442,28 +1442,37 @@ impl<T, A: Allocator> Vec<T, A> {

/// Converts the vector into [`Box<[T]>`][owned slice].
///
/// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
/// Before the conversion, this will attempt to shrink the vector's allocation to match its length,
/// but the final memory layout depends on the allocator's [memory fitting][memory-fitting] strategy.
/// The returned slice will have exactly [`len`] elements, but take note that the underlying allocation
/// may still contain unused capacity that is safe to use with sized deallocation methods.
///
/// When converting back to a vector using `Box<[T]>::into_vec`, the resulting
/// vector may retain this extra capacity. For details about allocator behavior,
/// see [`Allocator::shrink`] and the [memory fitting] documentation.
///
/// [`len`]: Vec::len
/// [owned slice]: Box
/// [memory-fitting]: Allocator#memory-fitting
/// [`shrink_to_fit`]: Vec::shrink_to_fit
///
/// # Examples
///
/// Basic conversion:
/// ```
/// let v = vec![1, 2, 3];
///
/// let slice = v.into_boxed_slice();
/// ```
///
/// Any excess capacity is removed:
///
/// Preserved allocation size when converting back:
/// ```
/// let mut vec = Vec::with_capacity(10);
/// vec.extend([1, 2, 3]);
///
/// assert!(vec.capacity() >= 10);
/// let slice = vec.into_boxed_slice();
/// assert_eq!(slice.into_vec().capacity(), 3);
/// let new_vec = slice.into_vec();
/// // The allocator may have kept extra capacity:
/// assert!(new_vec.capacity() >= 3);
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm curious about the test. I tried many times with assert_eq!(slice.into_vec().capacity(), 3);, it all passed. And I tested it for different types and cases. Only ZST kept extra capacity. Experiment result is here.

/// ```
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
Loading