Skip to content

Commit

Permalink
Add FromBytes::read_from_io and IntoBytes::write_to_io
Browse files Browse the repository at this point in the history
Makes progress on #158.
  • Loading branch information
jswrenn committed Nov 4, 2024
1 parent 1fb6365 commit 29fb787
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,12 +359,16 @@ use core::{
slice,
};

#[cfg(feature = "std")]
use std::io;

use crate::pointer::{invariant, BecauseExclusive};

#[cfg(any(feature = "alloc", test))]
extern crate alloc;
#[cfg(any(feature = "alloc", test))]
use alloc::{boxed::Box, vec::Vec};
use pointer::invariant::Initialized;

#[cfg(any(feature = "alloc", test, kani))]
use core::alloc::Layout;
Expand Down Expand Up @@ -4525,6 +4529,24 @@ pub unsafe trait FromBytes: FromZeros {
}
}

/// TODO
#[cfg(feature = "std")]
#[inline(always)]
fn read_from_io(source: &mut impl io::Read) -> io::Result<Self>
where
Self: Sized,
{
let mut buffer = MaybeUninit::<Self>::zeroed();
let ptr = Ptr::from_mut(&mut buffer);
// SAFETY: `buffer` consists entirely of initialized, zeroed bytes.
let ptr = unsafe { ptr.assume_validity::<Initialized>() };
let ptr = ptr.as_bytes::<BecauseExclusive>();
source.read_exact(ptr.as_mut())?;
// SAFETY: `buffer` consists entirely of initialized bytes, and `Self`
// is `FromBytes`.
Ok(unsafe { buffer.assume_init() })
}

#[deprecated(since = "0.8.0", note = "renamed to `FromBytes::ref_from_bytes`")]
#[doc(hidden)]
#[must_use = "has no side effects"]
Expand Down Expand Up @@ -5188,6 +5210,16 @@ pub unsafe trait IntoBytes {
Ok(())
}

/// TODO
#[cfg(feature = "std")]
#[inline(always)]
fn write_to_io(&self, dst: &mut impl io::Write) -> io::Result<()>
where
Self: Immutable,
{
dst.write_all(self.as_bytes())
}

#[deprecated(since = "0.8.0", note = "`IntoBytes::as_bytes_mut` was renamed to `as_mut_bytes`")]
#[doc(hidden)]
#[inline]
Expand Down

0 comments on commit 29fb787

Please sign in to comment.