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 map_err and err_into iterator adapters #714

Open
wants to merge 3 commits into
base: master
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
72 changes: 72 additions & 0 deletions src/adaptors/map.rs
@@ -1,6 +1,8 @@
use std::iter::FromIterator;
use std::marker::PhantomData;

use crate::traits::TryIterator;

#[derive(Clone, Debug)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct MapSpecialCase<I, F> {
Expand Down Expand Up @@ -122,3 +124,73 @@ pub fn map_into<I, R>(iter: I) -> MapInto<I, R> {
f: MapSpecialCaseFnInto(PhantomData),
}
}

/// An iterator adapter to apply a transformation within a nested `Result::Err`.
///
/// See [`.map_err()`](crate::Itertools::map_err) for more information.
pub type MapErr<I, F> = MapSpecialCase<I, MapSpecialCaseFnErr<F>>;

/// Create a new `MapErr` iterator.
pub(crate) fn map_err<I, F, T, E, E2>(iter: I, f: F) -> MapErr<I, F>
where
I: Iterator<Item = Result<T, E>>,
F: FnMut(E) -> E2,
{
MapSpecialCase {
iter,
f: MapSpecialCaseFnErr(f),
}
}

#[derive(Clone)]
pub struct MapSpecialCaseFnErr<F>(F);

impl<F> std::fmt::Debug for MapSpecialCaseFnErr<F> {
debug_fmt_fields!(MapSpecialCaseFnErr,);
}

impl<F, T, E, E2> MapSpecialCaseFn<Result<T, E>> for MapSpecialCaseFnErr<F>
where
F: FnMut(E) -> E2,
{
type Out = Result<T, E2>;

fn call(&mut self, r: Result<T, E>) -> Self::Out {
r.map_err(|v| self.0(v))
}
}

/// An iterator adapter to convert a nested `Result::Err` using [`Into`].
///
/// See [`.map_err()`](crate::Itertools::map_err) for more information.
pub type ErrInto<I, F> = MapSpecialCase<I, MapSpecialCaseFnErrInto<F>>;

/// Create a new `ErrInto` iterator.
pub(crate) fn err_into<I, E>(iter: I) -> ErrInto<I, E>
where
I: TryIterator,
<I as TryIterator>::Error: Into<E>,
{
MapSpecialCase {
iter,
f: MapSpecialCaseFnErrInto(PhantomData),
}
}

#[derive(Clone)]
pub struct MapSpecialCaseFnErrInto<E2>(PhantomData<E2>);

impl<F> std::fmt::Debug for MapSpecialCaseFnErrInto<F> {
debug_fmt_fields!(MapSpecialCaseFnErrInto,);
}

impl<T, E, E2> MapSpecialCaseFn<Result<T, E>> for MapSpecialCaseFnErrInto<E2>
where
E: Into<E2>,
{
type Out = Result<T, E2>;

fn call(&mut self, r: Result<T, E>) -> Self::Out {
r.map_err(Into::into)
}
}
5 changes: 4 additions & 1 deletion src/adaptors/mod.rs
Expand Up @@ -7,13 +7,16 @@
mod coalesce;
mod map;
mod multi_product;

pub use self::coalesce::*;
pub use self::map::{map_into, map_ok, MapInto, MapOk};
pub use self::map::{map_into, map_ok, MapInto, MapOk, MapErr, ErrInto};
#[allow(deprecated)]
pub use self::map::MapResults;
#[cfg(feature = "use_alloc")]
pub use self::multi_product::*;

pub(crate) use self::map::{map_err, err_into};

use std::fmt;
use std::iter::{Fuse, Peekable, FromIterator, FusedIterator};
use std::marker::PhantomData;
Expand Down
44 changes: 44 additions & 0 deletions src/lib.rs
Expand Up @@ -99,6 +99,8 @@ pub mod structs {
Batching,
MapInto,
MapOk,
MapErr,
ErrInto,
Merge,
MergeBy,
TakeWhileRef,
Expand Down Expand Up @@ -162,6 +164,7 @@ pub mod structs {

/// Traits helpful for using certain `Itertools` methods in generic contexts.
pub mod traits {
pub use crate::try_iterator::TryIterator;
pub use crate::tuple_impl::HomogeneousTuple;
}

Expand Down Expand Up @@ -237,6 +240,7 @@ mod sources;
mod take_while_inclusive;
#[cfg(feature = "use_alloc")]
mod tee;
mod try_iterator;
mod tuple_impl;
#[cfg(feature = "use_std")]
mod duplicates_impl;
Expand Down Expand Up @@ -928,6 +932,46 @@ pub trait Itertools : Iterator {
flatten_ok::flatten_ok(self)
}

/// Return an iterator adaptor that applies the provided closure to every
/// [`Result::Err`] value. [`Result::Ok`] values are unchanged.
///
/// # Examples
///
/// ```
/// use itertools::Itertools;
///
/// let iterator = vec![Ok(41), Err(0), Ok(11)].into_iter();
/// let mapped = iterator.map_err(|x| x + 2);
/// itertools::assert_equal(mapped, vec![Ok(41), Err(2), Ok(11)]);
/// ```
fn map_err<F, T, E, E2>(self, f: F) -> MapErr<Self, F>
where
Self: Iterator<Item = Result<T, E>> + Sized,
F: FnMut(E) -> E2,
{
adaptors::map_err(self, f)
}

/// Return an iterator adaptor that converts every [`Result::Err`] value
/// using the [`Into`] trait.
///
/// # Examples
///
/// ```
/// use itertools::Itertools;
///
/// let iterator = vec![Ok(()), Err(5i32)].into_iter();
/// let converted = iterator.err_into::<i64>();
/// itertools::assert_equal(converted, vec![Ok(()), Err(5i64)]);
/// ```
fn err_into<E>(self) -> ErrInto<Self, E>
where
Self: traits::TryIterator + Sized,
<Self as traits::TryIterator>::Error: Into<E>,
{
adaptors::err_into(self)
}

/// “Lift” a function of the values of the current iterator so as to process
/// an iterator of `Result` values instead.
///
Expand Down
34 changes: 34 additions & 0 deletions src/try_iterator.rs
@@ -0,0 +1,34 @@
mod private {
pub trait Sealed {}
impl<I, T, E> Sealed for I where I: Iterator<Item = Result<T, E>> {}
}

/// Helper trait automatically implemented for [`Iterator`]s of [`Result`]s.
///
/// Can be useful for specifying certain trait bounds more concisely. Take
/// [`.err_into()`][err_into] for example:
///
/// Without [`TryIterator`], [`err_into`][err_into] would have to be generic
/// over 3 type parameters: the type of [`Result::Ok`] values, the type of
/// [`Result::Err`] values, and the type to convert errors into. Usage would
/// look like this: `my_iterator.err_into<_, _, E>()`.
///
/// Using [`TryIterator`], [`err_into`][err_into] can be generic over a single
/// type parameter, and called like this: `my_iterator.err_into<E>()`.
///
/// [err_into]: crate::Itertools::err_into
pub trait TryIterator: Iterator + private::Sealed {
/// The type of [`Result::Ok`] values yielded by this [`Iterator`].
type Ok;

/// The type of [`Result::Err`] values yielded by this [`Iterator`].
type Error;
}

impl<I, T, E> TryIterator for I
where
I: Iterator<Item = Result<T, E>>,
{
type Ok = T;
type Error = E;
}
12 changes: 12 additions & 0 deletions tests/specializations.rs
Expand Up @@ -105,6 +105,18 @@ quickcheck! {
}
}

quickcheck! {
fn map_err(v: Vec<Result<char, u8>>) -> () {
test_specializations(&v.into_iter().map_err(|u| u.checked_add(1)));
}
}

quickcheck! {
fn err_into(v: Vec<Result<char, u8>>) -> () {
test_specializations(&v.into_iter().err_into::<u16>());
}
}

quickcheck! {
fn process_results(v: Vec<Result<u8, u8>>) -> () {
helper(v.iter().copied());
Expand Down