-
Notifications
You must be signed in to change notification settings - Fork 59
Closed
Description
While we can currently convert TinyVec to Box<[T]> via tinyvec.to_vec().into_boxed_slice(), this incurs unnecessary memory reallocation.
Implementing tinyvec.into_boxed_slice() would be better.
Since Box<[T]> is more compact and emphasizes immutable length, it is useful in certain situations.
use core::mem::size_of_val;
use tinyvec::{Array, TinyVec};
struct Foo {
bar: Box<[u32]>,
}
fn main() {
// Initialize TinyVec with 204800 elements (exceeding inline capacity)
let tv: TinyVec<[_; 102400]> = (0..204800).collect();
assert!(tv.is_heap());
assert_eq!(size_of_val(&tv), 409608);
let bar = tinyvec_into_boxed_slice(tv);
assert_eq!(size_of_val(&bar), 16); // Final size: 16 bytes (fat pointer)
let foo = Foo { bar };
assert_eq!(foo.bar.get(..3), Some(&[0, 1, 2][..]));
}
fn tinyvec_into_boxed_slice<T: Array>(
owned: TinyVec<T>,
) -> Box<[<T as Array>::Item]> {
use TinyVec::*;
match owned {
Heap(inner) => inner,
Inline(mut inner) => inner.drain_to_vec(),
}
.into_boxed_slice()
}Metadata
Metadata
Assignees
Labels
No labels