Add `Align` type
- Dominant language
- Rust
- Stars
- 2.6k
- Forks
- 179
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 29
Description
*Any design for this issue will interact with other issues tracked by #885; make sure to read that issue when tackling this one.*
*Needed for: #497*
Add a type like the following, which represents a `T` aligned to the alignment of `A`:
```rust
/// A `T` which is at least as aligned as `A`.
///
/// `Align`'s alignment is the maximum of the alignments of `T` and `A`,
/// and its size is `T`'s size rounded up to the next multiple of `A`'s
/// alignment (note that 0 is a valid multiple; if `T` is zero-sized, then
/// `Align` will be zero-sized as well).
///
/// The first `mem::size_of::()` bytes of `Align` have the same layout
/// as `T`, and any remaining bytes are initialized to unspecified values.
#[derive(Unaligned)]
#[repr(C)]
pub struct Align {
// The layout of `Align` is guaranteed to have `t` at byte offset 0 possibly
// followed by some padding bytes.
//
// `Align` is guaranteed to have the maximum alignment of `T` and `A`.
// This means that `_a`'s alignment requirement (equal to `A`'s) is
// satisfied by `_a` living at byte offset 0. Since `_a` is 0 bytes in
// length, `t` is properly aligned even if there is no padding between `_a`
// and `t` (namely, if `t` lives at byte offset 0). `repr(C)` guarantees
// that each field is located at the minimum address that satisfies the
// field's alignment, which means that there is guaranteed to be no padding
// between `_a` and `t`. Finally, if `size_of::() > 0` and
// `size_of::()` is not a multiple of `align_of::()`, there will be
// trailing padding to ensure that `Align`'s size is a multiple of its
// alignment.
_a: [A; 0],
t: T,
// INVARIANT: Any padding bytes are initialized. This is required in order
// to make it sound for `Align` to implement `AsBytes`.
}
```
This type was originally proposed (though never merged) [here](https://fuchsia-review.googlesource.com/c/fuchsia/+/720406), and a more up-to-date prototype is in https://github.com/google/zerocopy/commit/e8148f628823dc70175d8a8ae6d7062a97257817.
See also [this proposal for eliding alignment checks using `Align`](https://github.com/google/zerocopy/issues/280).
Contributor guide
Assessment
This issue has not been assessed yet.