tor_async_utils/
sinkext.rs1use std::{
4 marker::PhantomData,
5 pin::Pin,
6 task::{Context, Poll},
7};
8
9use futures::{ready, sink::Sink};
10use pin_project::pin_project;
11
12pub trait SinkExt<Item>: Sink<Item> {
14 fn with_fn<F, T, E>(self, func: F) -> WithFn<Self, F, T, E>
17 where
19 Self: Sized,
20 F: FnMut(T) -> Result<Item, E>,
21 E: From<Self::Error>,
22 {
23 WithFn {
24 sink: self,
25 func,
26 _phantom: PhantomData,
27 }
28 }
29}
30
31impl<Item, S> SinkExt<Item> for S where S: Sink<Item> {}
32
33#[pin_project]
35pub struct WithFn<S, F, T, E> {
36 #[pin]
38 sink: S,
39 func: F,
41 _phantom: PhantomData<fn() -> Result<T, E>>,
43}
44
45impl<S, Item, F, T, E> Sink<T> for WithFn<S, F, T, E>
46where
47 S: Sink<Item>,
48 F: FnMut(T) -> Result<Item, E>,
49 E: From<S::Error>,
50{
51 type Error = E;
52
53 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
54 ready!(self.project().sink.poll_ready(cx))?;
55 Poll::Ready(Ok(()))
56 }
57
58 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
59 ready!(self.project().sink.poll_flush(cx))?;
60 Poll::Ready(Ok(()))
61 }
62
63 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
64 ready!(self.project().sink.poll_close(cx))?;
65 Poll::Ready(Ok(()))
66 }
67
68 fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
69 let this = self.project();
70 let item = (this.func)(item)?;
71 this.sink.start_send(item).map_err(E::from)
72 }
73}