Skip to content
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

Add size != stride to frequently requested changes #216

Merged
merged 7 commits into from
Oct 18, 2023
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/frequently-requested-changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,29 @@ statement, and only later see the `if` and realize it's a conditional return.

Such a change would also have non-obvious evaluation order (evaluating the
condition before the return expression).

## Size != Stride

Rust assumes that the size of an object is equivalent to the stride of an object -
this means that the size of `[T; N]` is `N * std::mem::size_of::<T>`. Other languages
may have objects that take up less space in arrays due to the reuse of tail
padding, and allow interop with other languages which do this optimization.

One downside of this assumption is that types with alignment greater than their size can
waste large amounts of space due to padding. An overaligned struct such as the following:
```
#[repr(C, align(512))]
struct Overaligned(u8);
```
will store only 1 byte of data, but will have 511 bytes of tail padding for a total size of
512 bytes. This tail padding will not be reusable, and adding `Overaligned` as a struct field
may exacerbate this waste as additional trailing padding be included after any other members.

Rust makes several guarantees that make supporting size != stride difficult in the general case.
The combination of `std::array::from_ref` and array indexing is a stable guarantee that a pointer
(or reference) to a type is convertible to a pointer to a 1-array of that type, and vice versa.

Such a change could also pose problems for existing unsafe code, which may assume that pointers
can be manually offset by the size of the type to access the next array element. Unsafe
code may also assume that overwriting trailing padding is allowed, which would conflict with
the repurposing of such padding for data storage.
carbotaniuman marked this conversation as resolved.
Show resolved Hide resolved