trillium_tokio/
transport.rs

1use async_compat::Compat;
2use std::{io::Result, net::SocketAddr};
3use tokio::net::{TcpStream, ToSocketAddrs};
4use trillium_macros::{AsyncRead, AsyncWrite};
5use trillium_server_common::{AsyncRead, AsyncWrite, Transport};
6
7/// A transport newtype for tokio
8#[derive(Debug, Clone, AsyncRead, AsyncWrite)]
9pub struct TokioTransport<T>(pub(crate) T);
10
11impl<T> TokioTransport<T> {
12    /// returns the contained type
13    pub fn into_inner(self) -> T {
14        self.0
15    }
16}
17
18impl TokioTransport<Compat<TcpStream>> {
19    /// initiates an outbound http connection
20    pub async fn connect(socket: impl ToSocketAddrs) -> Result<Self> {
21        TcpStream::connect(socket)
22            .await
23            .map(|t| Self(Compat::new(t)))
24    }
25}
26
27impl<T> From<T> for TokioTransport<T> {
28    fn from(value: T) -> Self {
29        Self(value)
30    }
31}
32
33impl Transport for TokioTransport<Compat<TcpStream>> {
34    fn peer_addr(&self) -> Result<Option<SocketAddr>> {
35        self.0.get_ref().peer_addr().map(Some)
36    }
37
38    fn set_ip_ttl(&mut self, ttl: u32) -> Result<()> {
39        self.0.get_mut().set_ttl(ttl)
40    }
41
42    fn set_nodelay(&mut self, nodelay: bool) -> Result<()> {
43        self.0.get_mut().set_nodelay(nodelay)
44    }
45}
46
47#[cfg(unix)]
48impl Transport for TokioTransport<Compat<tokio::net::UnixStream>> {}