Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading