How to box a slice with a single copy?

I have a slice of type &[u8]. I'd like to convert it to a boxed slice.

One way I can do this is:

let bytes = // a `&[u8]`
let mut buf: Vec<u8> = Vec::with_capacity(bytes.len()); buf.extend(bytes);
let boxed_slice = buf.into_boxed_slice();

but I think this does 2 copies. It first copies the slice into a vector and then copies the vector into a buffer for the boxed slice.

Is there a way to do this with one copy?

Box<[T]> implements From<&'_ [T]>, so you can do the conversion directly with Box::from(bytes). Here's an example on the Playground.

2 Likes

Moreover, Vec::into_boxed_slice does not copy if the capacity is exact, so the original version is just the same.

Note that you can just call to_vec in cases like this instead of doing the with_capacity+extend dance.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.