tokio_util/io/sink_writer.rs
1use futures_sink::Sink;
2
3use futures_core::stream::Stream;
4use pin_project_lite::pin_project;
5use std::io;
6use std::pin::Pin;
7use std::task::{ready, Context, Poll};
8use tokio::io::{AsyncRead, AsyncWrite};
9
10pin_project! {
11 /// Convert a [`Sink`] of byte chunks into an [`AsyncWrite`].
12 ///
13 /// Whenever you write to this [`SinkWriter`], the supplied bytes are
14 /// forwarded to the inner [`Sink`]. When `shutdown` is called on this
15 /// [`SinkWriter`], the inner sink is closed.
16 ///
17 /// This adapter takes a `Sink<&[u8]>` and provides an [`AsyncWrite`] impl
18 /// for it. Because of the lifetime, this trait is relatively rarely
19 /// implemented. The main ways to get a `Sink<&[u8]>` that you can use with
20 /// this type are:
21 ///
22 /// * With the codec module by implementing the [`Encoder`]`<&[u8]>` trait.
23 /// * By wrapping a `Sink<Bytes>` in a [`CopyToBytes`].
24 /// * Manually implementing `Sink<&[u8]>` directly.
25 ///
26 /// The opposite conversion of implementing `Sink<_>` for an [`AsyncWrite`]
27 /// is done using the [`codec`] module.
28 ///
29 /// # Example
30 ///
31 /// ```
32 /// use bytes::Bytes;
33 /// use futures_util::SinkExt;
34 /// use std::io::{Error, ErrorKind};
35 /// use tokio::io::AsyncWriteExt;
36 /// use tokio_util::io::{SinkWriter, CopyToBytes};
37 /// use tokio_util::sync::PollSender;
38 ///
39 /// # #[tokio::main(flavor = "current_thread")]
40 /// # async fn main() -> Result<(), Error> {
41 /// // We use an mpsc channel as an example of a `Sink<Bytes>`.
42 /// let (tx, mut rx) = tokio::sync::mpsc::channel::<Bytes>(1);
43 /// let sink = PollSender::new(tx).sink_map_err(|_| Error::from(ErrorKind::BrokenPipe));
44 ///
45 /// // Wrap it in `CopyToBytes` to get a `Sink<&[u8]>`.
46 /// let mut writer = SinkWriter::new(CopyToBytes::new(sink));
47 ///
48 /// // Write data to our interface...
49 /// let data: [u8; 4] = [1, 2, 3, 4];
50 /// let _ = writer.write(&data).await?;
51 ///
52 /// // ... and receive it.
53 /// assert_eq!(data.as_slice(), &*rx.recv().await.unwrap());
54 /// # Ok(())
55 /// # }
56 /// ```
57 ///
58 /// [`AsyncWrite`]: tokio::io::AsyncWrite
59 /// [`CopyToBytes`]: crate::io::CopyToBytes
60 /// [`Encoder`]: crate::codec::Encoder
61 /// [`Sink`]: futures_sink::Sink
62 /// [`codec`]: crate::codec
63 #[derive(Debug)]
64 pub struct SinkWriter<S> {
65 #[pin]
66 inner: S,
67 }
68}
69
70impl<S> SinkWriter<S> {
71 /// Creates a new [`SinkWriter`].
72 pub fn new(sink: S) -> Self {
73 Self { inner: sink }
74 }
75
76 /// Gets a reference to the underlying sink.
77 pub fn get_ref(&self) -> &S {
78 &self.inner
79 }
80
81 /// Gets a mutable reference to the underlying sink.
82 pub fn get_mut(&mut self) -> &mut S {
83 &mut self.inner
84 }
85
86 /// Consumes this [`SinkWriter`], returning the underlying sink.
87 pub fn into_inner(self) -> S {
88 self.inner
89 }
90}
91impl<S, E> AsyncWrite for SinkWriter<S>
92where
93 for<'a> S: Sink<&'a [u8], Error = E>,
94 E: Into<io::Error>,
95{
96 fn poll_write(
97 self: Pin<&mut Self>,
98 cx: &mut Context<'_>,
99 buf: &[u8],
100 ) -> Poll<Result<usize, io::Error>> {
101 let mut this = self.project();
102
103 ready!(this.inner.as_mut().poll_ready(cx).map_err(Into::into))?;
104 match this.inner.as_mut().start_send(buf) {
105 Ok(()) => Poll::Ready(Ok(buf.len())),
106 Err(e) => Poll::Ready(Err(e.into())),
107 }
108 }
109
110 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
111 self.project().inner.poll_flush(cx).map_err(Into::into)
112 }
113
114 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
115 self.project().inner.poll_close(cx).map_err(Into::into)
116 }
117}
118
119impl<S: Stream> Stream for SinkWriter<S> {
120 type Item = S::Item;
121 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
122 self.project().inner.poll_next(cx)
123 }
124}
125
126impl<S: AsyncRead> AsyncRead for SinkWriter<S> {
127 fn poll_read(
128 self: Pin<&mut Self>,
129 cx: &mut Context<'_>,
130 buf: &mut tokio::io::ReadBuf<'_>,
131 ) -> Poll<io::Result<()>> {
132 self.project().inner.poll_read(cx, buf)
133 }
134}