Skip to main content

trillium_tokio/server/
tcp.rs

1use crate::TokioTransport;
2use async_compat::Compat;
3use std::{future::Future, io::Result, pin::Pin};
4use tokio::{
5    net::{TcpListener, TcpStream},
6    spawn,
7};
8use trillium::Info;
9use trillium_server_common::Server;
10
11/// Tcp-only Trillium server for Tokio
12#[derive(Debug)]
13pub struct TokioServer(TcpListener);
14
15impl From<TcpListener> for TokioServer {
16    fn from(value: TcpListener) -> Self {
17        Self(value)
18    }
19}
20
21impl Server for TokioServer {
22    type Transport = TokioTransport<Compat<TcpStream>>;
23    const DESCRIPTION: &'static str = concat!(
24        " (",
25        env!("CARGO_PKG_NAME"),
26        " v",
27        env!("CARGO_PKG_VERSION"),
28        ")"
29    );
30
31    fn accept(&mut self) -> Pin<Box<dyn Future<Output = Result<Self::Transport>> + Send + '_>> {
32        Box::pin(async move {
33            self.0
34                .accept()
35                .await
36                .map(|(t, _)| TokioTransport(Compat::new(t)))
37        })
38    }
39
40    fn listener_from_tcp(tcp: std::net::TcpListener) -> Self {
41        Self(tcp.try_into().unwrap())
42    }
43
44    fn info(&self) -> Info {
45        self.0.local_addr().unwrap().into()
46    }
47
48    fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
49        spawn(fut);
50    }
51
52    fn block_on(fut: impl Future<Output = ()> + 'static) {
53        crate::block_on(fut);
54    }
55}