Skip to content

Commit 57d66be

Browse files
committed
Fix aligment downcast check in TryAsAligned
We can't use core::mem::align_of on the Alignment types, they are always aligned 1. Instead use ::ALIGNMENT. Also adds a unit test of this, which breaks before and now works.
1 parent 7ab5dd3 commit 57d66be

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

gvariant/src/aligned_bytes.rs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -337,9 +337,7 @@ impl<FromA: Alignment, ToA: Alignment> TryAsAligned<ToA> for AlignedSlice<FromA>
337337
fn try_as_aligned(&self) -> Result<&AlignedSlice<ToA>, Misaligned> {
338338
// If narrowing the alignment we know it's fine (at compile time). If
339339
// widening the alignment we must fall back to runtime check
340-
if core::mem::align_of::<FromA>() >= core::mem::align_of::<ToA>()
341-
|| is_aligned_to::<ToA>(self)
342-
{
340+
if FromA::ALIGNMENT >= ToA::ALIGNMENT || is_aligned_to::<ToA>(self) {
343341
Ok(unsafe { &*(self as *const Self as *const AlignedSlice<ToA>) })
344342
} else {
345343
Err(Misaligned {})
@@ -350,9 +348,7 @@ impl<FromA: Alignment, ToA: Alignment> TryAsAlignedMut<ToA> for AlignedSlice<Fro
350348
fn try_as_aligned_mut(&mut self) -> Result<&mut AlignedSlice<ToA>, Misaligned> {
351349
// If narrowing the alignment we know it's fine (at compile time). If
352350
// widening the alignment we must fall back to runtime check
353-
if core::mem::align_of::<FromA>() >= core::mem::align_of::<ToA>()
354-
|| is_aligned_to::<ToA>(self)
355-
{
351+
if FromA::ALIGNMENT >= ToA::ALIGNMENT || is_aligned_to::<ToA>(self) {
356352
Ok(unsafe { &mut *(self as *mut Self as *mut AlignedSlice<ToA>) })
357353
} else {
358354
Err(Misaligned {})
@@ -605,3 +601,22 @@ fn align_bytes<A: Alignment>(value: &[u8]) -> &AlignedSlice<A> {
605601
pub fn empty_aligned<A: Alignment>() -> &'static AlignedSlice<A> {
606602
&align_bytes(b" ")[..0]
607603
}
604+
605+
#[cfg(test)]
606+
mod test {
607+
use super::*;
608+
609+
#[test]
610+
fn test_try_align() {
611+
#[repr(align(8))]
612+
struct AlignedBytes([u8; 16]);
613+
614+
let data = AlignedBytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
615+
let bytes = &data.0[..];
616+
617+
let aligned = TryAsAligned::<A8>::try_as_aligned(&bytes);
618+
assert!(aligned.is_ok());
619+
let misaligned = TryAsAligned::<A8>::try_as_aligned(&bytes[1..]);
620+
assert!(misaligned.is_err());
621+
}
622+
}

0 commit comments

Comments
 (0)