How do you copy between arrays of different sizes in Rust?
The most flexible way is to use iterators to process each element sequentially:
for (place, data) in array1.mut_iter().zip(array2.iter()) {
*place = *data
}
.mut_iter
creates an a Iterator
that gives&mut u8
, that is, mutable references pointing to the slice / array. iter
does the same but with generic links . .zip
takes two iterators and steps over them in blocking mode, causing the elements to appear as from a tuple (and stop as soon as one stops).
If you need / need to do something "fancy" with the data before writing to place
, this is the approach to use.
However, the simple copy function is also provided as separate methods,
-
.copy_from
which is used likearray1.copy_from(array2)
. -
std::slice::bytes::copy_memory
although you need to trim the two arrays because itcopy_memory
requires them to be the same length:use std::cmp; use std::slice::bytes; let len = cmp::min(array1.len(), array2.len()); bytes::copy_memory(array1.mut_slice_to(len), array2.slice_to(len));
(If you know it's
array1
always longerarray2
thenbytes::copy_memory(array1.mut_slice_to(array2.len()), array2)
it should work as well.)
At the moment the version bytes
optimizes the best, right down to the call memcpy
, but hopefully the rustc
/ LLVM improvements will eventually lead them to that.
source to share
You can do it manually
for (dst, src) in array1.iter_mut().zip(&array2) {
*dst = *src
}
for a typical cut. However, clone_from_slice
there is a faster specialization:
dst[..4].clone_from_slice(&src)
A slightly older method is to use the std::io::Write
one that was implemented for &mut [u8]
.
use std::io::Write;
let _ = dst.write(&src)
This will write to the end dst
and return how many values ββwere written to Result
. If you use write_all
this will return Err
if not all bytes can be written.
source to share