Skip to content

Commit 41b9edd

Browse files
committed
Add ByteValued::{write_all_to,read_exact_from}
Suggested-by: Paolo Bonzini <[email protected]> Signed-off-by: Patrick Roy <[email protected]>
1 parent c33d5a8 commit 41b9edd

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/bytes.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
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};
1415
use std::mem::{size_of, MaybeUninit};
1516
use std::result::Result;
1617
use 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

121136
macro_rules! byte_valued_array {

0 commit comments

Comments
 (0)