Search code examples
vectorrustheap-memorystack-allocation

How can I load all entries of a Vec<T> of arbitrary length onto the stack?


I am currently working with vectors and trying to ensure I have what is essentially an array of my vector on the stack. I cannot call Vec::into_boxed_slice since I am dynamically allocating space in my Vec. Is this at all possible?

Having read the Rustonomicon on how to implement Vec, it seems to stride over pointers on the heap, dereferencing at each entry. I want to chunk in Vec entries from the heap into the stack for fast access.


Solution

  • You can use the unsized_locals feature in nightly Rust:

    #![feature(unsized_locals)]
    
    fn example<T>(v: Vec<T>) {
        let s: [T] = *v.into_boxed_slice();
        dbg!(std::mem::size_of_val(&s));
    }
    
    fn main() {
        let x = vec![42; 100];
        example(x); // Prints 400
    }
    

    See also:


    I cannot call Vec::into_boxed_slice since I am dynamically allocating space in my Vec

    Sure you can.

    Vec [...] seems to stride over pointers on the heap, dereferencing at each entry

    Accessing each member in a Vec requires a memory dereference. Accessing each member in an array requires a memory dereference. There's no material difference in speed here.

    for fast access

    I doubt this will be any faster than directly accessing the data in the Vec. In fact, I wouldn't be surprised if it were slower, since you are copying it.