Skip to content

Guarantee the layout of structs with a single non-zero-sized field #164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Aug 27, 2019
35 changes: 28 additions & 7 deletions reference/src/layout/structs-and-tuples.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,25 @@ struct Zst2(Zst1, Zst0);
# }
```

#### Default layout of structs where only a single field is not a 1-ZST

The default layout of structs where only a single field is not a 1-ZST is the
same as the layout of that non-1-ZST field.

For example, the layout of:

```rust
struct SomeStruct(i32, ());
```

is the same as the layout of `i32`, but the layout of:

```rust
#[repr(align(16))] struct Zst;
struct SomeOtherStruct(i32, Zst);
```
is **unspecified**, since `Zst` is not a [1-ZST].

#### Unresolved questions

During the course of the discussion in [#11] and [#12], various
Expand All @@ -150,14 +169,14 @@ issue has been opened for further discussion on the repository. This
section documents the questions and gives a few light details, but the
reader is referred to the issues for further discussion.

**Single-field structs ([#34]).** If you have a struct with single field
(`struct Foo { x: T }`), should we guarantee that the memory layout of
`Foo` is identical to the memory layout of `T` (note that ABI details
around function calls may still draw a distinction, which is why
`#[repr(transparent)]` is needed). What about zero-sized types like
`PhantomData`?
**Zero-sized structs ([#37]).** If you have a struct which --
transitively -- contains no data of non-zero size, then the size of
that struct will be zero as well. These zero-sized structs appear
frequently as exceptions in other layout considerations (e.g.,
single-field structs). An example of such a struct is
`std::marker::PhantomData`.

[#34]: https://github.com/rust-rfcs/unsafe-code-guidelines/issues/34
[#37]: https://github.com/rust-rfcs/unsafe-code-guidelines/issues/37

**Homogeneous structs ([#36]).** If you have homogeneous structs, where all
the `N` fields are of a single type `T`, can we guarantee a mapping to
Expand Down Expand Up @@ -400,3 +419,5 @@ proposal (and -- further -- it does not match our existing behavior):
thread](https://github.com/rust-rfcs/unsafe-code-guidelines/pull/31#discussion_r224955817)).
- Many people would prefer the name ordering to be chosen for
"readability" and not optimal layout.

[1-ZST]: ../glossary.md#zero-sized-type--zst