Skip to content

Commit

Permalink
Fix alignment bug in test_impls (google#944)
Browse files Browse the repository at this point in the history
In the test for `TryFromBytes::try_from_mut`, in order to get a mutable
slice, we first copy into a new `Vec`. Previously, we failed to
guarantee that this `Vec` is aligned, and so the test sometimes
spuriously failed.
  • Loading branch information
joshlf authored Feb 23, 2024
1 parent d982b5b commit ea3e73f
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8371,8 +8371,24 @@ mod tests {
}

if let Some(bytes) = bytes {
let mut bytes = bytes.to_vec();
let res = ww.test_try_from_mut(bytes.as_mut_slice());
// We need to get a mutable byte slice, and so we clone
// into a `Vec`. However, we also need these bytes to
// satisfy `$ty`'s alignment requirement, which isn't
// guaranteed for `Vec<u8>`. In order to get around
// this, we create a `Vec` which is twice as long as we
// need. There is guaranteed to be an aligned byte range
// of size `size_of_val(val)` within that range.
let size = mem::size_of_val(val);
let align = mem::align_of_val(val);

let mut vec = bytes.to_vec();
vec.extend(bytes);
let slc = vec.as_slice();
let offset = slc.as_ptr().align_offset(align);
let bytes_mut = &mut vec.as_mut_slice()[offset..offset+size];
bytes_mut.copy_from_slice(bytes);

let res = ww.test_try_from_mut(bytes_mut);
if let Some(res) = res {
assert!(res.is_some(), "{}::try_from_mut({:?}): got `None`, expected `Some`", stringify!($ty), val);
}
Expand Down

0 comments on commit ea3e73f

Please sign in to comment.