Hide beginning of Vec

I would like to write a function that consumes a Vec and returns it in some form with a bit from the beginning cut (or rather hidden). Basically like this:

fn foo(v: Vec<u8>) -> &[u8] {

Of course this doesn't work because after the function call the Vec is consumed and the slice has no owner.

I would like to avoid shifting the Vec elements to the left because the Vec can potentially be a few hundred MB in size and I want to cut only a few bytes. I would like those "hidden" bytes to be freed when the rest of the Vec is freed.

Is this possible?

You could convert the Vec to a VecDeque, which is free as long as there's a little extra capacity (the exact details of that are unspecified and subject to change). Then deque.drain(..16) and return the rest.

1 Like

Actually, even better:

fn foo(v: Vec<u8>) -> std::vec::IntoIter<u8> {
    let mut iter = v.into_iter();
    iter.nth(15); // consume 0..=15

The recipient can even use IntoIter::as_slice / as_mut_slice if needed.


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.