Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

rust - How can I write data from a slice to the same slice?

I want to write the end of a slice to the top of the same 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]);

I've seen How to operate on 2 mutable slices of a Rust array

I want the maximum performance possible (for example, by using foo.as_ptr()).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To copy data from one range inside a slice to another in general (allowing overlap), we can't even use .split_at_mut().

I would use .split_at_mut() primarily otherwise. (Is there anything that makes you think the bounds check is not going to be optimized out? Also, are you copying enough data that it's a small effect in comparison?)

Anyway, this is how you could wrap std::ptr::copy (overlap-allowing copy, a.k.a memmove) in a safe or an unsafe function.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...