Skip to main content

compio_tls/
tokio_io.rs

1//! [`tokio::io`] traits for the TLS streams, so that crates written against
2//! them (`h2`, `tonic`...) run over compio TLS without a tokio runtime.
3
4use std::{
5    io,
6    pin::Pin,
7    task::{Context, Poll, ready},
8};
9
10use futures_util::{AsyncRead, AsyncWrite};
11use tokio::io::ReadBuf;
12
13use crate::{MaybeTlsStream, TlsStream};
14
15macro_rules! impl_tokio {
16    ($t:ident) => {
17        impl<S> tokio::io::AsyncRead for $t<S>
18        where
19            S: AsyncRead + AsyncWrite + Unpin,
20        {
21            fn poll_read(
22                self: Pin<&mut Self>,
23                cx: &mut Context<'_>,
24                buf: &mut ReadBuf<'_>,
25            ) -> Poll<io::Result<()>> {
26                let n = ready!(AsyncRead::poll_read(self, cx, buf.initialize_unfilled()))?;
27                buf.advance(n);
28                Poll::Ready(Ok(()))
29            }
30        }
31
32        impl<S> tokio::io::AsyncWrite for $t<S>
33        where
34            S: AsyncRead + AsyncWrite + Unpin,
35        {
36            fn poll_write(
37                self: Pin<&mut Self>,
38                cx: &mut Context<'_>,
39                buf: &[u8],
40            ) -> Poll<io::Result<usize>> {
41                AsyncWrite::poll_write(self, cx, buf)
42            }
43
44            fn poll_write_vectored(
45                self: Pin<&mut Self>,
46                cx: &mut Context<'_>,
47                bufs: &[io::IoSlice<'_>],
48            ) -> Poll<io::Result<usize>> {
49                AsyncWrite::poll_write_vectored(self, cx, bufs)
50            }
51
52            fn is_write_vectored(&self) -> bool {
53                self.writes_vectored()
54            }
55
56            fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
57                AsyncWrite::poll_flush(self, cx)
58            }
59
60            fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
61                AsyncWrite::poll_close(self, cx)
62            }
63        }
64    };
65}
66
67impl_tokio!(TlsStream);
68impl_tokio!(MaybeTlsStream);