How do you copy between arrays of different sizes in Rust?

If I have two arrays of different sizes:

let mut array1 = [0; 8];
let array2 = [1, 2, 3, 4];

      

How to copy array2

in the first 4 bytes array1

? I can take a mutable 4 byte slice of array1, but I'm not sure how or if I can assign to it.

+3


source to share


2 answers


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 like array1.copy_from(array2)

    .

  • std::slice::bytes::copy_memory

    although you need to trim the two arrays because it copy_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 longer array2

    then bytes::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.

+5


source


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.

+4


source







All Articles