Skip to content

Commit ff25fa2

Browse files
JohnTitorGankra
authored andcommitted
Add an example that shows the null-pointer opt does not happen
1 parent ca4aa39 commit ff25fa2

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

src/other-reprs.md

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ or C++. Any type you expect to pass through an FFI boundary should have
1212
necessary to soundly do more elaborate tricks with data layout such as
1313
reinterpreting values as a different type.
1414

15-
We strongly recommend using [rust-bindgen][] and/or [cbindgen][] to manage your FFI
15+
We strongly recommend using [rust-bindgen] and/or [cbindgen] to manage your FFI
1616
boundaries for you. The Rust team works closely with those projects to ensure
1717
that they work robustly and are compatible with current and future guarantees
1818
about type layouts and `repr`s.
@@ -89,11 +89,27 @@ in that there is a defined layout of the type. This makes it possible to
8989
pass the enum to C code, or access the type's raw representation and directly
9090
manipulate its tag and fields. See [the RFC][really-tagged] for details.
9191

92-
Adding an explicit `repr` to an enum suppresses the null-pointer
93-
optimization.
94-
9592
These `repr`s have no effect on a struct.
9693

94+
Adding an explicit `repr(u*)`, `repr(i*)`, or `repr(C)` to an enum suppresses the null-pointer optimization, like:
95+
96+
```rust
97+
# use std::mem::size_of;
98+
enum MyOption<T> {
99+
Some(T),
100+
None,
101+
}
102+
103+
#[repr(u8)]
104+
enum MyReprOption<T> {
105+
Some(T),
106+
None,
107+
}
108+
109+
assert_eq!(8, size_of::<MyOption<&u16>>());
110+
assert_eq!(16, size_of::<MyReprOption<&u16>>());
111+
```
112+
97113
## repr(packed)
98114

99115
`repr(packed)` forces Rust to strip any padding, and only align the type to a

0 commit comments

Comments
 (0)