From 152f9b5c2bac34bad7b164455953bfc56fa00967 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 1 Feb 2018 16:02:33 +0100 Subject: Add convenience helper for filtering iterators --- src/iter.rs | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 65 insertions(+) create mode 100644 src/iter.rs 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(F, I) + where F: Filter, + I: Iterator; + +impl Iterator for FilteredIterator + where F: Filter, + I: Iterator +{ + type Item = T; + + fn next(&mut self) -> Option { + while let Some(next) = self.1.next() { + if self.0.filter(&next) { + return Some(next); + } + } + + None + } +} + +pub trait FilterWith> : Iterator + Sized { + fn filter_with(self, f: F) -> FilteredIterator; +} + +impl> FilterWith for I + where I: Iterator +{ + fn filter_with(self, f: F) -> FilteredIterator { + FilteredIterator(f, self) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_filter_with() { + struct Foo; + impl Filter for Foo { + fn filter(&self, u: &u64) -> bool { + *u > 5 + } + } + + let foo = Foo; + + let v : Vec = 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]); + } +} diff --git a/src/lib.rs b/src/lib.rs index 7da2cc5..ff5d7ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -78,5 +78,6 @@ pub mod impl_traits; pub mod filter; pub mod failable; +pub mod iter; pub mod ops; -- cgit v1.2.3