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 TryFutureExt::{inspect_ok, inspect_err} #1630

Merged
merged 1 commit into from
May 25, 2019
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion futures-util/src/future/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ pub trait FutureExt: Future {
/// # });
/// ```
fn inspect<F>(self, f: F) -> Inspect<Self, F>
where F: FnOnce(&Self::Output) -> (),
where F: FnOnce(&Self::Output),
Self: Sized,
{
assert_future::<Self::Output, _>(Inspect::new(self, f))
Expand Down
49 changes: 49 additions & 0 deletions futures-util/src/try_future/inspect_err.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future, TryFuture};
use futures_core::task::{Context, Poll};
use pin_utils::{unsafe_pinned, unsafe_unpinned};

/// Future for the [`inspect_err`](super::TryFutureExt::inspect_err) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct InspectErr<Fut, F> {
future: Fut,
f: Option<F>,
}

impl<Fut: Unpin, F> Unpin for InspectErr<Fut, F> {}

impl<Fut, F> InspectErr<Fut, F>
where
Fut: TryFuture,
F: FnOnce(&Fut::Error),
{
unsafe_pinned!(future: Fut);
unsafe_unpinned!(f: Option<F>);

pub(super) fn new(future: Fut, f: F) -> Self {
Self { future, f: Some(f) }
}
}

impl<Fut: FusedFuture, F> FusedFuture for InspectErr<Fut, F> {
fn is_terminated(&self) -> bool {
self.future.is_terminated()
}
}

impl<Fut, F> Future for InspectErr<Fut, F>
where
Fut: TryFuture,
F: FnOnce(&Fut::Error),
{
type Output = Result<Fut::Ok, Fut::Error>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let e = ready!(self.as_mut().future().try_poll(cx));
if let Err(e) = &e {
self.as_mut().f().take().expect("cannot poll InspectErr twice")(e);
}
Poll::Ready(e)
}
}
49 changes: 49 additions & 0 deletions futures-util/src/try_future/inspect_ok.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future, TryFuture};
use futures_core::task::{Context, Poll};
use pin_utils::{unsafe_pinned, unsafe_unpinned};

/// Future for the [`inspect_ok`](super::TryFutureExt::inspect_ok) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct InspectOk<Fut, F> {
future: Fut,
f: Option<F>,
}

impl<Fut: Unpin, F> Unpin for InspectOk<Fut, F> {}

impl<Fut, F> InspectOk<Fut, F>
where
Fut: TryFuture,
F: FnOnce(&Fut::Ok),
{
unsafe_pinned!(future: Fut);
unsafe_unpinned!(f: Option<F>);

pub(super) fn new(future: Fut, f: F) -> Self {
Self { future, f: Some(f) }
}
}

impl<Fut: FusedFuture, F> FusedFuture for InspectOk<Fut, F> {
fn is_terminated(&self) -> bool {
self.future.is_terminated()
}
}

impl<Fut, F> Future for InspectOk<Fut, F>
where
Fut: TryFuture,
F: FnOnce(&Fut::Ok),
{
type Output = Result<Fut::Ok, Fut::Error>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let e = ready!(self.as_mut().future().try_poll(cx));
if let Ok(e) = &e {
self.as_mut().f().take().expect("cannot poll InspectOk twice")(e);
}
Poll::Ready(e)
}
}
58 changes: 58 additions & 0 deletions futures-util/src/try_future/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ pub use self::err_into::ErrInto;
mod flatten_sink;
pub use self::flatten_sink::FlattenSink;

mod inspect_ok;
pub use self::inspect_ok::InspectOk;

mod inspect_err;
pub use self::inspect_err::InspectErr;

mod into_future;
pub use self::into_future::IntoFuture;

Expand Down Expand Up @@ -322,6 +328,58 @@ pub trait TryFutureExt: TryFuture {
OrElse::new(self, f)
}

/// Do something with the success value of a future before passing it on.
///
/// When using futures, you'll often chain several of them together. While
/// working on such code, you might want to check out what's happening at
/// various parts in the pipeline, without consuming the intermediate
/// value. To do that, insert a call to `inspect_ok`.
///
/// # Examples
///
/// ```
/// #![feature(async_await)]
/// # futures::executor::block_on(async {
/// use futures::future::{self, TryFutureExt};
///
/// let future = future::ok::<_, ()>(1);
/// let new_future = future.inspect_ok(|&x| println!("about to resolve: {}", x));
/// assert_eq!(new_future.await, Ok(1));
/// # });
/// ```
fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where F: FnOnce(&Self::Ok),
Self: Sized,
{
InspectOk::new(self, f)
}

/// Do something with the error value of a future before passing it on.
///
/// When using futures, you'll often chain several of them together. While
/// working on such code, you might want to check out what's happening at
/// various parts in the pipeline, without consuming the intermediate
/// value. To do that, insert a call to `inspect_err`.
///
/// # Examples
///
/// ```
/// #![feature(async_await)]
/// # futures::executor::block_on(async {
/// use futures::future::{self, TryFutureExt};
///
/// let future = future::err::<(), _>(1);
/// let new_future = future.inspect_err(|&x| println!("about to error: {}", x));
/// assert_eq!(new_future.await, Err(1));
/// # });
/// ```
fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where F: FnOnce(&Self::Error),
Self: Sized,
{
InspectErr::new(self, f)
}

/// Flatten the execution of this future when the successful result of this
/// future is a stream.
///
Expand Down
2 changes: 1 addition & 1 deletion futures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ pub mod future {

TryFutureExt,
AndThen, ErrInto, FlattenSink, IntoFuture, MapErr, MapOk, OrElse,
TryFlattenStream, UnwrapOrElse,
InspectOk, InspectErr, TryFlattenStream, UnwrapOrElse,
};

#[cfg(feature = "never-type")]
Expand Down