tower_web/
net.rs

1//! Networking types and trait
2
3use futures::{Stream, Poll};
4use tokio::net::TcpStream;
5use tokio_io::{AsyncRead, AsyncWrite};
6
7use std::io;
8use std::net::SocketAddr;
9
10#[cfg(feature = "rustls")]
11use tokio_rustls::{TlsStream, rustls::ServerSession};
12
13/// A stream between a local and remote target.
14pub trait Connection: AsyncRead + AsyncWrite {
15    /// Returns the socket address of the remote peer of this connection.
16    fn peer_addr(&self) -> Option<SocketAddr>;
17}
18
19/// An asynchronous stream of connections.
20pub trait ConnectionStream {
21    /// Connection type yielded each iteration.
22    type Item: Connection;
23
24    /// Attempt to resolve the next connection, registering the current task for
25    /// wakeup if one is not yet available.
26    fn poll_next(&mut self) -> Poll<Option<Self::Item>, io::Error>;
27}
28
29impl Connection for TcpStream {
30    fn peer_addr(&self) -> Option<SocketAddr> {
31        TcpStream::peer_addr(self).ok()
32    }
33}
34
35#[cfg(feature = "rustls")]
36impl Connection for TlsStream<TcpStream, ServerSession> {
37    fn peer_addr(&self) -> Option<SocketAddr> {
38        TcpStream::peer_addr(self.get_ref().0).ok()
39    }
40}
41
42impl<T> ConnectionStream for T
43where
44    T: Stream<Error = io::Error>,
45    T::Item: Connection,
46{
47    type Item = <Self as Stream>::Item;
48
49    fn poll_next(&mut self) -> Poll<Option<Self::Item>, io::Error> {
50        self.poll()
51    }
52}
53
54#[derive(Debug)]
55pub(crate) struct Lift<T>(pub(crate) T);
56
57impl<T: ConnectionStream> Stream for Lift<T> {
58    type Item = <T as ConnectionStream>::Item;
59    type Error = io::Error;
60
61    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
62        self.0.poll_next()
63    }
64}