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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::{io::Result, path::Path};
use tokio::{
io::Result as IoResult,
net::{UnixListener as TokioUnixListener, UnixStream},
};
use crate::{
listener::{Acceptor, Listener},
web::{LocalAddr, RemoteAddr},
};
#[cfg_attr(docsrs, doc(cfg(unix)))]
pub struct UnixListener<T> {
path: T,
}
impl<T> UnixListener<T> {
pub fn bind(path: T) -> Self {
Self { path }
}
}
#[async_trait::async_trait]
impl<T: AsRef<Path> + Send> Listener for UnixListener<T> {
type Acceptor = UnixAcceptor;
async fn into_acceptor(self) -> IoResult<Self::Acceptor> {
let listener = TokioUnixListener::bind(self.path)?;
let local_addr = listener
.local_addr()
.map(|addr| LocalAddr(addr.into()))
.unwrap_or_default();
Ok(UnixAcceptor {
local_addr,
listener,
})
}
}
#[cfg_attr(docsrs, doc(cfg(unix)))]
pub struct UnixAcceptor {
local_addr: LocalAddr,
listener: TokioUnixListener,
}
#[async_trait::async_trait]
impl Acceptor for UnixAcceptor {
type Io = UnixStream;
#[inline]
fn local_addr(&self) -> Vec<LocalAddr> {
vec![self.local_addr.clone()]
}
#[inline]
async fn accept(&mut self) -> Result<(Self::Io, LocalAddr, RemoteAddr)> {
let (stream, addr) = self.listener.accept().await?;
Ok((stream, self.local_addr.clone(), RemoteAddr(addr.into())))
}
}
#[cfg(test)]
mod tests {
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
time::Duration,
};
use super::*;
#[tokio::test]
async fn unix_listener() {
let listener = UnixListener::bind("test-socket");
let mut acceptor = listener.into_acceptor().await.unwrap();
tokio::spawn(async move {
let mut stream = UnixStream::connect("test-socket").await.unwrap();
stream.write_i32(10).await.unwrap();
});
let (mut stream, _, _) = acceptor.accept().await.unwrap();
assert_eq!(stream.read_i32().await.unwrap(), 10);
tokio::time::sleep(Duration::from_secs(1)).await;
drop(acceptor);
std::fs::remove_file("test-socket").unwrap();
}
}