Skip to content

Commit

Permalink
[WIP] TryFromBytes
Browse files Browse the repository at this point in the history
TODO:
- Should we require `FromBytes: FromZeroes + TryFromBytes` or
  `FromZeroes: TryFromBytes`? We obviously only need one of these, but
  which one?

Makes progress on #5
  • Loading branch information
joshlf committed Aug 22, 2023
1 parent 514cc58 commit 1c4e141
Show file tree
Hide file tree
Showing 2 changed files with 524 additions and 75 deletions.
31 changes: 31 additions & 0 deletions src/derive_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,34 @@ macro_rules! union_has_padding {
false $(|| core::mem::size_of::<$t>() != core::mem::size_of::<$ts>())*
};
}

#[doc(hidden)]
pub use project::project as __project;

#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
#[macro_export]
macro_rules! impl_try_from_bytes {
($ty:ty { $($f:tt: $f_ty:ty),* } $(=> $validation_method:ident)?) => {
#[allow(unused_qualifications)]
unsafe impl zerocopy::TryFromBytes for $ty {
fn is_bit_valid(bytes: &zerocopy::MaybeValid<Self>) -> bool {
true $(&& {
let f: &zerocopy::MaybeValid<$f_ty>
= zerocopy::derive_util::__project!(&bytes.$f);
zerocopy::TryFromBytes::is_bit_valid(f)
})*
$(&& {
let bytes_ptr: *const zerocopy::MaybeValid<Self> = bytes;
let slf = unsafe { &*bytes_ptr.cast::<Self>() };
// TODO: What about interior mutability? One approach would
// be to have the validation method operate on a
// `#[repr(transparent)]` `Freeze` container that implements
// `Projectable`. If we eventually get a `Freeze` or
// `NoCell` trait, that container could implement `Deref`
// for types which don't contain any cells.
slf.$validation_method()
})?
}
}
}
}

0 comments on commit 1c4e141

Please sign in to comment.