wasmtime_wasi_http/
io.rs

1//! I/O utility for bridging between `tokio::io` and `hyper::rt`.
2
3use hyper::rt::{Read, ReadBufCursor, Write};
4use std::io::Error;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
8
9/// A type that wraps any type implementing [`tokio::io::AsyncRead`] and [`tokio::io::AsyncWrite`]
10/// and itself implements [`hyper::rt::Read`] and [`hyper::rt::Write`].
11#[derive(Debug)]
12pub struct TokioIo<T> {
13    inner: T,
14}
15
16impl<T> TokioIo<T> {
17    /// Create a new `TokioIo` wrapping the given inner type.
18    pub fn new(inner: T) -> TokioIo<T> {
19        TokioIo { inner }
20    }
21}
22
23impl<T: AsyncRead + Unpin> Read for TokioIo<T> {
24    fn poll_read(
25        mut self: Pin<&mut Self>,
26        cx: &mut Context<'_>,
27        mut buf: ReadBufCursor<'_>,
28    ) -> Poll<Result<(), Error>> {
29        unsafe {
30            let mut dst = ReadBuf::uninit(buf.as_mut());
31            let res = Pin::new(&mut self.inner).poll_read(cx, &mut dst);
32            let amt = dst.filled().len();
33            buf.advance(amt);
34            res
35        }
36    }
37}
38
39impl<T: AsyncWrite + Unpin> Write for TokioIo<T> {
40    fn poll_write(
41        mut self: Pin<&mut Self>,
42        cx: &mut Context<'_>,
43        buf: &[u8],
44    ) -> Poll<Result<usize, Error>> {
45        Pin::new(&mut self.inner).poll_write(cx, buf)
46    }
47
48    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
49        Pin::new(&mut self.inner).poll_flush(cx)
50    }
51
52    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
53        Pin::new(&mut self.inner).poll_shutdown(cx)
54    }
55}