Re: [PATCH] rust/alloc: add Vec::into_boxed_slice()
From: David Rheinsberg
Date: Thu Mar 26 2026 - 08:31:00 EST
Hi
On Thu, Mar 26, 2026, at 11:53 AM, Danilo Krummrich wrote:
> On Thu Mar 26, 2026 at 10:56 AM CET, David Rheinsberg wrote:
>> Add `Vec::into_boxed_slice()` similar to
>> `std::vec::Vec::into_boxed_slice()` [1].
>
> Do you have a user for this?
Yes.
>> + /// Converts the vector into [`Box<[T], A>`].
>> + ///
>> + /// Excess capacity is retained in the allocation, but lost until the box
>> + /// is dropped.
>> + pub fn into_boxed_slice(self) -> Box<[T], A> {
>> + let (buf, len, _cap) = self.into_raw_parts();
>> + let slice = ptr::slice_from_raw_parts_mut(buf, len);
>> +
>> + // SAFETY:
>> + // - `slice` has been allocated with `A`
>> + // - `slice` is suitably aligned
>> + // - `slice` has at least a length of `len`
>> + // - all elements within `slice` are initialized values of `T`
>> + // - `len` does not exceed `isize::MAX`
>> + unsafe { Box::from_raw(slice) }
>
> Box::from_raw() is missing the safety requirement that the allocation made with
> A must have been made for Layout::for_value::<T>(), as this is what we assume in
> the destructor.
Since `slice` is typed, shouldn't this be implied by:
"`slice` has been allocated with `A`"
There is also no mention of it in `From<Box<[T], A>> for Vec<T, A>`. This should have the same requirements, shouldn't it?
I will gladly mention it in v2, though.
> For this function we should call A::realloc() and document that
> into_boxed_slice() may shrink the backing allocation.
Will do.
> Additionally, can you please add a doc-test?
Do you want me to add a functionality test, or do you want me to add an example for documentation purposes? `doc-test` is a bit ambiguous in that regard.
Thanks
David