File tree Expand file tree Collapse file tree 1 file changed +15
-0
lines changed Expand file tree Collapse file tree 1 file changed +15
-0
lines changed Original file line number Diff line number Diff line change 1111//! Define the `ByteValued` trait to mark that it is safe to instantiate the struct with random
1212//! data.
1313
14+ use std:: io:: { Read , Write } ;
1415use std:: mem:: { size_of, MaybeUninit } ;
1516use std:: result:: Result ;
1617use std:: slice:: { from_raw_parts, from_raw_parts_mut} ;
@@ -116,6 +117,20 @@ pub unsafe trait ByteValued: Copy + Send + Sync {
116117 fn as_bytes ( & mut self ) -> VolatileSlice {
117118 VolatileSlice :: from ( self . as_mut_slice ( ) )
118119 }
120+
121+ /// Writes this [`ByteValued`]'s byte representation to the given [`Write`] impl.
122+ fn write_all_to < W : Write > ( & self , mut writer : W ) -> Result < ( ) , std:: io:: Error > {
123+ writer. write_all ( self . as_slice ( ) )
124+ }
125+
126+ /// Constructs an instance of this [`ByteValued`] by reading from the given [`Read`] impl.
127+ 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 ( ) } ;
132+ reader. read_exact ( result. as_mut_slice ( ) ) . map ( |_| result)
133+ }
119134}
120135
121136macro_rules! byte_valued_array {
You can’t perform that action at this time.
0 commit comments