update doc for Vec::into_boxed_slice#137546
Conversation
|
also note #135933 |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
| /// 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); |
There was a problem hiding this comment.
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.
|
r? libs |
|
Stepping off rotation for a bit @rustbot reroll |
| /// | ||
| /// 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. |
There was a problem hiding this comment.
This seems a bit confusing to me. Rust allocators don't support asking for the capacity, so conversion to Box<[T]> and into_vec can't have capacity > length (at least for non-ZST cases, where we're actually using the allocator).
The underlying allocator may, of course, not need to copy any memory when realloc / grow are called, growing in place, but that's an implementation detail of the allocator.
For example, "final memory layout depends on the allocator" is wrong (I think). The memory layout and provenance of the Box<[T]> returned is valid only for its length and is fixed regardless of the allocator; you can't say that because conversion to Vec later allowed you to resize in place the additional bytes were always usable.
Context
Vec::into_boxed_sliceto highlight the API dependency on the memory layout strategy, and the doctest to remove the "encoding" of exact capacity guarantee.Related issue
Vec::into_boxed_sliceno-excess guarantee regressed in 1.77.0 #125941r? @the8472