如何将切片中的数据写入同一切片?

时间:2016-09-20 21:30:50

标签: rust slice

我想将切片的末尾写到同一切片的顶部。

let mut foo = [1, 2, 3, 4, 5];

foo[..2].copy_from_slice(&[4..]); // error: multiple references to same data (mut and not)

assert!(foo, [4, 5, 3, 4, 5]);

我见过How to operate on 2 mutable slices of a Rust array

我希望获得最高性能(例如,使用foo.as_ptr())。

4 个答案:

答案 0 :(得分:7)

要将数据从切片内的一个范围复制到另一个范围(允许重叠),我们甚至无法使用.split_at_mut()

我主要使用.split_at_mut()。 (有没有什么能让你认为边界检查不会被优化?另外,你是否复制了足够的数据,相比之下它的影响很小?)

无论如何,这就是你如何在安全或std::ptr::copy函数中包装unsafe(允许重叠的复制,a.k.a memmove)。

use std::ptr::copy;
use std::ops::Range;

/// Copy the range `data[from]` onto the index `to` and following
///
/// **Panics** if `from` or `to` is out of bounds
pub fn move_memory<T: Copy>(data: &mut [T], from: Range<usize>, to: usize) {
    assert!(from.start <= from.end);
    assert!(from.end <= data.len());
    assert!(to <= data.len() - (from.end - from.start));
    unsafe {
        move_memory_unchecked(data, from, to);
    }
}

pub unsafe fn move_memory_unchecked<T: Copy>(data: &mut [T], from: Range<usize>, to: usize) {
    debug_assert!(from.start <= from.end);
    debug_assert!(from.end <= data.len());
    debug_assert!(to <= data.len() - (from.end - from.start));
    let ptr = data.as_mut_ptr();
    copy(ptr.offset(from.start as isize),
         ptr.offset(to as isize),
         from.end - from.start)
}

fn main() {
    let mut data = [0, 1, 2, 3, 4, 5, 6, 7];
    move_memory(&mut data, 2..6, 0);
    println!("{:?}", data);
    move_memory(&mut data, 0..3, 5);
    println!("{:?}", data);
}

Playground link

答案 1 :(得分:3)

如果您的类型实施Copy ,则子项不重叠:

fn main() {
    let mut v = [1, 2, 3, 4, 5, 6];

    {
        let (left, right) = v.split_at_mut(3);
        // Perform further work to ensure slices are the same length, as needed
        left.copy_from_slice(right);
    }

    assert!(v == [4, 5, 6, 4, 5, 6]);
}

答案 2 :(得分:2)

我找到了一个更好的方法来做我想要的事情:

fn main() {
    let mut v = [1, 2, 3, 4, 5, 6];

    // scoped to restrict the lifetime of the borrows
    {
        let (left, right) = v.split_at_mut(3);
        assert!(left == [1, 2, 3]);
        assert!(right == [4, 5, 6]);
        for (l, r) in left.iter_mut().zip(right) {
            *l = *r;
        }
    }

    assert!(v == [4, 5, 6, 4, 5, 6]);
}

答案 3 :(得分:2)

Rust 1.37 (2019-08-15)添加了库函数slice::copy_within,它可以完全满足您的需求:

let mut foo = [1, 2, 3, 4, 5];

foo.copy_within(3 .. 5, 0);  // <-- THIS

assert_eq!(foo, [4, 5, 3, 4, 5]);