@@ -118,17 +118,22 @@ pub unsafe trait ByteValued: Copy + Send + Sync {
118
118
VolatileSlice :: from ( self . as_mut_slice ( ) )
119
119
}
120
120
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
+
121
129
/// Writes this [`ByteValued`]'s byte representation to the given [`Write`] impl.
122
130
fn write_all_to < W : Write > ( & self , mut writer : W ) -> Result < ( ) , std:: io:: Error > {
123
131
writer. write_all ( self . as_slice ( ) )
124
132
}
125
133
126
134
/// Constructs an instance of this [`ByteValued`] by reading from the given [`Read`] impl.
127
135
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 ( ) ;
132
137
reader. read_exact ( result. as_mut_slice ( ) ) . map ( |_| result)
133
138
}
134
139
}
@@ -305,10 +310,7 @@ pub trait Bytes<A> {
305
310
///
306
311
/// Returns an error if there's not enough data inside the container.
307
312
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 ( ) ;
312
314
self . read_slice ( result. as_mut_slice ( ) , addr) . map ( |_| result)
313
315
}
314
316
@@ -659,4 +661,11 @@ pub(crate) mod tests {
659
661
let result = s. write_all_to ( b. as_mut_slice ( ) ) ;
660
662
assert_eq ! ( result. unwrap_err( ) . kind( ) , ErrorKind :: WriteZero ) ;
661
663
}
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
+ }
662
671
}
0 commit comments