Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Itertools::filter_{,map_}results #377

Merged
merged 4 commits into from Jun 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
152 changes: 145 additions & 7 deletions src/adaptors/mod.rs
Expand Up @@ -1074,28 +1074,31 @@ where
I::Item: Into<R>,
{}

/// An iterator adapter to apply a transformation within a nested `Result`.
#[deprecated(note="Use MapOk instead", since="0.10")]
pub type MapResults<I, F> = MapOk<I, F>;

/// An iterator adapter to apply a transformation within a nested `Result::Ok`.
///
/// See [`.map_results()`](../trait.Itertools.html#method.map_results) for more information.
/// See [`.map_ok()`](../trait.Itertools.html#method.map_ok) for more information.
#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct MapResults<I, F> {
pub struct MapOk<I, F> {
iter: I,
f: F
}

/// Create a new `MapResults` iterator.
pub fn map_results<I, F, T, U, E>(iter: I, f: F) -> MapResults<I, F>
/// Create a new `MapOk` iterator.
pub fn map_ok<I, F, T, U, E>(iter: I, f: F) -> MapOk<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(T) -> U,
{
MapResults {
MapOk {
iter,
f,
}
}

impl<I, F, T, U, E> Iterator for MapResults<I, F>
impl<I, F, T, U, E> Iterator for MapOk<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(T) -> U,
{
Expand Down Expand Up @@ -1124,6 +1127,141 @@ impl<I, F, T, U, E> Iterator for MapResults<I, F>
}
}

/// An iterator adapter to filter values within a nested `Result::Ok`.
///
/// See [`.filter_ok()`](../trait.Itertools.html#method.filter_ok) for more information.
#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct FilterOk<I, F> {
iter: I,
f: F
}

/// Create a new `FilterOk` iterator.
pub fn filter_ok<I, F, T, E>(iter: I, f: F) -> FilterOk<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(&T) -> bool,
{
FilterOk {
iter,
f,
}
}

impl<I, F, T, E> Iterator for FilterOk<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(&T) -> bool,
{
type Item = Result<T, E>;

fn next(&mut self) -> Option<Self::Item> {
loop {
match self.iter.next() {
Some(Ok(v)) => {
if (self.f)(&v) {
return Some(Ok(v));
}
},
Some(Err(e)) => return Some(Err(e)),
None => return None,
}
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.iter.size_hint().1)
}

fn fold<Acc, Fold>(self, init: Acc, fold_f: Fold) -> Acc
where Fold: FnMut(Acc, Self::Item) -> Acc,
{
let mut f = self.f;
self.iter.filter(|v| {
v.as_ref().map(&mut f).unwrap_or(true)
}).fold(init, fold_f)
}

fn collect<C>(self) -> C
where C: FromIterator<Self::Item>
{
let mut f = self.f;
self.iter.filter(|v| {
v.as_ref().map(&mut f).unwrap_or(true)
}).collect()
}
}

/// An iterator adapter to filter and apply a transformation on values within a nested `Result::Ok`.
///
/// See [`.filter_map_ok()`](../trait.Itertools.html#method.filter_map_ok) for more information.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct FilterMapOk<I, F> {
iter: I,
f: F
}

fn transpose_result<T, E>(result: Result<Option<T>, E>) -> Option<Result<T, E>> {
match result {
Ok(Some(v)) => Some(Ok(v)),
Ok(None) => None,
Err(e) => Some(Err(e)),
}
}

/// Create a new `FilterOk` iterator.
pub fn filter_map_ok<I, F, T, U, E>(iter: I, f: F) -> FilterMapOk<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(T) -> Option<U>,
{
FilterMapOk {
iter,
f,
}
}

impl<I, F, T, U, E> Iterator for FilterMapOk<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(T) -> Option<U>,
{
type Item = Result<U, E>;

fn next(&mut self) -> Option<Self::Item> {
loop {
match self.iter.next() {
Some(Ok(v)) => {
if let Some(v) = (self.f)(v) {
return Some(Ok(v));
}
},
Some(Err(e)) => return Some(Err(e)),
None => return None,
}
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.iter.size_hint().1)
}

fn fold<Acc, Fold>(self, init: Acc, fold_f: Fold) -> Acc
where Fold: FnMut(Acc, Self::Item) -> Acc,
{
let mut f = self.f;
self.iter.filter_map(|v| {
transpose_result(v.map(&mut f))
}).fold(init, fold_f)
}

fn collect<C>(self) -> C
where C: FromIterator<Self::Item>
{
let mut f = self.f;
self.iter.filter_map(|v| {
transpose_result(v.map(&mut f))
}).collect()
}
}

/// An iterator adapter to get the positions of each element that matches a predicate.
///
/// See [`.positions()`](../trait.Itertools.html#method.positions) for more information.
Expand Down
69 changes: 62 additions & 7 deletions src/lib.rs
Expand Up @@ -80,10 +80,13 @@ pub mod structs {
DedupBy,
Interleave,
InterleaveShortest,
FilterMapOk,
FilterOk,
Product,
PutBack,
Batching,
MapInto,
MapOk,
MapResults,
Merge,
MergeBy,
Expand Down Expand Up @@ -719,6 +722,14 @@ pub trait Itertools : Iterator {
adaptors::map_into(self)
}

#[deprecated(note="Use .map_ok() instead", since="0.10")]
fn map_results<F, T, U, E>(self, f: F) -> MapOk<Self, F>
where Self: Iterator<Item = Result<T, E>> + Sized,
F: FnMut(T) -> U,
{
self.map_ok(f)
}

/// Return an iterator adaptor that applies the provided closure
/// to every `Result::Ok` value. `Result::Err` values are
/// unchanged.
Expand All @@ -727,14 +738,50 @@ pub trait Itertools : Iterator {
/// use itertools::Itertools;
///
/// let input = vec![Ok(41), Err(false), Ok(11)];
/// let it = input.into_iter().map_results(|i| i + 1);
/// let it = input.into_iter().map_ok(|i| i + 1);
/// itertools::assert_equal(it, vec![Ok(42), Err(false), Ok(12)]);
/// ```
fn map_results<F, T, U, E>(self, f: F) -> MapResults<Self, F>
fn map_ok<F, T, U, E>(self, f: F) -> MapOk<Self, F>
where Self: Iterator<Item = Result<T, E>> + Sized,
F: FnMut(T) -> U,
{
adaptors::map_results(self, f)
adaptors::map_ok(self, f)
}

/// Return an iterator adaptor that filters every `Result::Ok`
/// value with the provided closure. `Result::Err` values are
/// unchanged.
///
/// ```
/// use itertools::Itertools;
///
/// let input = vec![Ok(22), Err(false), Ok(11)];
/// let it = input.into_iter().filter_ok(|&i| i > 20);
/// itertools::assert_equal(it, vec![Ok(22), Err(false)]);
/// ```
fn filter_ok<F, T, E>(self, f: F) -> FilterOk<Self, F>
where Self: Iterator<Item = Result<T, E>> + Sized,
F: FnMut(&T) -> bool,
{
adaptors::filter_ok(self, f)
}

/// Return an iterator adaptor that filters and transforms every
/// `Result::Ok` value with the provided closure. `Result::Err`
/// values are unchanged.
///
/// ```
/// use itertools::Itertools;
///
/// let input = vec![Ok(22), Err(false), Ok(11)];
/// let it = input.into_iter().filter_map_ok(|i| if i > 20 { Some(i * 2) } else { None });
/// itertools::assert_equal(it, vec![Ok(44), Err(false)]);
/// ```
fn filter_map_ok<F, T, U, E>(self, f: F) -> FilterMapOk<Self, F>
where Self: Iterator<Item = Result<T, E>> + Sized,
F: FnMut(T) -> Option<U>,
{
adaptors::filter_map_ok(self, f)
}

/// Return an iterator adaptor that merges the two base iterators in
Expand Down Expand Up @@ -1723,6 +1770,14 @@ pub trait Itertools : Iterator {
format::new_format(self, sep, format)
}

#[deprecated(note="Use .fold_ok() instead", since="0.10")]
fn fold_results<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E>
where Self: Iterator<Item = Result<A, E>>,
F: FnMut(B, A) -> B
{
self.fold_ok(start, f)
}

/// Fold `Result` values from an iterator.
///
/// Only `Ok` values are folded. If no error is encountered, the folded
Expand Down Expand Up @@ -1755,17 +1810,17 @@ pub trait Itertools : Iterator {
/// assert_eq!(
/// values.iter()
/// .map(Ok::<_, ()>)
/// .fold_results(0, Add::add),
/// .fold_ok(0, Add::add),
/// Ok(3)
/// );
/// assert!(
/// values.iter()
/// .map(|&x| if x >= 0 { Ok(x) } else { Err("Negative number") })
/// .fold_results(0, Add::add)
/// .fold_ok(0, Add::add)
/// .is_err()
/// );
/// ```
fn fold_results<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E>
fn fold_ok<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E>
where Self: Iterator<Item = Result<A, E>>,
F: FnMut(B, A) -> B
{
Expand All @@ -1784,7 +1839,7 @@ pub trait Itertools : Iterator {
/// value is returned inside `Some`. Otherwise, the operation terminates
/// and returns `None`. No iterator elements are consumed after the `None`.
///
/// This is the `Option` equivalent to `fold_results`.
/// This is the `Option` equivalent to `fold_ok`.
///
/// ```
/// use std::ops::Add;
Expand Down