@@ -260,6 +260,14 @@ impl SockAddr {
260
260
_ => None ,
261
261
}
262
262
}
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
+ }
263
271
}
264
272
265
273
impl From < SocketAddr > for SockAddr {
@@ -339,29 +347,18 @@ impl fmt::Debug for SockAddr {
339
347
340
348
impl PartialEq for SockAddr {
341
349
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 ( )
347
351
}
348
352
}
349
353
350
354
impl Eq for SockAddr { }
351
355
352
356
impl Hash for SockAddr {
353
357
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) ;
358
359
}
359
360
}
360
361
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
-
365
362
#[ cfg( test) ]
366
363
mod tests {
367
364
use super :: * ;
0 commit comments