| 1 | use core::pin::Pin; |
| 2 | |
| 3 | use pin_project_lite::pin_project; |
| 4 | |
| 5 | use crate::stream::Stream; |
| 6 | use crate::task::{Context, Poll}; |
| 7 | |
| 8 | pin_project! { |
| 9 | /// A stream that does something with each element of another stream. |
| 10 | /// |
| 11 | /// This `struct` is created by the [`inspect`] method on [`Stream`]. See its |
| 12 | /// documentation for more. |
| 13 | /// |
| 14 | /// [`inspect`]: trait.Stream.html#method.inspect |
| 15 | /// [`Stream`]: trait.Stream.html |
| 16 | #[derive (Debug)] |
| 17 | pub struct Inspect<S, F> { |
| 18 | #[pin] |
| 19 | stream: S, |
| 20 | f: F, |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | impl<S, F> Inspect<S, F> { |
| 25 | pub(super) fn new(stream: S, f: F) -> Self { |
| 26 | Self { |
| 27 | stream, |
| 28 | f, |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl<S, F> Stream for Inspect<S, F> |
| 34 | where |
| 35 | S: Stream, |
| 36 | F: FnMut(&S::Item), |
| 37 | { |
| 38 | type Item = S::Item; |
| 39 | |
| 40 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 41 | let mut this: Projection<'_, S, F> = self.project(); |
| 42 | let next: Option<::Item> = futures_core::ready!(this.stream.as_mut().poll_next(cx)); |
| 43 | |
| 44 | Poll::Ready(next.map(|x: ::Item| { |
| 45 | (this.f)(&x); |
| 46 | x |
| 47 | })) |
| 48 | } |
| 49 | } |
| 50 | |