1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use crate::TokioTransport;
use async_compat::Compat;
use std::{future::Future, io::Result, pin::Pin};
use tokio::{
    net::{TcpListener, TcpStream},
    spawn,
};
use trillium::Info;
use trillium_server_common::Server;

/// Tcp-only Trillium server for Tokio
#[derive(Debug)]
pub struct TokioServer(TcpListener);

impl From<TcpListener> for TokioServer {
    fn from(value: TcpListener) -> Self {
        Self(value)
    }
}

impl Server for TokioServer {
    type Transport = TokioTransport<Compat<TcpStream>>;
    const DESCRIPTION: &'static str = concat!(
        " (",
        env!("CARGO_PKG_NAME"),
        " v",
        env!("CARGO_PKG_VERSION"),
        ")"
    );

    fn accept(&mut self) -> Pin<Box<dyn Future<Output = Result<Self::Transport>> + Send + '_>> {
        Box::pin(async move {
            self.0
                .accept()
                .await
                .map(|(t, _)| TokioTransport(Compat::new(t)))
        })
    }

    fn listener_from_tcp(tcp: std::net::TcpListener) -> Self {
        Self(tcp.try_into().unwrap())
    }

    fn info(&self) -> Info {
        self.0.local_addr().unwrap().into()
    }

    fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
        spawn(fut);
    }

    fn block_on(fut: impl Future<Output = ()> + 'static) {
        crate::block_on(fut);
    }
}