diff options
author | Matthias Beyer <mail@beyermatthias.de> | 2018-02-01 16:49:22 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-02-01 16:49:22 +0100 |
commit | 581a9acd6fef99a8365f7b9896a8bc4e4d0bdd7a (patch) | |
tree | b0d521514bda0f6c2a3ba1de3dfc8440f600ad70 | |
parent | f21f7c57a63a63b07fb56e58deb6bedda8591fd8 (diff) | |
parent | 152f9b5c2bac34bad7b164455953bfc56fa00967 (diff) |
Merge pull request #25 from matthiasbeyer/filtered-iterators
Add convenience helper for filtering iterators
-rw-r--r-- | src/iter.rs | 64 | ||||
-rw-r--r-- | src/lib.rs | 1 |
2 files changed, 65 insertions, 0 deletions
diff --git a/src/iter.rs b/src/iter.rs new file mode 100644 index 0000000..79675d1 --- /dev/null +++ b/src/iter.rs @@ -0,0 +1,64 @@ +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// + +use filter::Filter; + +pub struct FilteredIterator<T, F, I>(F, I) + where F: Filter<T>, + I: Iterator<Item = T>; + +impl<T, F, I> Iterator for FilteredIterator<T, F, I> + where F: Filter<T>, + I: Iterator<Item = T> +{ + type Item = T; + + fn next(&mut self) -> Option<Self::Item> { + while let Some(next) = self.1.next() { + if self.0.filter(&next) { + return Some(next); + } + } + + None + } +} + +pub trait FilterWith<T, F: Filter<T>> : Iterator<Item = T> + Sized { + fn filter_with(self, f: F) -> FilteredIterator<T, F, Self>; +} + +impl<I, T, F: Filter<T>> FilterWith<T, F> for I + where I: Iterator<Item = T> +{ + fn filter_with(self, f: F) -> FilteredIterator<T, F, Self> { + FilteredIterator(f, self) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_filter_with() { + struct Foo; + impl Filter<u64> for Foo { + fn filter(&self, u: &u64) -> bool { + *u > 5 + } + } + + let foo = Foo; + + let v : Vec<u64> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0] + .into_iter() + .filter_with(foo) + .collect(); + + assert_eq!(v, vec![6, 7, 8, 9]); + } +} @@ -78,5 +78,6 @@ pub mod impl_traits; pub mod filter; pub mod failable; +pub mod iter; pub mod ops; |