Skip to content

Commit b8b8980

Browse files
committed
Avoid unsafe unaligned loads in test.
1 parent 10f6a5c commit b8b8980

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/test/run-pass/mir_adt_construction.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
use std::fmt;
12+
1113
#[repr(C)]
1214
enum CEnum {
1315
Hello = 30,
@@ -24,7 +26,6 @@ fn test1(c: CEnum) -> i32 {
2426
}
2527

2628
#[repr(packed)]
27-
#[derive(PartialEq, Debug)]
2829
struct Pakd {
2930
a: u64,
3031
b: u32,
@@ -33,6 +34,36 @@ struct Pakd {
3334
e: ()
3435
}
3536

37+
// It is unsafe to use #[derive(Debug)] on a packed struct because the code generated by the derive
38+
// macro takes references to the fields instead of accessing them directly.
39+
impl fmt::Debug for Pakd {
40+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41+
// It's important that we load the fields into locals by-value here. This will do safe
42+
// unaligned loads into the locals, then pass references to the properly-aligned locals to
43+
// the formatting code.
44+
let Pakd { a, b, c, d, e } = *self;
45+
f.debug_struct("Pakd")
46+
.field("a", &a)
47+
.field("b", &b)
48+
.field("c", &c)
49+
.field("d", &d)
50+
.field("e", &e)
51+
.finish()
52+
}
53+
}
54+
55+
// It is unsafe to use #[derive(PartialEq)] on a packed struct because the code generated by the
56+
// derive macro takes references to the fields instead of accessing them directly.
57+
impl PartialEq for Pakd {
58+
fn eq(&self, other: &Pakd) -> bool {
59+
self.a == other.a &&
60+
self.b == other.b &&
61+
self.c == other.c &&
62+
self.d == other.d &&
63+
self.e == other.e
64+
}
65+
}
66+
3667
impl Drop for Pakd {
3768
fn drop(&mut self) {}
3869
}

0 commit comments

Comments
 (0)