简体   繁体   中英

Copy big value from Box into Vec in Rust without blowing the stack

I want to copy (not move) a very big value from a box into a vec. The normal way of doing this (dereferencing the box) means the value is copied onto the stack temporarily, which blows it. Here's an example and a Playground link where it can be reproduced.

fn main() {
    let big_value = Box::new([0u8; 8 * 1024 * 1024]);
    let mut vec = Vec::new();
    vec.push(*big_value);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5998cff185dc209e7a1e676d41850ff4

Since both the Box and the Vec are on the heap, it should be possible to do a copy without passing through the stack. What's the best solution here?

See this answer on a Reddit post I made: https://old.reddit.com/r/rust/comments/n2jasd/question_copy_big_value_from_box_into_vec_without/gwmrcxp/

You can do this with vec.extend_from_slice(std::slice_from_ref(&big_value)); . This performs no allocations, and just copies the big_value from the heap into a new slot in the vec.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM