Skip to content

Commit 1cda797

Browse files
committed
Fix zerocopy validation logic and add detailed explanations
1 parent 02e4ab5 commit 1cda797

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/lib.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -1102,8 +1102,16 @@ mod impl_zerocopy {
11021102
let my_candidate =
11031103
unsafe { candidate.assume_validity::<zerocopy::pointer::invariant::Valid>() };
11041104
{
1105-
(my_candidate.read_unaligned::<zerocopy::pointer::BecauseImmutable>() ^ T::ALL_BITS)
1106-
== T::EMPTY
1105+
// ALL_BITS has all valid bits set to 1. If we invert it we get a mask with all invalid bits.
1106+
let invalid_bits = !T::ALL_BITS;
1107+
// TODO: Currently this assumes that the candidate is aligned. We actually need to check this beforehand
1108+
// Dereference the pointer to the candidate
1109+
let candidate =
1110+
my_candidate.read_unaligned::<zerocopy::pointer::BecauseImmutable>();
1111+
// 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.
1112+
let invalid_bits_in_candidate = candidate & invalid_bits;
1113+
// Verify that there are no 1s left.
1114+
return invalid_bits_in_candidate == T::EMPTY;
11071115
}
11081116
}
11091117
}

0 commit comments

Comments
 (0)