From 8cd0a76438966aec2307c795713038816b7e4ce7 Mon Sep 17 00:00:00 2001 From: Bergmann89 Date: Sat, 7 Nov 2020 19:56:04 +0100 Subject: [PATCH] Implemented 'count' operation --- asparit/src/core/iterator.rs | 16 ++++++++++++++++ asparit/src/inner/count.rs | 23 +++++++++++++++++++++++ asparit/src/inner/mod.rs | 1 + 3 files changed, 40 insertions(+) create mode 100644 asparit/src/inner/count.rs diff --git a/asparit/src/core/iterator.rs b/asparit/src/core/iterator.rs index d515362..d0309ad 100644 --- a/asparit/src/core/iterator.rs +++ b/asparit/src/core/iterator.rs @@ -9,6 +9,7 @@ use crate::{ cloned::Cloned, collect::Collect, copied::Copied, + count::Count, filter::Filter, filter_map::FilterMap, flatten::{FlatMapIter, FlattenIter}, @@ -290,6 +291,21 @@ pub trait ParallelIterator<'a>: Sized + Send { TryForEachInit::new(self, init, operation) } + /// Counts the number of items in this parallel iterator. + /// + /// # Examples + /// + /// ``` + /// use rayon::prelude::*; + /// + /// let count = (0..100).into_par_iter().count(); + /// + /// assert_eq!(count, 100); + /// ``` + fn count(self) -> Count { + Count::new(self) + } + /// Applies `operation` to each item of this iterator, producing a new /// iterator with the results. /// diff --git a/asparit/src/inner/count.rs b/asparit/src/inner/count.rs new file mode 100644 index 0000000..e36f8cb --- /dev/null +++ b/asparit/src/inner/count.rs @@ -0,0 +1,23 @@ +use crate::{Driver, Executor, ParallelIterator}; + +pub struct Count { + iterator: X, +} + +impl Count { + pub fn new(iterator: X) -> Self { + Self { iterator } + } +} + +impl<'a, X> Driver<'a, usize> for Count +where + X: ParallelIterator<'a>, +{ + fn exec_with(self, executor: E) -> E::Result + where + E: Executor<'a, usize>, + { + self.iterator.map(|_| 1).sum().exec_with(executor) + } +} diff --git a/asparit/src/inner/mod.rs b/asparit/src/inner/mod.rs index 27da6ed..897fcdf 100644 --- a/asparit/src/inner/mod.rs +++ b/asparit/src/inner/mod.rs @@ -1,6 +1,7 @@ pub mod cloned; pub mod collect; pub mod copied; +pub mod count; pub mod filter; pub mod filter_map; pub mod flatten;