Search code examples
algorithmrustmemmove

Is there an equivalent of C++ std::copy in Rust?


The std::copy function in C++ copies elements pointed at by one iterator over the elements pointed at by another iterator. One important aspect of std::copy in C++ is that good implementations optimize by using std::memmove if the type of the iterated elements is TriviallyCopyable in C++ speak (a type that implements the Copy trait in Rust speak).

Is there currently anything equivalent or similar to C++ std::copy in the Rust standard library?


Solution

  • Iterators in Rust and iterators in C++ are different things. Rust iterators are similar to ones in Java and other high-level languages - they are not pointer-like things, they are a kind of "producers" of data. So it is just not possible to optimize them to copy data in bulk - it may make no sense at all for some iterator because it can, for example, return an infinite sequence of values.

    The closest thing you can do, I guess, is something like this (for Copy types; for Clone types *t = *s will become *t = s.clone()):

    fn main() {
        let     source = [1i, 2, 3, 4, 5];
        let mut target = [1i, 1, 1, 1, 1];
    
        println!("source: {}", source.as_slice());
        println!("target: {}", target.as_slice());
        println!("-------");
    
        for (s, t) in source.iter().zip(target.mut_iter()) {
            *t = *s;
        }
    
        println!("source: {}", source.as_slice());
        println!("target: {}", target.as_slice());
    }