Skip to main content

static_web_server/
transport.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Static Web Server.
3// See https://static-web-server.net/ for more information
4// Copyright (C) 2019-present Jose Quintana <joseluisq.net>
5
6//! Async transport module.
7//!
8
9// Most of the file is borrowed from https://github.com/seanmonstar/warp/blob/master/src/transport.rs
10
11use std::io;
12use std::net::SocketAddr;
13use std::pin::Pin;
14use std::task::{Context, Poll};
15
16use hyper::server::conn::AddrStream;
17use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
18
19/// Transport trait that supports the remote (peer) address.
20pub trait Transport: AsyncRead + AsyncWrite {
21    /// Returns the remote (peer) address of this connection.
22    fn remote_addr(&self) -> Option<SocketAddr>;
23}
24
25impl Transport for AddrStream {
26    fn remote_addr(&self) -> Option<SocketAddr> {
27        Some(self.remote_addr())
28    }
29}
30
31/// Type to support `Transport`, `AsyncRead` and `AsyncWrite`.
32pub struct LiftIo<T>(pub T);
33
34impl<T: AsyncRead + Unpin> AsyncRead for LiftIo<T> {
35    fn poll_read(
36        self: Pin<&mut Self>,
37        cx: &mut Context<'_>,
38        buf: &mut ReadBuf<'_>,
39    ) -> Poll<io::Result<()>> {
40        Pin::new(&mut self.get_mut().0).poll_read(cx, buf)
41    }
42}
43
44impl<T: AsyncWrite + Unpin> AsyncWrite for LiftIo<T> {
45    fn poll_write(
46        self: Pin<&mut Self>,
47        cx: &mut Context<'_>,
48        buf: &[u8],
49    ) -> Poll<io::Result<usize>> {
50        Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
51    }
52
53    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
54        Pin::new(&mut self.get_mut().0).poll_flush(cx)
55    }
56
57    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
58        Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
59    }
60}
61
62impl<T: AsyncRead + AsyncWrite + Unpin> Transport for LiftIo<T> {
63    fn remote_addr(&self) -> Option<SocketAddr> {
64        None
65    }
66}