有没有办法将ChunkMut <t>从Vec :: chunks_mut转换为slice&mut [T]?

时间:2019-02-24 04:27:38

标签: vector rust

我正在并行填充向量,但是对于这个一般性问题,我只发现了提示而没有答案。

下面的代码有效,但是我想切换到Rng::fill而不是遍历每个块。单个Vec中可能没有多个可变切片;我不确定。

extern crate rayon;
extern crate rand;
extern crate rand_xoshiro;

use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256StarStar;
use rayon::prelude::*;
use std::{iter, env};
use std::sync::{Arc, Mutex};

// i16 because I was filling up my RAM for large tests...
fn gen_rand_vec(data: &mut [i16]) {
    let num_threads = rayon::current_num_threads();
    let mut rng = rand::thread_rng();
    let mut prng = Xoshiro256StarStar::from_rng(&mut rng).unwrap();
    // lazy iterator of fast, unique RNGs
    // Arc and Mutex are just so it can be accessed from multiple threads
    let rng_it = Arc::new(Mutex::new(iter::repeat(()).map(|()| {
        let new_prng = prng.clone();
        prng.jump();
        new_prng
    })));
    // generates random numbers for each chunk in parallel
    // par_chunks_mut is parallel version of chunks_mut
    data.par_chunks_mut(data.len() / num_threads).for_each(|chunk| {
        // I used extra braces because it might be required to unlock Mutex. 
        // Not sure.
        let mut prng = { rng_it.lock().unwrap().next().unwrap() };
        for i in chunk.iter_mut() {
            *i = prng.gen_range(-1024, 1024);
        }
    });
}

1 个答案:

答案 0 :(得分:0)

事实证明,ChunksMut迭代器提供了切片。我不确定如何从文档中收集信息。我是通过阅读the source来弄清楚的:

#[derive(Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct ChunksMut<'a, T:'a> {
    v: &'a mut [T],
    chunk_size: usize
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for ChunksMut<'a, T> {
    type Item = &'a mut [T];

    #[inline]
    fn next(&mut self) -> Option<&'a mut [T]> {
        if self.v.is_empty() {
            None
        } else {
            let sz = cmp::min(self.v.len(), self.chunk_size);
            let tmp = mem::replace(&mut self.v, &mut []);
            let (head, tail) = tmp.split_at_mut(sz);
            self.v = tail;
            Some(head)
        }
}

我想这只是经验;对于其他人来说,很明显,ChunksMut<T>中类型为Vec<T>的迭代器返回类型为[T]的对象。现在这很有意义。对于中间结构,还不是很清楚。

pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T>
// ...
impl<'a, T> Iterator for ChunksMut<'a, T>

阅读此内容后,看起来迭代器返回的类型为T的对象,与Vec<T>.iter()相同,这没有任何意义。