Skip to content

Commit a51b0a2

Browse files
committed
Use mem::offset_of! for sockaddr_un.sun_path
1 parent 0399709 commit a51b0a2

1 file changed

Lines changed: 6 additions & 11 deletions

File tree

‎library/std/src/os/unix/net/addr.rs‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,7 @@ mod libc {
1818
pubstructsockaddr_un;
1919
}
2020

21-
fnsun_path_offset(addr:&libc::sockaddr_un) -> usize{
22-
// Work with an actual instance of the type since using a null pointer is UB
23-
let base = (addr as*const libc::sockaddr_un).addr();
24-
let path = core::ptr::addr_of!(addr.sun_path).addr();
25-
path - base
26-
}
21+
constSUN_PATH_OFFSET:usize = mem::offset_of!(libc::sockaddr_un, sun_path);
2722

2823
pub(super)fnsockaddr_un(path:&Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)>{
2924
// SAFETY: All zeros is a valid representation for `sockaddr_un`.
@@ -53,7 +48,7 @@ pub(super) fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::s
5348
ptr::copy_nonoverlapping(bytes.as_ptr(), addr.sun_path.as_mut_ptr().cast(), bytes.len())
5449
};
5550

56-
letmut len = sun_path_offset(&addr) + bytes.len();
51+
letmut len = SUN_PATH_OFFSET + bytes.len();
5752
match bytes.get(0){
5853
Some(&0) | None => {}
5954
Some(_) => len += 1,
@@ -114,13 +109,13 @@ impl SocketAddr {
114109
let sun_path:&[u8] =
115110
unsafe{ mem::transmute::<&[libc::c_char],&[u8]>(&addr.sun_path)};
116111
len = core::slice::memchr::memchr(0, sun_path)
117-
.map_or(len, |new_len| (new_len + sun_path_offset(&addr))as libc::socklen_t);
112+
.map_or(len, |new_len| (new_len + SUN_PATH_OFFSET)as libc::socklen_t);
118113
}
119114

120115
if len == 0{
121116
// When there is a datagram from unnamed unix socket
122117
// linux returns zero bytes of address
123-
len = sun_path_offset(&addr)as libc::socklen_t;// i.e., zero-length address
118+
len = SUN_PATH_OFFSETas libc::socklen_t;// i.e., zero-length address
124119
}elseif addr.sun_family != libc::AF_UNIXas libc::sa_family_t{
125120
returnErr(io::const_io_error!(
126121
io::ErrorKind::InvalidInput,
@@ -238,7 +233,7 @@ impl SocketAddr {
238233
}
239234

240235
fnaddress(&self) -> AddressKind<'_>{
241-
let len = self.lenasusize - sun_path_offset(&self.addr);
236+
let len = self.lenasusize - SUN_PATH_OFFSET;
242237
let path = unsafe{ mem::transmute::<&[libc::c_char],&[u8]>(&self.addr.sun_path)};
243238

244239
// macOS seems to return a len of 16 and a zeroed sun_path for unnamed addresses
@@ -287,7 +282,7 @@ impl linux_ext::addr::SocketAddrExt for SocketAddr {
287282
addr.sun_path.as_mut_ptr().add(1)as*mutu8,
288283
name.len(),
289284
);
290-
let len = (sun_path_offset(&addr) + 1 + name.len())as libc::socklen_t;
285+
let len = (SUN_PATH_OFFSET + 1 + name.len())as libc::socklen_t;
291286
SocketAddr::from_parts(addr, len)
292287
}
293288
}

0 commit comments

Comments
 (0)