@@ -393,20 +393,26 @@ impl Fill for [u8] {
393393 }
394394}
395395
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`.
398400macro_rules! unsafe_impl_fill {
399401 ( ) => { } ;
400402 ( $t: ty) => {
401403 impl Fill for [ $t] {
402404 fn fill<R : Rng + ?Sized >( & mut self , rng: & mut R ) {
403405 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+ ) ;
410416 for x in self {
411417 * x = x. to_le( ) ;
412418 }
@@ -417,12 +423,16 @@ macro_rules! unsafe_impl_fill {
417423 impl Fill for [ Wrapping <$t>] {
418424 fn fill<R : Rng + ?Sized >( & mut self , rng: & mut R ) {
419425 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+ ) ;
426436 for x in self {
427437 * x = Wrapping ( x. 0 . to_le( ) ) ;
428438 }
@@ -438,7 +448,9 @@ macro_rules! unsafe_impl_fill {
438448 }
439449}
440450
451+ // SAFETY: All representations of `[u8; size_of::<u*>()]` are representations of `u*`.
441452unsafe_impl_fill ! ( u16 , u32 , u64 , u128 , ) ;
453+ // SAFETY: All representations of `[u8; size_of::<i*>()]` are representations of `i*`.
442454unsafe_impl_fill ! ( i8 , i16 , i32 , i64 , i128 , ) ;
443455
444456impl < T , const N : usize > Fill for [ T ; N ]
0 commit comments