hyper_serve/
accept.rs

1//! [`Accept`] trait and utilities.
2
3use std::{
4    future::{Future, Ready},
5    io,
6};
7
8use tokio::net::TcpStream;
9
10/// An asynchronous function to modify io stream and service.
11pub trait Accept<I, S> {
12    /// IO stream produced by accept.
13    type Stream;
14
15    /// Service produced by accept.
16    type Service;
17
18    /// Future return value.
19    type Future: Future<Output = io::Result<(Self::Stream, Self::Service)>>;
20
21    /// Process io stream and service asynchronously.
22    fn accept(&self, stream: I, service: S) -> Self::Future;
23}
24
25/// A no-op acceptor.
26#[derive(Clone, Copy, Debug, Default)]
27pub struct DefaultAcceptor;
28
29impl DefaultAcceptor {
30    /// Create a new default acceptor.
31    pub fn new() -> Self {
32        Self
33    }
34}
35
36impl<I, S> Accept<I, S> for DefaultAcceptor {
37    type Stream = I;
38    type Service = S;
39    type Future = Ready<io::Result<(Self::Stream, Self::Service)>>;
40
41    fn accept(&self, stream: I, service: S) -> Self::Future {
42        std::future::ready(Ok((stream, service)))
43    }
44}
45
46/// An acceptor that sets `TCP_NODELAY` on accepted streams.
47#[derive(Clone, Copy, Debug, Default)]
48pub struct NoDelayAcceptor;
49
50impl NoDelayAcceptor {
51    /// Create a new acceptor that sets `TCP_NODELAY` on accepted streams.
52    pub fn new() -> Self {
53        Self
54    }
55}
56
57impl<S> Accept<TcpStream, S> for NoDelayAcceptor {
58    type Stream = TcpStream;
59    type Service = S;
60    type Future = Ready<io::Result<(Self::Stream, Self::Service)>>;
61
62    fn accept(&self, stream: TcpStream, service: S) -> Self::Future {
63        std::future::ready(stream.set_nodelay(true).and(Ok((stream, service))))
64    }
65}