I'm trying to copy the content of a Vec
into an existing Vec
, replacing the content of the target Vec
.
Here is what I'm looking for:
- allocation of new memory shouldn't be needed (unless the target
Vec
is too short) because the targetVec
is already allocated - it should not use an iterator because a memcopy should be good enough do the job
- the source
Vec
shouldn't be changed - ideally it should use safe methods
Here is what I tried:
vec.clone()
: gives correct content but allocates new memory, which should not be needed for a copy into an already existing big enoughVec
vec.clear(); vec.extend();
: copies in place, but seems to use an iterator on each element, which should not be needed, I just want a memcopyvec.copy_from_slice()
: is what I'm looking for, but needs exactly the same size buffers, which for some reason I can't seem to get
What doesn't work
#![feature(shrink_to)]
fn vec_copy(src: &Vec<i32>, dst: &mut Vec<i32>) {
// Try to adjust dst buffer size... there should be a better way
if src.len() > dst.len() {
let addon = src.len() - dst.len();
dst.reserve_exact(addon);
} else {
dst.shrink_to(src.len());
}
// Do the copy
// panics! :
// thread 'main' panicked at libcore/slice/mod.rs:1645:9
// 'destination and source slices have different lengths'
//
dst.copy_from_slice(src.as_slice()); // <--- panics here
}
fn main() {
// Copy from a shorter Vec
let mut container = vec![1, 2];
let test1 = vec![3]; // shorter vec
println!("{:p} = {:?}", &container[0], container); // output: 0x7f00bda20008 = [1, 2]
vec_copy(&test1, &mut container); // panics inside function
println!("{:p} = {:?}", &container[0], container); // expected: 0x7f00bda20008 = [3]
// Copy from a longer Vec
container = vec![1, 2];
let test2 = vec![4, 5, 6]; // longer Vec
println!("{:p} = {:?}", &container[0], container); // output: 0x7fef5b820018 = [1, 2]
vec_copy(&test2, &mut container); // panics inside function
println!("{:p} = {:?}", &container[0], container); // expected: 0x7fef5b820018 = [4, 5, 6]
}
Panics with error:
thread 'main' panicked at libcore/slice/mod.rs:1645:9,
'destination and source slices have different lengths'
The question
Using vec.copy_from_slice()
seems to be the way to memcopy in place the content of a Vec
into an other, without unneeded memory allocation and without using an iterator.
How can I set the size of the target Vec
so that vec.copy_from_slice()
doesn't panic?