Skip to content

Commit 3deba62

Browse files
committed
Cleanup PartialEq and Hash impls for SockAddr
1 parent c394ac3 commit 3deba62

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

src/sockaddr.rs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,14 @@ impl SockAddr {
260260
_ => None,
261261
}
262262
}
263+
264+
/// Returns the initialised storage bytes.
265+
fn as_bytes(&self) -> &[u8] {
266+
// SAFETY: `self.storage` is a C struct which can always be treated a
267+
// slice of bytes. Futhermore we ensure we don't read any unitialised
268+
// bytes by using `self.len`.
269+
unsafe { std::slice::from_raw_parts(self.as_ptr().cast(), self.len as usize) }
270+
}
263271
}
264272

265273
impl From<SocketAddr> for SockAddr {
@@ -339,29 +347,18 @@ impl fmt::Debug for SockAddr {
339347

340348
impl PartialEq for SockAddr {
341349
fn eq(&self, other: &Self) -> bool {
342-
unsafe {
343-
let these_bytes: &[u8] = any_as_u8_slice(&self.storage, self.len as usize);
344-
let those_bytes: &[u8] = any_as_u8_slice(&other.storage, other.len as usize);
345-
these_bytes == those_bytes
346-
}
350+
self.as_bytes() == other.as_bytes()
347351
}
348352
}
349353

350354
impl Eq for SockAddr {}
351355

352356
impl Hash for SockAddr {
353357
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
354-
unsafe {
355-
let these_bytes: &[u8] = any_as_u8_slice(&self.storage, self.len as usize);
356-
these_bytes.hash(state);
357-
}
358+
self.as_bytes().hash(state);
358359
}
359360
}
360361

361-
unsafe fn any_as_u8_slice<T: Sized>(p: &T, size: usize) -> &[u8] {
362-
::std::slice::from_raw_parts((p as *const T) as *const u8, size)
363-
}
364-
365362
#[cfg(test)]
366363
mod tests {
367364
use super::*;

0 commit comments

Comments
 (0)