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 try_filter_map_results method. #2

Open
wants to merge 4 commits into
base: feature/try_map_results
Choose a base branch
from
Open
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
121 changes: 121 additions & 0 deletions src/adaptors/mod.rs
Expand Up @@ -1159,6 +1159,127 @@ impl<I, F, T, U, E> Iterator for MapResults<I, F>
}
}

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

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

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

fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|v| v.and_then(&mut self.f))
}

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

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

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

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

/// Create a new `TryFilterMapResults` iterator.
pub fn try_filter_map_results<I, F, T, U, E>(iter: I, f: F) -> TryFilterMapResults<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(T) -> Result<Option<U>, E>
{
TryFilterMapResults {
iter: iter,
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)),
}
}

impl<I, F, T, U, E> Iterator for TryFilterMapResults<I, F>
where I: Iterator<Item = Result<T, E>>,
F: FnMut(T) -> Result<Option<U>, E>
{
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).transpose() {
return Some(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.and_then(&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.and_then(&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
38 changes: 38 additions & 0 deletions src/lib.rs
Expand Up @@ -59,6 +59,8 @@ pub mod structs {
Batching,
Step,
MapResults,
TryFilterMapResults,
TryMapResults,
Merge,
MergeBy,
TakeWhileRef,
Expand Down Expand Up @@ -635,6 +637,42 @@ pub trait Itertools : Iterator {
adaptors::map_results(self, f)
}

/// Return an iterator adaptor that applies the provided fallible
/// closure to every `Result::Ok` value. `Result::Err` values in
/// the original iterator are unchanged.
///
/// ```
/// use itertools::Itertools;
///
/// let input = vec![Ok(41), Err(false), Ok(i32::max_value())];
/// let it = input.into_iter().try_map_results(|i| i.checked_add(1).ok_or(true));
/// itertools::assert_equal(it, vec![Ok(42), Err(false), Err(true)]);
/// ```
fn try_map_results<F, T, U, E>(self, f: F) -> TryMapResults<Self, F>
where Self: Iterator<Item = Result<T, E>> + Sized,
F: FnMut(T) -> Result<U, E>,
{
adaptors::try_map_results(self, f)
}

/// Return an iterator adaptor that filters and transforms every
/// `Result::Ok` value with the provided fallible closure.
/// `Result::Err` values in the original iterator are unchanged.
///
/// ```
/// use itertools::Itertools;
///
/// let input = vec![Ok(11), Ok(41), Err(false), Ok(i32::max_value())];
/// let it = input.into_iter().try_filter_map_results(|i| if i > 20 { Some(i.checked_add(1).ok_or(true)).transpose() } else { Ok(None) });
/// itertools::assert_equal(it, vec![Ok(42), Err(false), Err(true)]);
/// ```
fn try_filter_map_results<F, T, U, E>(self, f: F) -> TryFilterMapResults<Self, F>
where Self: Iterator<Item = Result<T, E>> + Sized,
F: FnMut(T) -> Result<Option<U>, E>,
{
adaptors::try_filter_map_results(self, f)
}

/// Return an iterator adaptor that merges the two base iterators in
/// ascending order. If both base iterators are sorted (ascending), the
/// result is sorted.
Expand Down