sinktools/
for_each.rs

1//! [`ForEach`] consuming sink.
2use core::pin::Pin;
3use core::task::{Context, Poll};
4
5use pin_project_lite::pin_project;
6
7use crate::Sink;
8
9pin_project! {
10    /// Same as [`core::iterator::ForEach`] but as a [`Sink`].
11    ///
12    /// Synchronously consumes items and always returns `Poll::Ready(Ok(())`.
13    #[must_use = "sinks do nothing unless polled"]
14    pub struct ForEach<Func> {
15        func: Func,
16    }
17}
18impl<Func> ForEach<Func> {
19    /// Create with consuming `func`.
20    pub fn new<Item>(func: Func) -> Self
21    where
22        Self: Sink<Item>,
23    {
24        Self { func }
25    }
26}
27impl<Func, Item> Sink<Item> for ForEach<Func>
28where
29    Func: FnMut(Item),
30{
31    type Error = core::convert::Infallible;
32
33    fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
34        Poll::Ready(Ok(()))
35    }
36
37    fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> {
38        (self.project().func)(item);
39        Ok(())
40    }
41
42    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
43        Poll::Ready(Ok(()))
44    }
45
46    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
47        Poll::Ready(Ok(()))
48    }
49}