Reputation: 51
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);
}
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?
Upvotes: 2
Views: 641
Reputation: 51
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.
Upvotes: 3