@@ -118,17 +118,22 @@ pub unsafe trait ByteValued: Copy + Send + Sync {
118118 VolatileSlice :: from ( self . as_mut_slice ( ) )
119119 }
120120
121+ /// Constructs a `Self` ewhose binary representation is set to all zeroes.
122+ fn zeroed ( ) -> Self {
123+ // SAFETY: ByteValued objects must be assignable from arbitrary byte
124+ // sequences and are mandated to be packed.
125+ // Hence, zeroed memory is a fine initialization.
126+ unsafe { MaybeUninit :: < Self > :: zeroed ( ) . assume_init ( ) }
127+ }
128+
121129 /// Writes this [`ByteValued`]'s byte representation to the given [`Write`] impl.
122130 fn write_all_to < W : Write > ( & self , mut writer : W ) -> Result < ( ) , std:: io:: Error > {
123131 writer. write_all ( self . as_slice ( ) )
124132 }
125133
126134 /// Constructs an instance of this [`ByteValued`] by reading from the given [`Read`] impl.
127135 fn read_exact_from < R : Read > ( mut reader : R ) -> Result < Self , std:: io:: Error > {
128- // SAFETY: ByteValued objects must be assignable from arbitrary byte
129- // sequences and are mandated to be packed.
130- // Hence, zeroed memory is a fine initialization.
131- let mut result: Self = unsafe { MaybeUninit :: < Self > :: zeroed ( ) . assume_init ( ) } ;
136+ let mut result = Self :: zeroed ( ) ;
132137 reader. read_exact ( result. as_mut_slice ( ) ) . map ( |_| result)
133138 }
134139}
@@ -305,10 +310,7 @@ pub trait Bytes<A> {
305310 ///
306311 /// Returns an error if there's not enough data inside the container.
307312 fn read_obj < T : ByteValued > ( & self , addr : A ) -> Result < T , Self :: E > {
308- // SAFETY: ByteValued objects must be assignable from a arbitrary byte
309- // sequence and are mandated to be packed.
310- // Hence, zeroed memory is a fine initialization.
311- let mut result: T = unsafe { MaybeUninit :: < T > :: zeroed ( ) . assume_init ( ) } ;
313+ let mut result = T :: zeroed ( ) ;
312314 self . read_slice ( result. as_mut_slice ( ) , addr) . map ( |_| result)
313315 }
314316
@@ -659,4 +661,11 @@ pub(crate) mod tests {
659661 let result = s. write_all_to ( b. as_mut_slice ( ) ) ;
660662 assert_eq ! ( result. unwrap_err( ) . kind( ) , ErrorKind :: WriteZero ) ;
661663 }
664+
665+ #[ test]
666+ fn test_byte_valued_zeroed ( ) {
667+ let s = S :: zeroed ( ) ;
668+
669+ assert ! ( s. as_slice( ) . iter( ) . all( |& b| b == 0x0 ) ) ;
670+ }
662671}
0 commit comments