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
use crate::{ TimeoutIoError, InstantExt, WaitForEvent, EventMask };
use std::{ io::Result as IoResult, time::{ Duration, Instant }, net::{ TcpListener, TcpStream } };
#[doc(hidden)]
pub trait StdAcceptor<T> where Self: WaitForEvent {
fn accept(&self) -> IoResult<T>;
}
impl StdAcceptor<TcpStream> for TcpListener {
fn accept(&self) -> IoResult<TcpStream> {
Ok(TcpListener::accept(self)?.0)
}
}
#[cfg(unix)]
impl StdAcceptor<::std::os::unix::net::UnixStream> for ::std::os::unix::net::UnixListener {
fn accept(&self) -> IoResult<::std::os::unix::net::UnixStream> {
Ok(::std::os::unix::net::UnixListener::accept(self)?.0)
}
}
pub trait Acceptor<T> {
fn accept(&self, timeout: Duration) -> Result<T, TimeoutIoError>;
}
impl<U, T: StdAcceptor<U> + WaitForEvent> Acceptor<U> for T {
fn accept(&self, timeout: Duration) -> Result<U, TimeoutIoError> {
self.set_blocking_mode(false)?;
let timeout_point = Instant::now() + timeout;
loop {
self.wait_for_event(EventMask::new_r(), timeout_point.remaining())?;
match StdAcceptor::accept(self) {
Ok(connection) => return Ok(connection),
Err(error) => {
let error = TimeoutIoError::from(error);
if !error.should_retry() { return Err(error) }
}
}
}
}
}