Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: Implement into_boxed_slice() for TinyVec #205

Open
2moe opened this issue Feb 18, 2025 · 1 comment · May be fixed by #206
Open

Suggestion: Implement into_boxed_slice() for TinyVec #205

2moe opened this issue Feb 18, 2025 · 1 comment · May be fixed by #206

Comments

@2moe
Copy link

2moe commented Feb 18, 2025

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()
}
@Lokathor
Copy link
Owner

Sounds great. Do the PR and I can probably review this pretty quick.

@2moe 2moe linked a pull request Feb 20, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants