Skip to content

Commit 1c4e141

Browse files
committed
[WIP] TryFromBytes
TODO: - Should we require `FromBytes: FromZeroes + TryFromBytes` or `FromZeroes: TryFromBytes`? We obviously only need one of these, but which one? Makes progress on #5
1 parent 514cc58 commit 1c4e141

File tree

2 files changed

+524
-75
lines changed

2 files changed

+524
-75
lines changed

src/derive_util.rs

+31
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,34 @@ macro_rules! union_has_padding {
6262
false $(|| core::mem::size_of::<$t>() != core::mem::size_of::<$ts>())*
6363
};
6464
}
65+
66+
#[doc(hidden)]
67+
pub use project::project as __project;
68+
69+
#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
70+
#[macro_export]
71+
macro_rules! impl_try_from_bytes {
72+
($ty:ty { $($f:tt: $f_ty:ty),* } $(=> $validation_method:ident)?) => {
73+
#[allow(unused_qualifications)]
74+
unsafe impl zerocopy::TryFromBytes for $ty {
75+
fn is_bit_valid(bytes: &zerocopy::MaybeValid<Self>) -> bool {
76+
true $(&& {
77+
let f: &zerocopy::MaybeValid<$f_ty>
78+
= zerocopy::derive_util::__project!(&bytes.$f);
79+
zerocopy::TryFromBytes::is_bit_valid(f)
80+
})*
81+
$(&& {
82+
let bytes_ptr: *const zerocopy::MaybeValid<Self> = bytes;
83+
let slf = unsafe { &*bytes_ptr.cast::<Self>() };
84+
// TODO: What about interior mutability? One approach would
85+
// be to have the validation method operate on a
86+
// `#[repr(transparent)]` `Freeze` container that implements
87+
// `Projectable`. If we eventually get a `Freeze` or
88+
// `NoCell` trait, that container could implement `Deref`
89+
// for types which don't contain any cells.
90+
slf.$validation_method()
91+
})?
92+
}
93+
}
94+
}
95+
}

0 commit comments

Comments
 (0)