Skip to content

Commit

Permalink
Fix zerocopy validation logic and add detailed explanations
Browse files Browse the repository at this point in the history
  • Loading branch information
zebreus committed Nov 12, 2024
1 parent 02e4ab5 commit 1cda797
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1102,8 +1102,16 @@ mod impl_zerocopy {
let my_candidate =
unsafe { candidate.assume_validity::<zerocopy::pointer::invariant::Valid>() };
{
(my_candidate.read_unaligned::<zerocopy::pointer::BecauseImmutable>() ^ T::ALL_BITS)
== T::EMPTY
// ALL_BITS has all valid bits set to 1. If we invert it we get a mask with all invalid bits.
let invalid_bits = !T::ALL_BITS;
// TODO: Currently this assumes that the candidate is aligned. We actually need to check this beforehand
// Dereference the pointer to the candidate
let candidate =
my_candidate.read_unaligned::<zerocopy::pointer::BecauseImmutable>();
// By applying the invalid_bits mask to the candidate, only invalid bits will remain 1. So if there are any 1s left in this value we know that the candidate is invalid.
let invalid_bits_in_candidate = candidate & invalid_bits;
// Verify that there are no 1s left.
return invalid_bits_in_candidate == T::EMPTY;
}
}
}
Expand Down

0 comments on commit 1cda797

Please sign in to comment.