rocket/listener/
listener.rs

1use std::io;
2
3use futures::TryFutureExt;
4use tokio_util::either::Either;
5
6use crate::listener::{Connection, Endpoint};
7
8pub trait Listener: Sized + Send + Sync {
9    type Accept: Send;
10
11    type Connection: Connection;
12
13    #[crate::async_bound(Send)]
14    async fn accept(&self) -> io::Result<Self::Accept>;
15
16    #[crate::async_bound(Send)]
17    async fn connect(&self, accept: Self::Accept) -> io::Result<Self::Connection>;
18
19    fn endpoint(&self) -> io::Result<Endpoint>;
20}
21
22impl<L: Listener> Listener for &L {
23    type Accept = L::Accept;
24
25    type Connection = L::Connection;
26
27    async fn accept(&self) -> io::Result<Self::Accept> {
28        <L as Listener>::accept(self).await
29    }
30
31    async fn connect(&self, accept: Self::Accept) -> io::Result<Self::Connection> {
32        <L as Listener>::connect(self, accept).await
33    }
34
35    fn endpoint(&self) -> io::Result<Endpoint> {
36        <L as Listener>::endpoint(self)
37    }
38}
39
40impl<A: Listener, B: Listener> Listener for Either<A, B> {
41    type Accept = Either<A::Accept, B::Accept>;
42
43    type Connection = Either<A::Connection, B::Connection>;
44
45    async fn accept(&self) -> io::Result<Self::Accept> {
46        match self {
47            Either::Left(l) => l.accept().map_ok(Either::Left).await,
48            Either::Right(l) => l.accept().map_ok(Either::Right).await,
49        }
50    }
51
52    async fn connect(&self, accept: Self::Accept) -> io::Result<Self::Connection>  {
53        match (self, accept) {
54            (Either::Left(l), Either::Left(a)) => l.connect(a).map_ok(Either::Left).await,
55            (Either::Right(l), Either::Right(a)) => l.connect(a).map_ok(Either::Right).await,
56            _ => unreachable!()
57        }
58    }
59
60    fn endpoint(&self) -> io::Result<Endpoint> {
61        match self {
62            Either::Left(l) => l.endpoint(),
63            Either::Right(l) => l.endpoint(),
64        }
65    }
66}