Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to clone a fixed-sized array?

Tags:

rust

I have a struct that consists of a fixed-size byte array with 65536 elements.

I've implemented Clone on my struct naively — I create a new array and loop through the original, copying each element one-at-a-time. Is there a more efficient or idiomatic way of doing this that would essentially boil down to a memcpy?

like image 917
w.brian Avatar asked Nov 04 '25 13:11

w.brian


1 Answers

Since Rust 1.21

Arrays of items that are Clone always implement Clone, so you can simply call .clone() on the array, or #[derive(Clone)] on the struct.

Before Rust 1.21

As of Rust 1.12, arrays only implement Clone for up to 32 items. However, arrays implement Copy for any number of items (despite Copy requiring Clone!). We can therefore make an implicit copy of the array in our implementation of Clone.

struct Foo {
    b: [u8; 65536],
}

impl Clone for Foo {
    fn clone(&self) -> Self {
        Foo {
            b: self.b
        }
    }
}

If you also want your struct to implement Copy, then you can also implement Clone::clone by just making a copy of self:

#[derive(Copy)]
struct Foo {
    b: [u8; 65536],
}

impl Clone for Foo {
    fn clone(&self) -> Self {
        *self
    }
}
like image 151
Francis Gagné Avatar answered Nov 06 '25 04:11

Francis Gagné



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!