@@ -393,20 +393,26 @@ impl Fill for [u8] {
393
393
}
394
394
}
395
395
396
- // This macro is unsafe to call: target types must support transmute from
397
- // random bits (i.e. all bit representations are valid).
396
+ /// Implement `Fill` for given type `T`.
397
+ ///
398
+ /// # Safety
399
+ /// All representations of `[u8; size_of::<T>()]` are also representations of `T`.
398
400
macro_rules! unsafe_impl_fill {
399
401
( ) => { } ;
400
402
( $t: ty) => {
401
403
impl Fill for [ $t] {
402
404
fn fill<R : Rng + ?Sized >( & mut self , rng: & mut R ) {
403
405
if self . len( ) > 0 {
404
- rng. fill_bytes( unsafe {
405
- slice:: from_raw_parts_mut( self . as_mut_ptr( )
406
- as * mut u8 ,
407
- mem:: size_of_val( self )
408
- )
409
- } ) ;
406
+ let size = mem:: size_of_val( self ) ;
407
+ rng. fill_bytes(
408
+ // SAFETY: `self` is not borrowed and all byte sequences are representations of `T`.
409
+ unsafe {
410
+ slice:: from_raw_parts_mut( self . as_mut_ptr( )
411
+ as * mut u8 ,
412
+ size
413
+ )
414
+ }
415
+ ) ;
410
416
for x in self {
411
417
* x = x. to_le( ) ;
412
418
}
@@ -417,12 +423,16 @@ macro_rules! unsafe_impl_fill {
417
423
impl Fill for [ Wrapping <$t>] {
418
424
fn fill<R : Rng + ?Sized >( & mut self , rng: & mut R ) {
419
425
if self . len( ) > 0 {
420
- rng. fill_bytes( unsafe {
421
- slice:: from_raw_parts_mut( self . as_mut_ptr( )
422
- as * mut u8 ,
423
- self . len( ) * mem:: size_of:: <$t>( )
424
- )
425
- } ) ;
426
+ let size = self . len( ) * mem:: size_of:: <$t>( ) ;
427
+ rng. fill_bytes(
428
+ // SAFETY: `self` is not borrowed and all byte sequences are representations of `T`.
429
+ unsafe {
430
+ slice:: from_raw_parts_mut( self . as_mut_ptr( )
431
+ as * mut u8 ,
432
+ size
433
+ )
434
+ }
435
+ ) ;
426
436
for x in self {
427
437
* x = Wrapping ( x. 0 . to_le( ) ) ;
428
438
}
@@ -438,7 +448,9 @@ macro_rules! unsafe_impl_fill {
438
448
}
439
449
}
440
450
451
+ // SAFETY: All representations of `[u8; size_of::<u*>()]` are representations of `u*`.
441
452
unsafe_impl_fill ! ( u16 , u32 , u64 , u128 , ) ;
453
+ // SAFETY: All representations of `[u8; size_of::<i*>()]` are representations of `i*`.
442
454
unsafe_impl_fill ! ( i8 , i16 , i32 , i64 , i128 , ) ;
443
455
444
456
impl < T , const N : usize > Fill for [ T ; N ]
0 commit comments