Skip to content

Commit

Permalink
Add SockAddr::as_unix
Browse files Browse the repository at this point in the history
Returns the SocketAddr type used by the standard library for Unix
sockets.
  • Loading branch information
Thomasdezeeuw committed Apr 11, 2023
1 parent 3deba62 commit 81d75df
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/sys/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -741,8 +741,17 @@ impl SockAddr {
}
}

/// Returns this address as a `Path` reference if it is an `AF_UNIX` pathname address, otherwise
/// returns `None`.
/// Returns this address as Unix `SocketAddr` if it is an `AF_UNIX` pathname
/// address, otherwise returns `None`.
pub fn as_unix(&self) -> Option<std::os::unix::net::SocketAddr> {
let path = self.as_pathname()?;
// SAFETY: we can represent this as a valid pathname, then so can the
// standard library.
Some(std::os::unix::net::SocketAddr::from_pathname(path).unwrap())
}

/// Returns this address as a `Path` reference if it is an `AF_UNIX`
/// pathname address, otherwise returns `None`.
pub fn as_pathname(&self) -> Option<&Path> {
self.as_sockaddr_un().and_then(|storage| {
(self.len() > offset_of_path(storage) as u32 && storage.sun_path[0] != 0).then(|| {
Expand Down
3 changes: 3 additions & 0 deletions tests/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ fn socket_address_unix() {
assert!(!addr.is_unnamed());
assert_eq!(addr.as_pathname(), Some(Path::new(string)));
assert_eq!(addr.as_abstract_namespace(), None);
let unix = addr.as_unix().unwrap();
assert_eq!(addr.as_pathname(), unix.as_pathname());
}
}

Expand All @@ -172,6 +174,7 @@ fn socket_address_unix_unnamed() {
assert!(addr.is_unnamed());
assert_eq!(addr.as_pathname(), None);
assert_eq!(addr.as_abstract_namespace(), None);
assert!(addr.as_unix().is_none());
}
}

Expand Down

0 comments on commit 81d75df

Please sign in to comment.