Search code examples
arraysrustslicememcpyborrow-checker

Copy slice into its own array


I want to copy the values at one slice of an array into another slice.

The obvious way (using iteration) is:

for i in 0..10 {
    self.ram[i] = self.ram[20 + i];
}

However, that seems rather inefficient.

The usual way to copy a slice:

arr[0..10].copy_from_slice(&arr[20..30]);

does not work as arr is borrowed twice.

The only other way to do this that comes to mind is std::ptr::copy_nonoverlapping, which is unsafe.

What is the best way to copy a slice into its own array (while knowing that source and destination do not overlap)?


Solution

  • Using copy_within():

    arr.copy_within(20..30, 0);
    

    Note that it does not require them to not overlap.

    If you're sure they do not overlap, and you want to exploit that, you can use unsafe code:

    let p = arr.as_mut_ptr();
    unsafe {
        std::ptr::copy_nonoverlapping(p.add(20), p, 10);
    }