Re: [PATCH] rust/alloc: add Vec::into_boxed_slice()
From: David Rheinsberg
Date: Thu Mar 26 2026 - 06:51:12 EST
Hi Alice,
On Thu, Mar 26, 2026, at 11:33 AM, Alice Ryhl wrote:
> On Thu, Mar 26, 2026 at 10:56:20AM +0100, David Rheinsberg wrote:
>> Add `Vec::into_boxed_slice()` similar to
>> `std::vec::Vec::into_boxed_slice()` [1].
>>
>> There is currently no way to easily consume the allocation of a vector.
>> However, it is very convenient to use `Vec` to initialize a dynamically
>> sized array and then "seal" it, so it can be passed along as a Box:
>>
>> fn create_from(src: &[T]) -> Result<KBox<[U]>, AllocError> {
>> let v = Vec::with_capacity(n, GFP_KERNEL)?;
>>
>> for i in src {
>> v.push(foo(i)?, GFP_KERNEL)?;
>> }
>>
>> Ok(v.into_boxed_slice())
>> }
>>
>> A valid alternative is to use `Box::new_uninit()` rather than
>> `Vec::with_capacity()`, and eventually convert the box via
>> `Box::assume_init()`. This works but needlessly requires unsafe code,
>> awkward drop handling, etc. Using `Vec` is the much simpler solution.
>>
>> [1] https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_boxed_slice
>>
>> Signed-off-by: David Rheinsberg <david@xxxxxxxxxxxx>
>
>> + /// Excess capacity is retained in the allocation, but lost until the box
>> + /// is dropped.
>
> We currently say that you should provide the right length when freeing
> an allocation, but this is going to violate that. You should probably
> invoke realloc here, like stdlib does.
Thanks, didn't know that!
`std` calls `shrink_to_fit()`. Should I add it as well? How about `shrink_to()`? I don't particularly need them, but I can expose them as well, given that I would have to implement those.
Thanks
David