Skip to content

Commit 57aea01

Browse files
joshlfehuss
authored andcommitted
Guarantee repr(C) union field offset
Makes progress on rust-lang/unsafe-code-guidelines#595
1 parent 141b1af commit 57aea01

1 file changed

Lines changed: 7 additions & 1 deletion

File tree

src/type-layout.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ r[layout.repr.c.union.intro]
255255
A union declared with `#[repr(C)]` will have the same size and alignment as an equivalent C union declaration in the C language for the target platform.
256256

257257
r[layout.repr.c.union.size-align]
258-
The union will have a size of the maximum size of all of its fields rounded to its alignment, and an alignment of the maximum alignment of all of its fields. These maximums may come from different fields.
258+
The union will have a size of the maximum size of all of its fields rounded to its alignment, and an alignment of the maximum alignment of all of its fields. These maximums may come from different fields. Each field lives at byte offset 0 from the beginning of the union.
259259

260260
```rust
261261
#[repr(C)]
@@ -267,6 +267,9 @@ union Union {
267267
assert_eq!(std::mem::size_of::<Union>(), 4); // From f2
268268
assert_eq!(std::mem::align_of::<Union>(), 2); // From f1
269269

270+
assert_eq!(std::mem::offset_of!(Union, f1), 0);
271+
assert_eq!(std::mem::offset_of!(Union, f2), 0);
272+
270273
#[repr(C)]
271274
union SizeRoundedUp {
272275
a: u32,
@@ -277,6 +280,9 @@ assert_eq!(std::mem::size_of::<SizeRoundedUp>(), 8); // Size of 6 from b,
277280
// rounded up to 8 from
278281
// alignment of a.
279282
assert_eq!(std::mem::align_of::<SizeRoundedUp>(), 4); // From a
283+
284+
assert_eq!(std::mem::offset_of!(SizeRoundedUp, a), 0);
285+
assert_eq!(std::mem::offset_of!(SizeRoundedUp, b), 0);
280286
```
281287

282288
r[layout.repr.c.enum]

0 commit comments

Comments
 (0)