Skip to content

Commit 81d75df

Browse files
committed
Add SockAddr::as_unix
Returns the SocketAddr type used by the standard library for Unix sockets.
1 parent 3deba62 commit 81d75df

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/sys/unix.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -741,8 +741,17 @@ impl SockAddr {
741741
}
742742
}
743743

744-
/// Returns this address as a `Path` reference if it is an `AF_UNIX` pathname address, otherwise
745-
/// returns `None`.
744+
/// Returns this address as Unix `SocketAddr` if it is an `AF_UNIX` pathname
745+
/// address, otherwise returns `None`.
746+
pub fn as_unix(&self) -> Option<std::os::unix::net::SocketAddr> {
747+
let path = self.as_pathname()?;
748+
// SAFETY: we can represent this as a valid pathname, then so can the
749+
// standard library.
750+
Some(std::os::unix::net::SocketAddr::from_pathname(path).unwrap())
751+
}
752+
753+
/// Returns this address as a `Path` reference if it is an `AF_UNIX`
754+
/// pathname address, otherwise returns `None`.
746755
pub fn as_pathname(&self) -> Option<&Path> {
747756
self.as_sockaddr_un().and_then(|storage| {
748757
(self.len() > offset_of_path(storage) as u32 && storage.sun_path[0] != 0).then(|| {

tests/socket.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ fn socket_address_unix() {
155155
assert!(!addr.is_unnamed());
156156
assert_eq!(addr.as_pathname(), Some(Path::new(string)));
157157
assert_eq!(addr.as_abstract_namespace(), None);
158+
let unix = addr.as_unix().unwrap();
159+
assert_eq!(addr.as_pathname(), unix.as_pathname());
158160
}
159161
}
160162

@@ -172,6 +174,7 @@ fn socket_address_unix_unnamed() {
172174
assert!(addr.is_unnamed());
173175
assert_eq!(addr.as_pathname(), None);
174176
assert_eq!(addr.as_abstract_namespace(), None);
177+
assert!(addr.as_unix().is_none());
175178
}
176179
}
177180

0 commit comments

Comments
 (0)