use crate::{ core::{Collector, Executor}, Consumer, Folder, ParallelIterator, }; use super::noop::NoOpReducer; pub struct ForEach { iterator: I, operation: F, } impl ForEach { pub fn new(iterator: I, operation: F) -> Self { Self { iterator, operation, } } } impl Collector for ForEach where I: ParallelIterator, F: Fn(I::Item) + Sync + Send + Copy, { type Iterator = I; type Consumer = ForEachConsumer; fn exec_with(self, executor: E) -> E::Result where E: Executor, { let iterator = self.iterator; let operation = self.operation; let consumer = ForEachConsumer { operation }; iterator.drive(executor, consumer) } } pub struct ForEachConsumer { operation: F, } impl Consumer for ForEachConsumer where F: Fn(T) + Sync + Send + Copy, { type Folder = ForEachConsumer; type Reducer = NoOpReducer; type Result = (); fn split_off_left(&self) -> (Self, NoOpReducer) { ( ForEachConsumer { operation: self.operation, }, NoOpReducer, ) } fn into_folder(self) -> Self { self } } impl Folder for ForEachConsumer where F: Fn(T) + Sync + Send + Copy, { type Result = (); fn consume(self, item: T) -> Self { (self.operation)(item); self } fn consume_iter(self, iter: I) -> Self where I: IntoIterator, { iter.into_iter().for_each(self.operation); self } fn complete(self) {} } #[cfg(test)] mod tests { use super::*; use crate::*; #[test] fn test_for_each() { (0..10usize) .into_par_iter() .for_each(&|j| { println!("{}", j); }) .exec(); } }