Skip to content

Commit 5f42a1f

Browse files
committed
Document ABI changes from #[repr(u*)] enum
1 parent 616b984 commit 5f42a1f

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/other-reprs.md

+18-2
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ enum representation in C is implementation defined, so this is really a "best
3737
guess". In particular, this may be incorrect when the C code of interest is
3838
compiled with certain flags.
3939

40+
* "C-like" enums with `repr(C)` or `repr(u*)` still may not be set to an
41+
integer value without a corresponding variant, even though this is
42+
permitted behavior in C or C++. It is undefined behavior to (unsafely)
43+
construct an instance of an enum that does not match one of its
44+
variants. (This allows exhaustive matches to continue to be written and
45+
compiled as normal.)
46+
4047

4148

4249
# repr(u8), repr(u16), repr(u32), repr(u64)
@@ -47,8 +54,17 @@ ask Rust to allow this by setting the overflowing element to explicitly be 0.
4754
However Rust will not allow you to create an enum where two variants have the
4855
same discriminant.
4956

50-
On non-C-like enums, this will inhibit certain optimizations like the null-
51-
pointer optimization.
57+
If a C-like enum is missing a `repr(u*)` or `repr(C)`, it is treated
58+
like a one-member struct for ABI compatibility purposes. This means
59+
that, for instance, some ABIs will unconditionally pass it on the stack
60+
instead of in a register. Adding a `repr` causes it to be treated
61+
exactly like the specified integer size for ABI purposes.
62+
63+
However, a non-C-like enum will always be treated like a struct (even if
64+
the only data is `()` or `PhantomData`). Adding `repr` simply forces the
65+
discriminant to be represented in memory by the specified integer size.
66+
This does have the effect of inhibiting certain optimizations like the
67+
null-pointer optimization.
5268

5369
These reprs have no effect on a struct.
5470

0 commit comments

Comments
 (0)