1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//! Extension trait for `Sink`.

use std::{
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

use futures::{ready, sink::Sink};
use pin_project::pin_project;

/// Extension trait for `Sink`
pub trait SinkExt<Item>: Sink<Item> {
    /// As `Sink::with`, but takes a function that returns an `Item` rather
    /// than `Future<Output=Item>`.
    fn with_fn<F, T, E>(self, func: F) -> WithFn<Self, F, T, E>
    // or error?
    where
        Self: Sized,
        F: FnMut(T) -> Result<Item, E>,
        E: From<Self::Error>;
}

impl<Item, S> SinkExt<Item> for S
where
    S: Sink<Item>,
{
    fn with_fn<F, T, E>(self, func: F) -> WithFn<Self, F, T, E>
    where
        Self: Sized,
        F: FnMut(T) -> Result<Item, E>,
        E: From<Self::Error>,
    {
        WithFn {
            sink: self,
            func,
            _phantom: PhantomData,
        }
    }
}

/// Sink returned by [`SinkExt::with_fn`].
#[pin_project]
pub struct WithFn<S, F, T, E> {
    /// The underlying sink
    #[pin]
    sink: S,
    /// The user-provided function.
    func: F,
    /// Phantom data to ensure type consistency.
    _phantom: PhantomData<fn() -> Result<T, E>>,
}

impl<S, Item, F, T, E> Sink<T> for WithFn<S, F, T, E>
where
    S: Sink<Item>,
    F: FnMut(T) -> Result<Item, E>,
    E: From<S::Error>,
{
    type Error = E;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        ready!(self.project().sink.poll_ready(cx))?;
        Poll::Ready(Ok(()))
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        ready!(self.project().sink.poll_flush(cx))?;
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        ready!(self.project().sink.poll_close(cx))?;
        Poll::Ready(Ok(()))
    }

    fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
        let this = self.project();
        let item = (this.func)(item)?;
        this.sink.start_send(item).map_err(E::from)
    }
}