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
93
94
95
96
97
98
99
100
101
102
103
use std::{
borrow::Cow,
fmt::{self, Display, Formatter},
};
#[derive(Debug, Clone)]
pub enum Addr {
SocketAddr(std::net::SocketAddr),
#[cfg(unix)]
#[cfg_attr(docsrs, doc(cfg(unix)))]
Unix(std::sync::Arc<tokio::net::unix::SocketAddr>),
Custom(&'static str, Cow<'static, str>),
}
impl Default for Addr {
fn default() -> Self {
Self::Custom("unknown", "unknown".into())
}
}
impl PartialEq for Addr {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Addr::SocketAddr(addr1), Addr::SocketAddr(addr2)) => addr1 == addr2,
#[cfg(unix)]
(Addr::Unix(addr1), Addr::Unix(addr2)) => addr1.as_pathname() == addr2.as_pathname(),
(Addr::Custom(scheme1, addr1), Addr::Custom(scheme2, addr2)) => {
scheme1 == scheme2 && addr1 == addr2
}
_ => false,
}
}
}
impl From<std::net::SocketAddr> for Addr {
fn from(addr: std::net::SocketAddr) -> Self {
Addr::SocketAddr(addr)
}
}
#[cfg(unix)]
impl From<tokio::net::unix::SocketAddr> for Addr {
fn from(addr: tokio::net::unix::SocketAddr) -> Self {
Addr::Unix(addr.into())
}
}
impl Addr {
pub fn socket(addr: std::net::SocketAddr) -> Self {
Self::SocketAddr(addr)
}
#[cfg(unix)]
#[cfg_attr(docsrs, doc(cfg(unix)))]
pub fn unix(addr: tokio::net::unix::SocketAddr) -> Self {
Self::Unix(addr.into())
}
pub fn custom(scheme: &'static str, addr: impl Into<Cow<'static, str>>) -> Self {
Self::Custom(scheme, addr.into())
}
pub fn as_socket_addr(&self) -> Option<&std::net::SocketAddr> {
match self {
Addr::SocketAddr(addr) => Some(addr),
_ => None,
}
}
#[cfg(unix)]
#[cfg_attr(docsrs, doc(cfg(unix)))]
pub fn as_unix_socket_addr(&self) -> Option<&tokio::net::unix::SocketAddr> {
match self {
Addr::Unix(addr) => Some(addr),
_ => None,
}
}
}
impl Display for Addr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Addr::SocketAddr(addr) => write!(f, "socket://{}", addr),
#[cfg(unix)]
Addr::Unix(addr) => match addr.as_pathname() {
Some(path) => write!(f, "unix://{}", path.display()),
None => f.write_str("unix://unknown"),
},
Addr::Custom(scheme, addr) => write!(f, "{}://{}", scheme, addr),
}
}
}