Problem with understanding Rayon IntoParallelRefIterator

#1

Hi, I recently tried to understand the mechanism of IntoParallelRefIterator in Rayon framework and tried to copy all the related struct and trait to a single file and play. But the code can’t compile.

//Sorry for paste all the code here, just try to explain...
fn get_iter(v: &[i32]) {
    //this can't compile. But I think I have put all the related code in the file.

    //no method named `par_iter` found for type `&[i32]` in the current scope
    // note: the method `par_iter` exists but the following trait bounds were not satisfied:
    //       `[i32] : IntoParallelRefIterator`
    //       `&[i32] : IntoParallelRefIterator`
    //       `[i32] : IntoParallelRefIterator`
    let iter = v.par_iter();

    //Do something with iter
}

trait IntoParallelRefIterator<'data> {
    type Iter: ParallelIterator<Item = Self::Item>;

    type Item: Send + 'data;

    fn par_iter(&'data self) -> Self::Iter;
}

//I think IntoParallelRefIterator has been implemented automatically
//for all IntoParallelIterator
impl<'data, I: 'data + ?Sized> IntoParallelRefIterator<'data> for I
where
    &'data I: IntoParallelIterator,
{
    type Iter = <&'data I as IntoParallelIterator>::Iter;
    type Item = <&'data I as IntoParallelIterator>::Item;

    fn par_iter(&'data self) -> Self::Iter {
        self.into_par_iter()
    }
}

trait IntoParallelIterator {
    type Iter: ParallelIterator<Item = Self::Item>;

    type Item: Send;

    fn into_par_iter(self) -> Self::Iter;
}

//And here Vec implemented the IntoParallelIterator
impl<T: Send> IntoParallelIterator for Vec<T> {
    type Item = T;
    type Iter = IntoIter<T>;

    fn into_par_iter(self) -> Self::Iter {
        IntoIter { vec: self }
    }
}

#[derive(Debug, Clone)]
pub struct IntoIter<T: Send> {
    vec: Vec<T>,
}

trait ParallelIterator {
    type Item: Send;

    fn drive_unindexed(self);
}

trait IndexedParallelIterator {
    fn drive(self);
}

impl<T: Send> ParallelIterator for IntoIter<T> {
    type Item = T;

    fn drive_unindexed(self) {}
}

impl<T: Send> IndexedParallelIterator for IntoIter<T> {
    fn drive(self) {}
}

I basically just copy and paste the code from Rayon source code, really want to know what did the trick to making this compiled, thank you for the patience to read the long code, thank you very much!

0 Likes

#2

I think this is the one you need:

1 Like

#3

Thank you so very much for answer my dumb question… I can finally continue…

0 Likes