zerocopy/util/
macro_util.rs

1// Copyright 2022 The Fuchsia Authors
2//
3// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6// This file may not be copied, modified, or distributed except according to
7// those terms.
8
9//! Utilities used by macros and by `zerocopy-derive`.
10//!
11//! These are defined here `zerocopy` rather than in code generated by macros or
12//! by `zerocopy-derive` so that they can be compiled once rather than
13//! recompiled for every invocation (e.g., if they were defined in generated
14//! code, then deriving `IntoBytes` and `FromBytes` on three different types
15//! would result in the code in question being emitted and compiled six
16//! different times).
17
18#![allow(missing_debug_implementations)]
19
20use core::mem::{self, ManuallyDrop};
21
22// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
23// `cfg` when `size_of_val_raw` is stabilized.
24#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
25use core::ptr::{self, NonNull};
26
27use crate::{
28    pointer::{
29        invariant::{self, AtLeast, Invariants},
30        AliasingSafe, AliasingSafeReason, BecauseExclusive, BecauseImmutable,
31    },
32    Immutable, IntoBytes, Ptr, TryFromBytes, Unalign, ValidityError,
33};
34
35#[cfg_attr(
36    zerocopy_diagnostic_on_unimplemented,
37    diagnostic::on_unimplemented(
38        message = "`{T}` has inter-field padding",
39        label = "types with padding cannot implement `IntoBytes`",
40        note = "consider using `zerocopy::Unalign` to lower the alignment of individual fields",
41        note = "consider adding explicit fields where padding would be",
42        note = "consider using `#[repr(packed)]` to remove inter-field padding"
43    )
44)]
45pub trait PaddingFree<T: ?Sized, const HAS_PADDING: bool> {}
46impl<T: ?Sized> PaddingFree<T, false> for () {}
47
48/// A type whose size is equal to `align_of::<T>()`.
49#[repr(C)]
50pub struct AlignOf<T> {
51    // This field ensures that:
52    // - The size is always at least 1 (the minimum possible alignment).
53    // - If the alignment is greater than 1, Rust has to round up to the next
54    //   multiple of it in order to make sure that `Align`'s size is a multiple
55    //   of that alignment. Without this field, its size could be 0, which is a
56    //   valid multiple of any alignment.
57    _u: u8,
58    _a: [T; 0],
59}
60
61impl<T> AlignOf<T> {
62    #[inline(never)] // Make `missing_inline_in_public_items` happy.
63    #[cfg_attr(coverage_nightly, coverage(off))]
64    pub fn into_t(self) -> T {
65        unreachable!()
66    }
67}
68
69/// A type whose size is equal to `max(align_of::<T>(), align_of::<U>())`.
70#[repr(C)]
71pub union MaxAlignsOf<T, U> {
72    _t: ManuallyDrop<AlignOf<T>>,
73    _u: ManuallyDrop<AlignOf<U>>,
74}
75
76impl<T, U> MaxAlignsOf<T, U> {
77    #[inline(never)] // Make `missing_inline_in_public_items` happy.
78    #[cfg_attr(coverage_nightly, coverage(off))]
79    pub fn new(_t: T, _u: U) -> MaxAlignsOf<T, U> {
80        unreachable!()
81    }
82}
83
84const _64K: usize = 1 << 16;
85
86// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
87// `cfg` when `size_of_val_raw` is stabilized.
88#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
89#[repr(C, align(65536))]
90struct Aligned64kAllocation([u8; _64K]);
91
92/// A pointer to an aligned allocation of size 2^16.
93///
94/// # Safety
95///
96/// `ALIGNED_64K_ALLOCATION` is guaranteed to point to the entirety of an
97/// allocation with size and alignment 2^16, and to have valid provenance.
98// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
99// `cfg` when `size_of_val_raw` is stabilized.
100#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
101pub const ALIGNED_64K_ALLOCATION: NonNull<[u8]> = {
102    const REF: &Aligned64kAllocation = &Aligned64kAllocation([0; _64K]);
103    let ptr: *const Aligned64kAllocation = REF;
104    let ptr: *const [u8] = ptr::slice_from_raw_parts(ptr.cast(), _64K);
105    // SAFETY:
106    // - `ptr` is derived from a Rust reference, which is guaranteed to be
107    //   non-null.
108    // - `ptr` is derived from an `&Aligned64kAllocation`, which has size and
109    //   alignment `_64K` as promised. Its length is initialized to `_64K`,
110    //   which means that it refers to the entire allocation.
111    // - `ptr` is derived from a Rust reference, which is guaranteed to have
112    //   valid provenance.
113    //
114    // TODO(#429): Once `NonNull::new_unchecked` docs document that it preserves
115    // provenance, cite those docs.
116    // TODO: Replace this `as` with `ptr.cast_mut()` once our MSRV >= 1.65
117    #[allow(clippy::as_conversions)]
118    unsafe {
119        NonNull::new_unchecked(ptr as *mut _)
120    }
121};
122
123/// Computes the offset of the base of the field `$trailing_field_name` within
124/// the type `$ty`.
125///
126/// `trailing_field_offset!` produces code which is valid in a `const` context.
127// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
128// `cfg` when `size_of_val_raw` is stabilized.
129#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
130#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
131#[macro_export]
132macro_rules! trailing_field_offset {
133    ($ty:ty, $trailing_field_name:tt) => {{
134        let min_size = {
135            let zero_elems: *const [()] =
136                $crate::util::macro_util::core_reexport::ptr::slice_from_raw_parts(
137                    // Work around https://github.com/rust-lang/rust-clippy/issues/12280
138                    #[allow(clippy::incompatible_msrv)]
139                    $crate::util::macro_util::core_reexport::ptr::NonNull::<()>::dangling()
140                        .as_ptr()
141                        .cast_const(),
142                    0,
143                );
144            // SAFETY:
145            // - If `$ty` is `Sized`, `size_of_val_raw` is always safe to call.
146            // - Otherwise:
147            //   - If `$ty` is not a slice DST, this pointer conversion will
148            //     fail due to "mismatched vtable kinds", and compilation will
149            //     fail.
150            //   - If `$ty` is a slice DST, we have constructed `zero_elems` to
151            //     have zero trailing slice elements. Per the `size_of_val_raw`
152            //     docs, "For the special case where the dynamic tail length is
153            //     0, this function is safe to call." [1]
154            //
155            // [1] https://doc.rust-lang.org/nightly/std/mem/fn.size_of_val_raw.html
156            unsafe {
157                #[allow(clippy::as_conversions)]
158                $crate::util::macro_util::core_reexport::mem::size_of_val_raw(
159                    zero_elems as *const $ty,
160                )
161            }
162        };
163
164        assert!(min_size <= _64K);
165
166        #[allow(clippy::as_conversions)]
167        let ptr = ALIGNED_64K_ALLOCATION.as_ptr() as *const $ty;
168
169        // SAFETY:
170        // - Thanks to the preceding `assert!`, we know that the value with zero
171        //   elements fits in `_64K` bytes, and thus in the allocation addressed
172        //   by `ALIGNED_64K_ALLOCATION`. The offset of the trailing field is
173        //   guaranteed to be no larger than this size, so this field projection
174        //   is guaranteed to remain in-bounds of its allocation.
175        // - Because the minimum size is no larger than `_64K` bytes, and
176        //   because an object's size must always be a multiple of its alignment
177        //   [1], we know that `$ty`'s alignment is no larger than `_64K`. The
178        //   allocation addressed by `ALIGNED_64K_ALLOCATION` is guaranteed to
179        //   be aligned to `_64K`, so `ptr` is guaranteed to satisfy `$ty`'s
180        //   alignment.
181        // - As required by `addr_of!`, we do not write through `field`.
182        //
183        //   Note that, as of [2], this requirement is technically unnecessary
184        //   for Rust versions >= 1.75.0, but no harm in guaranteeing it anyway
185        //   until we bump our MSRV.
186        //
187        // [1] Per https://doc.rust-lang.org/reference/type-layout.html:
188        //
189        //   The size of a value is always a multiple of its alignment.
190        //
191        // [2] https://github.com/rust-lang/reference/pull/1387
192        let field = unsafe {
193            $crate::util::macro_util::core_reexport::ptr::addr_of!((*ptr).$trailing_field_name)
194        };
195        // SAFETY:
196        // - Both `ptr` and `field` are derived from the same allocated object.
197        // - By the preceding safety comment, `field` is in bounds of that
198        //   allocated object.
199        // - The distance, in bytes, between `ptr` and `field` is required to be
200        //   a multiple of the size of `u8`, which is trivially true because
201        //   `u8`'s size is 1.
202        // - The distance, in bytes, cannot overflow `isize`. This is guaranteed
203        //   because no allocated object can have a size larger than can fit in
204        //   `isize`. [1]
205        // - The distance being in-bounds cannot rely on wrapping around the
206        //   address space. This is guaranteed because the same is guaranteed of
207        //   allocated objects. [1]
208        //
209        // [1] TODO(#429), TODO(https://github.com/rust-lang/rust/pull/116675):
210        //     Once these are guaranteed in the Reference, cite it.
211        let offset = unsafe { field.cast::<u8>().offset_from(ptr.cast::<u8>()) };
212        // Guaranteed not to be lossy: `field` comes after `ptr`, so the offset
213        // from `ptr` to `field` is guaranteed to be positive.
214        assert!(offset >= 0);
215        Some(
216            #[allow(clippy::as_conversions)]
217            {
218                offset as usize
219            },
220        )
221    }};
222}
223
224/// Computes alignment of `$ty: ?Sized`.
225///
226/// `align_of!` produces code which is valid in a `const` context.
227// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
228// `cfg` when `size_of_val_raw` is stabilized.
229#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
230#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
231#[macro_export]
232macro_rules! align_of {
233    ($ty:ty) => {{
234        // SAFETY: `OffsetOfTrailingIsAlignment` is `repr(C)`, and its layout is
235        // guaranteed [1] to begin with the single-byte layout for `_byte`,
236        // followed by the padding needed to align `_trailing`, then the layout
237        // for `_trailing`, and finally any trailing padding bytes needed to
238        // correctly-align the entire struct.
239        //
240        // This macro computes the alignment of `$ty` by counting the number of
241        // bytes preceeding `_trailing`. For instance, if the alignment of `$ty`
242        // is `1`, then no padding is required align `_trailing` and it will be
243        // located immediately after `_byte` at offset 1. If the alignment of
244        // `$ty` is 2, then a single padding byte is required before
245        // `_trailing`, and `_trailing` will be located at offset 2.
246
247        // This correspondence between offset and alignment holds for all valid
248        // Rust alignments, and we confirm this exhaustively (or, at least up to
249        // the maximum alignment supported by `trailing_field_offset!`) in
250        // `test_align_of_dst`.
251        //
252        // [1]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprc
253
254        #[repr(C)]
255        struct OffsetOfTrailingIsAlignment {
256            _byte: u8,
257            _trailing: $ty,
258        }
259
260        trailing_field_offset!(OffsetOfTrailingIsAlignment, _trailing)
261    }};
262}
263
264mod size_to_tag {
265    pub trait SizeToTag<const SIZE: usize> {
266        type Tag;
267    }
268
269    impl SizeToTag<1> for () {
270        type Tag = u8;
271    }
272    impl SizeToTag<2> for () {
273        type Tag = u16;
274    }
275    impl SizeToTag<4> for () {
276        type Tag = u32;
277    }
278    impl SizeToTag<8> for () {
279        type Tag = u64;
280    }
281    impl SizeToTag<16> for () {
282        type Tag = u128;
283    }
284}
285
286/// An alias for the unsigned integer of the given size in bytes.
287#[doc(hidden)]
288pub type SizeToTag<const SIZE: usize> = <() as size_to_tag::SizeToTag<SIZE>>::Tag;
289
290// We put `Sized` in its own module so it can have the same name as the standard
291// library `Sized` without shadowing it in the parent module.
292#[cfg(zerocopy_diagnostic_on_unimplemented)]
293mod __size_of {
294    #[diagnostic::on_unimplemented(
295        message = "`{Self}` is unsized",
296        label = "`IntoBytes` needs all field types to be `Sized` in order to determine whether there is inter-field padding",
297        note = "consider using `#[repr(packed)]` to remove inter-field padding",
298        note = "`IntoBytes` does not require the fields of `#[repr(packed)]` types to be `Sized`"
299    )]
300    pub trait Sized: core::marker::Sized {}
301    impl<T: core::marker::Sized> Sized for T {}
302
303    #[inline(always)]
304    #[must_use]
305    #[allow(clippy::needless_maybe_sized)]
306    pub const fn size_of<T: Sized + ?core::marker::Sized>() -> usize {
307        core::mem::size_of::<T>()
308    }
309}
310
311#[cfg(zerocopy_diagnostic_on_unimplemented)]
312pub use __size_of::size_of;
313#[cfg(not(zerocopy_diagnostic_on_unimplemented))]
314pub use core::mem::size_of;
315
316/// Does the struct type `$t` have padding?
317///
318/// `$ts` is the list of the type of every field in `$t`. `$t` must be a
319/// struct type, or else `struct_has_padding!`'s result may be meaningless.
320///
321/// Note that `struct_has_padding!`'s results are independent of `repcr` since
322/// they only consider the size of the type and the sizes of the fields.
323/// Whatever the repr, the size of the type already takes into account any
324/// padding that the compiler has decided to add. Structs with well-defined
325/// representations (such as `repr(C)`) can use this macro to check for padding.
326/// Note that while this may yield some consistent value for some `repr(Rust)`
327/// structs, it is not guaranteed across platforms or compilations.
328#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
329#[macro_export]
330macro_rules! struct_has_padding {
331    ($t:ty, [$($ts:ty),*]) => {
332        ::zerocopy::util::macro_util::size_of::<$t>() > 0 $(+ ::zerocopy::util::macro_util::size_of::<$ts>())*
333    };
334}
335
336/// Does the union type `$t` have padding?
337///
338/// `$ts` is the list of the type of every field in `$t`. `$t` must be a
339/// union type, or else `union_has_padding!`'s result may be meaningless.
340///
341/// Note that `union_has_padding!`'s results are independent of `repr` since
342/// they only consider the size of the type and the sizes of the fields.
343/// Whatever the repr, the size of the type already takes into account any
344/// padding that the compiler has decided to add. Unions with well-defined
345/// representations (such as `repr(C)`) can use this macro to check for padding.
346/// Note that while this may yield some consistent value for some `repr(Rust)`
347/// unions, it is not guaranteed across platforms or compilations.
348#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
349#[macro_export]
350macro_rules! union_has_padding {
351    ($t:ty, [$($ts:ty),*]) => {
352        false $(|| ::zerocopy::util::macro_util::size_of::<$t>() != ::zerocopy::util::macro_util::size_of::<$ts>())*
353    };
354}
355
356/// Does the enum type `$t` have padding?
357///
358/// `$disc` is the type of the enum tag, and `$ts` is a list of fields in each
359/// square-bracket-delimited variant. `$t` must be an enum, or else
360/// `enum_has_padding!`'s result may be meaningless. An enum has padding if any
361/// of its variant structs [1][2] contain padding, and so all of the variants of
362/// an enum must be "full" in order for the enum to not have padding.
363///
364/// The results of `enum_has_padding!` require that the enum is not
365/// `repr(Rust)`, as `repr(Rust)` enums may niche the enum's tag and reduce the
366/// total number of bytes required to represent the enum as a result. As long as
367/// the enum is `repr(C)`, `repr(int)`, or `repr(C, int)`, this will
368/// consistently return whether the enum contains any padding bytes.
369///
370/// [1]: https://doc.rust-lang.org/1.81.0/reference/type-layout.html#reprc-enums-with-fields
371/// [2]: https://doc.rust-lang.org/1.81.0/reference/type-layout.html#primitive-representation-of-enums-with-fields
372#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
373#[macro_export]
374macro_rules! enum_has_padding {
375    ($t:ty, $disc:ty, $([$($ts:ty),*]),*) => {
376        false $(
377            || ::zerocopy::util::macro_util::size_of::<$t>()
378                != (
379                    ::zerocopy::util::macro_util::size_of::<$disc>()
380                    $(+ ::zerocopy::util::macro_util::size_of::<$ts>())*
381                )
382        )*
383    }
384}
385
386/// Does `t` have alignment greater than or equal to `u`?  If not, this macro
387/// produces a compile error. It must be invoked in a dead codepath. This is
388/// used in `transmute_ref!` and `transmute_mut!`.
389#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
390#[macro_export]
391macro_rules! assert_align_gt_eq {
392    ($t:ident, $u: ident) => {{
393        // The comments here should be read in the context of this macro's
394        // invocations in `transmute_ref!` and `transmute_mut!`.
395        if false {
396            // The type wildcard in this bound is inferred to be `T` because
397            // `align_of.into_t()` is assigned to `t` (which has type `T`).
398            let align_of: $crate::util::macro_util::AlignOf<_> = unreachable!();
399            $t = align_of.into_t();
400            // `max_aligns` is inferred to have type `MaxAlignsOf<T, U>` because
401            // of the inferred types of `t` and `u`.
402            let mut max_aligns = $crate::util::macro_util::MaxAlignsOf::new($t, $u);
403
404            // This transmute will only compile successfully if
405            // `align_of::<T>() == max(align_of::<T>(), align_of::<U>())` - in
406            // other words, if `align_of::<T>() >= align_of::<U>()`.
407            //
408            // SAFETY: This code is never run.
409            max_aligns = unsafe {
410                // Clippy: We can't annotate the types; this macro is designed
411                // to infer the types from the calling context.
412                #[allow(clippy::missing_transmute_annotations)]
413                $crate::util::macro_util::core_reexport::mem::transmute(align_of)
414            };
415        } else {
416            loop {}
417        }
418    }};
419}
420
421/// Do `t` and `u` have the same size?  If not, this macro produces a compile
422/// error. It must be invoked in a dead codepath. This is used in
423/// `transmute_ref!` and `transmute_mut!`.
424#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
425#[macro_export]
426macro_rules! assert_size_eq {
427    ($t:ident, $u: ident) => {{
428        // The comments here should be read in the context of this macro's
429        // invocations in `transmute_ref!` and `transmute_mut!`.
430        if false {
431            // SAFETY: This code is never run.
432            $u = unsafe {
433                // Clippy:
434                // - It's okay to transmute a type to itself.
435                // - We can't annotate the types; this macro is designed to
436                //   infer the types from the calling context.
437                #[allow(clippy::useless_transmute, clippy::missing_transmute_annotations)]
438                $crate::util::macro_util::core_reexport::mem::transmute($t)
439            };
440        } else {
441            loop {}
442        }
443    }};
444}
445
446/// Transmutes a reference of one type to a reference of another type.
447///
448/// # Safety
449///
450/// The caller must guarantee that:
451/// - `Src: IntoBytes + Immutable`
452/// - `Dst: FromBytes + Immutable`
453/// - `size_of::<Src>() == size_of::<Dst>()`
454/// - `align_of::<Src>() >= align_of::<Dst>()`
455#[inline(always)]
456pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>(
457    src: &'src Src,
458) -> &'dst Dst {
459    let src: *const Src = src;
460    let dst = src.cast::<Dst>();
461    // SAFETY:
462    // - We know that it is sound to view the target type of the input reference
463    //   (`Src`) as the target type of the output reference (`Dst`) because the
464    //   caller has guaranteed that `Src: IntoBytes`, `Dst: FromBytes`, and
465    //   `size_of::<Src>() == size_of::<Dst>()`.
466    // - We know that there are no `UnsafeCell`s, and thus we don't have to
467    //   worry about `UnsafeCell` overlap, because `Src: Immutable` and `Dst:
468    //   Immutable`.
469    // - The caller has guaranteed that alignment is not increased.
470    // - We know that the returned lifetime will not outlive the input lifetime
471    //   thanks to the lifetime bounds on this function.
472    //
473    // TODO(#67): Once our MSRV is 1.58, replace this `transmute` with `&*dst`.
474    #[allow(clippy::transmute_ptr_to_ref)]
475    unsafe {
476        mem::transmute(dst)
477    }
478}
479
480/// Transmutes a mutable reference of one type to a mutable reference of another
481/// type.
482///
483/// # Safety
484///
485/// The caller must guarantee that:
486/// - `Src: FromBytes + IntoBytes`
487/// - `Dst: FromBytes + IntoBytes`
488/// - `size_of::<Src>() == size_of::<Dst>()`
489/// - `align_of::<Src>() >= align_of::<Dst>()`
490// TODO(#686): Consider removing the `Immutable` requirement.
491#[inline(always)]
492pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>(
493    src: &'src mut Src,
494) -> &'dst mut Dst {
495    let src: *mut Src = src;
496    let dst = src.cast::<Dst>();
497    // SAFETY:
498    // - We know that it is sound to view the target type of the input reference
499    //   (`Src`) as the target type of the output reference (`Dst`) and
500    //   vice-versa because the caller has guaranteed that `Src: FromBytes +
501    //   IntoBytes`, `Dst: FromBytes + IntoBytes`, and `size_of::<Src>() ==
502    //   size_of::<Dst>()`.
503    // - The caller has guaranteed that alignment is not increased.
504    // - We know that the returned lifetime will not outlive the input lifetime
505    //   thanks to the lifetime bounds on this function.
506    unsafe { &mut *dst }
507}
508
509/// Is a given source a valid instance of `Dst`?
510///
511/// If so, returns `src` casted to a `Ptr<Dst, _>`. Otherwise returns `None`.
512///
513/// # Safety
514///
515/// Unsafe code may assume that, if `try_cast_or_pme(src)` returns `Some`,
516/// `*src` is a bit-valid instance of `Dst`, and that the size of `Src` is
517/// greater than or equal to the size of `Dst`.
518///
519/// # Panics
520///
521/// `try_cast_or_pme` may either produce a post-monomorphization error or a
522/// panic if `Dst` not the same size as `Src`. Otherwise, `try_cast_or_pme`
523/// panics under the same circumstances as [`is_bit_valid`].
524///
525/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
526#[doc(hidden)]
527#[inline]
528fn try_cast_or_pme<Src, Dst, I, R>(
529    src: Ptr<'_, Src, I>,
530) -> Result<
531    Ptr<'_, Dst, (I::Aliasing, invariant::Any, invariant::Valid)>,
532    ValidityError<Ptr<'_, Src, I>, Dst>,
533>
534where
535    Src: IntoBytes,
536    Dst: TryFromBytes + AliasingSafe<Src, I::Aliasing, R>,
537    I: Invariants<Validity = invariant::Valid>,
538    I::Aliasing: AtLeast<invariant::Shared>,
539    R: AliasingSafeReason,
540{
541    static_assert!(Src, Dst => mem::size_of::<Dst>() == mem::size_of::<Src>());
542
543    // SAFETY: This is a pointer cast, satisfying the following properties:
544    // - `p as *mut Dst` addresses a subset of the `bytes` addressed by `src`,
545    //   because we assert above that the size of `Dst` equal to the size of
546    //   `Src`.
547    // - `p as *mut Dst` is a provenance-preserving cast
548    // - Because `Dst: AliasingSafe<Src, I::Aliasing, _>`, either:
549    //   - `I::Aliasing` is `Exclusive`
550    //   - `Src` and `Dst` are both `Immutable`, in which case they
551    //     trivially contain `UnsafeCell`s at identical locations
552    #[allow(clippy::as_conversions)]
553    let c_ptr = unsafe { src.cast_unsized(|p| p as *mut Dst) };
554
555    // SAFETY: `c_ptr` is derived from `src` which is `IntoBytes`. By
556    // invariant on `IntoByte`s, `c_ptr`'s referent consists entirely of
557    // initialized bytes.
558    let c_ptr = unsafe { c_ptr.assume_initialized() };
559
560    match c_ptr.try_into_valid() {
561        Ok(ptr) => Ok(ptr),
562        Err(err) => {
563            // Re-cast `Ptr<Dst>` to `Ptr<Src>`.
564            let ptr = err.into_src();
565            // SAFETY: This is a pointer cast, satisfying the following
566            // properties:
567            // - `p as *mut Src` addresses a subset of the `bytes` addressed by
568            //   `ptr`, because we assert above that the size of `Dst` is equal
569            //   to the size of `Src`.
570            // - `p as *mut Src` is a provenance-preserving cast
571            // - Because `Dst: AliasingSafe<Src, I::Aliasing, _>`, either:
572            //   - `I::Aliasing` is `Exclusive`
573            //   - `Src` and `Dst` are both `Immutable`, in which case they
574            //     trivially contain `UnsafeCell`s at identical locations
575            #[allow(clippy::as_conversions)]
576            let ptr = unsafe { ptr.cast_unsized(|p| p as *mut Src) };
577            // SAFETY: `ptr` is `src`, and has the same alignment invariant.
578            let ptr = unsafe { ptr.assume_alignment::<I::Alignment>() };
579            // SAFETY: `ptr` is `src` and has the same validity invariant.
580            let ptr = unsafe { ptr.assume_validity::<I::Validity>() };
581            Err(ValidityError::new(ptr.unify_invariants()))
582        }
583    }
584}
585
586/// Attempts to transmute `Src` into `Dst`.
587///
588/// A helper for `try_transmute!`.
589///
590/// # Panics
591///
592/// `try_transmute` may either produce a post-monomorphization error or a panic
593/// if `Dst` is bigger than `Src`. Otherwise, `try_transmute` panics under the
594/// same circumstances as [`is_bit_valid`].
595///
596/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
597#[inline(always)]
598pub fn try_transmute<Src, Dst>(src: Src) -> Result<Dst, ValidityError<Src, Dst>>
599where
600    Src: IntoBytes,
601    Dst: TryFromBytes,
602{
603    let mut src = ManuallyDrop::new(src);
604    let ptr = Ptr::from_mut(&mut src);
605    // Wrapping `Dst` in `Unalign` ensures that this cast does not fail due to
606    // alignment requirements.
607    match try_cast_or_pme::<_, ManuallyDrop<Unalign<Dst>>, _, BecauseExclusive>(ptr) {
608        Ok(ptr) => {
609            let dst = ptr.bikeshed_recall_aligned().as_mut();
610            // SAFETY: By shadowing `dst`, we ensure that `dst` is not re-used
611            // after taking its inner value.
612            let dst = unsafe { ManuallyDrop::take(dst) };
613            Ok(dst.into_inner())
614        }
615        Err(_) => Err(ValidityError::new(ManuallyDrop::into_inner(src))),
616    }
617}
618
619/// Attempts to transmute `&Src` into `&Dst`.
620///
621/// A helper for `try_transmute_ref!`.
622///
623/// # Panics
624///
625/// `try_transmute_ref` may either produce a post-monomorphization error or a
626/// panic if `Dst` is bigger or has a stricter alignment requirement than `Src`.
627/// Otherwise, `try_transmute_ref` panics under the same circumstances as
628/// [`is_bit_valid`].
629///
630/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
631#[inline(always)]
632pub fn try_transmute_ref<Src, Dst>(src: &Src) -> Result<&Dst, ValidityError<&Src, Dst>>
633where
634    Src: IntoBytes + Immutable,
635    Dst: TryFromBytes + Immutable,
636{
637    match try_cast_or_pme::<Src, Dst, _, BecauseImmutable>(Ptr::from_ref(src)) {
638        Ok(ptr) => {
639            static_assert!(Src, Dst => mem::align_of::<Dst>() <= mem::align_of::<Src>());
640            // SAFETY: We have checked that `Dst` does not have a stricter
641            // alignment requirement than `Src`.
642            let ptr = unsafe { ptr.assume_alignment::<invariant::Aligned>() };
643            Ok(ptr.as_ref())
644        }
645        Err(err) => Err(err.map_src(Ptr::as_ref)),
646    }
647}
648
649/// Attempts to transmute `&mut Src` into `&mut Dst`.
650///
651/// A helper for `try_transmute_mut!`.
652///
653/// # Panics
654///
655/// `try_transmute_mut` may either produce a post-monomorphization error or a
656/// panic if `Dst` is bigger or has a stricter alignment requirement than `Src`.
657/// Otherwise, `try_transmute_mut` panics under the same circumstances as
658/// [`is_bit_valid`].
659///
660/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
661#[inline(always)]
662pub fn try_transmute_mut<Src, Dst>(src: &mut Src) -> Result<&mut Dst, ValidityError<&mut Src, Dst>>
663where
664    Src: IntoBytes,
665    Dst: TryFromBytes,
666{
667    match try_cast_or_pme::<Src, Dst, _, BecauseExclusive>(Ptr::from_mut(src)) {
668        Ok(ptr) => {
669            static_assert!(Src, Dst => mem::align_of::<Dst>() <= mem::align_of::<Src>());
670            // SAFETY: We have checked that `Dst` does not have a stricter
671            // alignment requirement than `Src`.
672            let ptr = unsafe { ptr.assume_alignment::<invariant::Aligned>() };
673            Ok(ptr.as_mut())
674        }
675        Err(err) => Err(err.map_src(Ptr::as_mut)),
676    }
677}
678
679/// A function which emits a warning if its return value is not used.
680#[must_use]
681#[inline(always)]
682pub const fn must_use<T>(t: T) -> T {
683    t
684}
685
686// NOTE: We can't change this to a `pub use core as core_reexport` until [1] is
687// fixed or we update to a semver-breaking version (as of this writing, 0.8.0)
688// on the `main` branch.
689//
690// [1] https://github.com/obi1kenobi/cargo-semver-checks/issues/573
691pub mod core_reexport {
692    pub use core::*;
693
694    pub mod mem {
695        pub use core::mem::*;
696    }
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702    use crate::util::testutil::*;
703
704    #[test]
705    fn test_align_of() {
706        macro_rules! test {
707            ($ty:ty) => {
708                assert_eq!(mem::size_of::<AlignOf<$ty>>(), mem::align_of::<$ty>());
709            };
710        }
711
712        test!(());
713        test!(u8);
714        test!(AU64);
715        test!([AU64; 2]);
716    }
717
718    #[test]
719    fn test_max_aligns_of() {
720        macro_rules! test {
721            ($t:ty, $u:ty) => {
722                assert_eq!(
723                    mem::size_of::<MaxAlignsOf<$t, $u>>(),
724                    core::cmp::max(mem::align_of::<$t>(), mem::align_of::<$u>())
725                );
726            };
727        }
728
729        test!(u8, u8);
730        test!(u8, AU64);
731        test!(AU64, u8);
732    }
733
734    #[test]
735    fn test_typed_align_check() {
736        // Test that the type-based alignment check used in
737        // `assert_align_gt_eq!` behaves as expected.
738
739        macro_rules! assert_t_align_gteq_u_align {
740            ($t:ty, $u:ty, $gteq:expr) => {
741                assert_eq!(
742                    mem::size_of::<MaxAlignsOf<$t, $u>>() == mem::size_of::<AlignOf<$t>>(),
743                    $gteq
744                );
745            };
746        }
747
748        assert_t_align_gteq_u_align!(u8, u8, true);
749        assert_t_align_gteq_u_align!(AU64, AU64, true);
750        assert_t_align_gteq_u_align!(AU64, u8, true);
751        assert_t_align_gteq_u_align!(u8, AU64, false);
752    }
753
754    // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove
755    // this `cfg` when `size_of_val_raw` is stabilized.
756    #[allow(clippy::decimal_literal_representation)]
757    #[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
758    #[test]
759    fn test_trailing_field_offset() {
760        assert_eq!(mem::align_of::<Aligned64kAllocation>(), _64K);
761
762        macro_rules! test {
763            (#[$cfg:meta] ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {{
764                #[$cfg]
765                struct Test($(#[allow(dead_code)] $ts,)* #[allow(dead_code)] $trailing_field_ty);
766                assert_eq!(test!(@offset $($ts),* ; $trailing_field_ty), $expect);
767            }};
768            (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {
769                test!(#[$cfg] ($($ts),* ; $trailing_field_ty) => $expect);
770                test!($(#[$cfgs])* ($($ts),* ; $trailing_field_ty) => $expect);
771            };
772            (@offset ; $_trailing:ty) => { trailing_field_offset!(Test, 0) };
773            (@offset $_t:ty ; $_trailing:ty) => { trailing_field_offset!(Test, 1) };
774        }
775
776        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; u8) => Some(0));
777        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; [u8]) => Some(0));
778        test!(#[repr(C)] #[repr(C, packed)] (u8; u8) => Some(1));
779        test!(#[repr(C)] (; AU64) => Some(0));
780        test!(#[repr(C)] (; [AU64]) => Some(0));
781        test!(#[repr(C)] (u8; AU64) => Some(8));
782        test!(#[repr(C)] (u8; [AU64]) => Some(8));
783        test!(#[repr(C)] (; Nested<u8, AU64>) => Some(0));
784        test!(#[repr(C)] (; Nested<u8, [AU64]>) => Some(0));
785        test!(#[repr(C)] (u8; Nested<u8, AU64>) => Some(8));
786        test!(#[repr(C)] (u8; Nested<u8, [AU64]>) => Some(8));
787
788        // Test that `packed(N)` limits the offset of the trailing field.
789        test!(#[repr(C, packed(        1))] (u8; elain::Align<        2>) => Some(        1));
790        test!(#[repr(C, packed(        2))] (u8; elain::Align<        4>) => Some(        2));
791        test!(#[repr(C, packed(        4))] (u8; elain::Align<        8>) => Some(        4));
792        test!(#[repr(C, packed(        8))] (u8; elain::Align<       16>) => Some(        8));
793        test!(#[repr(C, packed(       16))] (u8; elain::Align<       32>) => Some(       16));
794        test!(#[repr(C, packed(       32))] (u8; elain::Align<       64>) => Some(       32));
795        test!(#[repr(C, packed(       64))] (u8; elain::Align<      128>) => Some(       64));
796        test!(#[repr(C, packed(      128))] (u8; elain::Align<      256>) => Some(      128));
797        test!(#[repr(C, packed(      256))] (u8; elain::Align<      512>) => Some(      256));
798        test!(#[repr(C, packed(      512))] (u8; elain::Align<     1024>) => Some(      512));
799        test!(#[repr(C, packed(     1024))] (u8; elain::Align<     2048>) => Some(     1024));
800        test!(#[repr(C, packed(     2048))] (u8; elain::Align<     4096>) => Some(     2048));
801        test!(#[repr(C, packed(     4096))] (u8; elain::Align<     8192>) => Some(     4096));
802        test!(#[repr(C, packed(     8192))] (u8; elain::Align<    16384>) => Some(     8192));
803        test!(#[repr(C, packed(    16384))] (u8; elain::Align<    32768>) => Some(    16384));
804        test!(#[repr(C, packed(    32768))] (u8; elain::Align<    65536>) => Some(    32768));
805        test!(#[repr(C, packed(    65536))] (u8; elain::Align<   131072>) => Some(    65536));
806        /* Alignments above 65536 are not yet supported.
807        test!(#[repr(C, packed(   131072))] (u8; elain::Align<   262144>) => Some(   131072));
808        test!(#[repr(C, packed(   262144))] (u8; elain::Align<   524288>) => Some(   262144));
809        test!(#[repr(C, packed(   524288))] (u8; elain::Align<  1048576>) => Some(   524288));
810        test!(#[repr(C, packed(  1048576))] (u8; elain::Align<  2097152>) => Some(  1048576));
811        test!(#[repr(C, packed(  2097152))] (u8; elain::Align<  4194304>) => Some(  2097152));
812        test!(#[repr(C, packed(  4194304))] (u8; elain::Align<  8388608>) => Some(  4194304));
813        test!(#[repr(C, packed(  8388608))] (u8; elain::Align< 16777216>) => Some(  8388608));
814        test!(#[repr(C, packed( 16777216))] (u8; elain::Align< 33554432>) => Some( 16777216));
815        test!(#[repr(C, packed( 33554432))] (u8; elain::Align< 67108864>) => Some( 33554432));
816        test!(#[repr(C, packed( 67108864))] (u8; elain::Align< 33554432>) => Some( 67108864));
817        test!(#[repr(C, packed( 33554432))] (u8; elain::Align<134217728>) => Some( 33554432));
818        test!(#[repr(C, packed(134217728))] (u8; elain::Align<268435456>) => Some(134217728));
819        test!(#[repr(C, packed(268435456))] (u8; elain::Align<268435456>) => Some(268435456));
820        */
821
822        // Test that `align(N)` does not limit the offset of the trailing field.
823        test!(#[repr(C, align(        1))] (u8; elain::Align<        2>) => Some(        2));
824        test!(#[repr(C, align(        2))] (u8; elain::Align<        4>) => Some(        4));
825        test!(#[repr(C, align(        4))] (u8; elain::Align<        8>) => Some(        8));
826        test!(#[repr(C, align(        8))] (u8; elain::Align<       16>) => Some(       16));
827        test!(#[repr(C, align(       16))] (u8; elain::Align<       32>) => Some(       32));
828        test!(#[repr(C, align(       32))] (u8; elain::Align<       64>) => Some(       64));
829        test!(#[repr(C, align(       64))] (u8; elain::Align<      128>) => Some(      128));
830        test!(#[repr(C, align(      128))] (u8; elain::Align<      256>) => Some(      256));
831        test!(#[repr(C, align(      256))] (u8; elain::Align<      512>) => Some(      512));
832        test!(#[repr(C, align(      512))] (u8; elain::Align<     1024>) => Some(     1024));
833        test!(#[repr(C, align(     1024))] (u8; elain::Align<     2048>) => Some(     2048));
834        test!(#[repr(C, align(     2048))] (u8; elain::Align<     4096>) => Some(     4096));
835        test!(#[repr(C, align(     4096))] (u8; elain::Align<     8192>) => Some(     8192));
836        test!(#[repr(C, align(     8192))] (u8; elain::Align<    16384>) => Some(    16384));
837        test!(#[repr(C, align(    16384))] (u8; elain::Align<    32768>) => Some(    32768));
838        test!(#[repr(C, align(    32768))] (u8; elain::Align<    65536>) => Some(    65536));
839        /* Alignments above 65536 are not yet supported.
840        test!(#[repr(C, align(    65536))] (u8; elain::Align<   131072>) => Some(   131072));
841        test!(#[repr(C, align(   131072))] (u8; elain::Align<   262144>) => Some(   262144));
842        test!(#[repr(C, align(   262144))] (u8; elain::Align<   524288>) => Some(   524288));
843        test!(#[repr(C, align(   524288))] (u8; elain::Align<  1048576>) => Some(  1048576));
844        test!(#[repr(C, align(  1048576))] (u8; elain::Align<  2097152>) => Some(  2097152));
845        test!(#[repr(C, align(  2097152))] (u8; elain::Align<  4194304>) => Some(  4194304));
846        test!(#[repr(C, align(  4194304))] (u8; elain::Align<  8388608>) => Some(  8388608));
847        test!(#[repr(C, align(  8388608))] (u8; elain::Align< 16777216>) => Some( 16777216));
848        test!(#[repr(C, align( 16777216))] (u8; elain::Align< 33554432>) => Some( 33554432));
849        test!(#[repr(C, align( 33554432))] (u8; elain::Align< 67108864>) => Some( 67108864));
850        test!(#[repr(C, align( 67108864))] (u8; elain::Align< 33554432>) => Some( 33554432));
851        test!(#[repr(C, align( 33554432))] (u8; elain::Align<134217728>) => Some(134217728));
852        test!(#[repr(C, align(134217728))] (u8; elain::Align<268435456>) => Some(268435456));
853        */
854    }
855
856    // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove
857    // this `cfg` when `size_of_val_raw` is stabilized.
858    #[allow(clippy::decimal_literal_representation)]
859    #[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
860    #[test]
861    fn test_align_of_dst() {
862        // Test that `align_of!` correctly computes the alignment of DSTs.
863        assert_eq!(align_of!([elain::Align<1>]), Some(1));
864        assert_eq!(align_of!([elain::Align<2>]), Some(2));
865        assert_eq!(align_of!([elain::Align<4>]), Some(4));
866        assert_eq!(align_of!([elain::Align<8>]), Some(8));
867        assert_eq!(align_of!([elain::Align<16>]), Some(16));
868        assert_eq!(align_of!([elain::Align<32>]), Some(32));
869        assert_eq!(align_of!([elain::Align<64>]), Some(64));
870        assert_eq!(align_of!([elain::Align<128>]), Some(128));
871        assert_eq!(align_of!([elain::Align<256>]), Some(256));
872        assert_eq!(align_of!([elain::Align<512>]), Some(512));
873        assert_eq!(align_of!([elain::Align<1024>]), Some(1024));
874        assert_eq!(align_of!([elain::Align<2048>]), Some(2048));
875        assert_eq!(align_of!([elain::Align<4096>]), Some(4096));
876        assert_eq!(align_of!([elain::Align<8192>]), Some(8192));
877        assert_eq!(align_of!([elain::Align<16384>]), Some(16384));
878        assert_eq!(align_of!([elain::Align<32768>]), Some(32768));
879        assert_eq!(align_of!([elain::Align<65536>]), Some(65536));
880        /* Alignments above 65536 are not yet supported.
881        assert_eq!(align_of!([elain::Align<131072>]), Some(131072));
882        assert_eq!(align_of!([elain::Align<262144>]), Some(262144));
883        assert_eq!(align_of!([elain::Align<524288>]), Some(524288));
884        assert_eq!(align_of!([elain::Align<1048576>]), Some(1048576));
885        assert_eq!(align_of!([elain::Align<2097152>]), Some(2097152));
886        assert_eq!(align_of!([elain::Align<4194304>]), Some(4194304));
887        assert_eq!(align_of!([elain::Align<8388608>]), Some(8388608));
888        assert_eq!(align_of!([elain::Align<16777216>]), Some(16777216));
889        assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432));
890        assert_eq!(align_of!([elain::Align<67108864>]), Some(67108864));
891        assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432));
892        assert_eq!(align_of!([elain::Align<134217728>]), Some(134217728));
893        assert_eq!(align_of!([elain::Align<268435456>]), Some(268435456));
894        */
895    }
896
897    #[test]
898    fn test_enum_casts() {
899        // Test that casting the variants of enums with signed integer reprs to
900        // unsigned integers obeys expected signed -> unsigned casting rules.
901
902        #[repr(i8)]
903        enum ReprI8 {
904            MinusOne = -1,
905            Zero = 0,
906            Min = i8::MIN,
907            Max = i8::MAX,
908        }
909
910        #[allow(clippy::as_conversions)]
911        let x = ReprI8::MinusOne as u8;
912        assert_eq!(x, u8::MAX);
913
914        #[allow(clippy::as_conversions)]
915        let x = ReprI8::Zero as u8;
916        assert_eq!(x, 0);
917
918        #[allow(clippy::as_conversions)]
919        let x = ReprI8::Min as u8;
920        assert_eq!(x, 128);
921
922        #[allow(clippy::as_conversions)]
923        let x = ReprI8::Max as u8;
924        assert_eq!(x, 127);
925    }
926
927    #[test]
928    fn test_struct_has_padding() {
929        // Test that, for each provided repr, `struct_has_padding!` reports the
930        // expected value.
931        macro_rules! test {
932            (#[$cfg:meta] ($($ts:ty),*) => $expect:expr) => {{
933                #[$cfg]
934                struct Test($(#[allow(dead_code)] $ts),*);
935                assert_eq!(struct_has_padding!(Test, [$($ts),*]), $expect);
936            }};
937            (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),*) => $expect:expr) => {
938                test!(#[$cfg] ($($ts),*) => $expect);
939                test!($(#[$cfgs])* ($($ts),*) => $expect);
940            };
941        }
942
943        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] () => false);
944        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8) => false);
945        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8, ()) => false);
946        test!(#[repr(C)] #[repr(packed)] (u8, u8) => false);
947
948        test!(#[repr(C)] (u8, AU64) => true);
949        // Rust won't let you put `#[repr(packed)]` on a type which contains a
950        // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here.
951        // It's not ideal, but it definitely has align > 1 on /some/ of our CI
952        // targets, and this isn't a particularly complex macro we're testing
953        // anyway.
954        test!(#[repr(packed)] (u8, u64) => false);
955    }
956
957    #[test]
958    fn test_union_has_padding() {
959        // Test that, for each provided repr, `union_has_padding!` reports the
960        // expected value.
961        macro_rules! test {
962            (#[$cfg:meta] {$($fs:ident: $ts:ty),*} => $expect:expr) => {{
963                #[$cfg]
964                #[allow(unused)] // fields are never read
965                union Test{ $($fs: $ts),* }
966                assert_eq!(union_has_padding!(Test, [$($ts),*]), $expect);
967            }};
968            (#[$cfg:meta] $(#[$cfgs:meta])* {$($fs:ident: $ts:ty),*} => $expect:expr) => {
969                test!(#[$cfg] {$($fs: $ts),*} => $expect);
970                test!($(#[$cfgs])* {$($fs: $ts),*} => $expect);
971            };
972        }
973
974        test!(#[repr(C)] #[repr(packed)] {a: u8} => false);
975        test!(#[repr(C)] #[repr(packed)] {a: u8, b: u8} => false);
976
977        // Rust won't let you put `#[repr(packed)]` on a type which contains a
978        // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here.
979        // It's not ideal, but it definitely has align > 1 on /some/ of our CI
980        // targets, and this isn't a particularly complex macro we're testing
981        // anyway.
982        test!(#[repr(C)] #[repr(packed)] {a: u8, b: u64} => true);
983    }
984
985    #[test]
986    fn test_enum_has_padding() {
987        // Test that, for each provided repr, `enum_has_padding!` reports the
988        // expected value.
989        macro_rules! test {
990            (#[repr($disc:ident $(, $c:ident)?)] { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {
991                test!(@case #[repr($disc $(, $c)?)] { $($vs ($($ts),*),)* } => $expect);
992            };
993            (#[repr($disc:ident $(, $c:ident)?)] #[$cfg:meta] $(#[$cfgs:meta])* { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {
994                test!(@case #[repr($disc $(, $c)?)] #[$cfg] { $($vs ($($ts),*),)* } => $expect);
995                test!(#[repr($disc $(, $c)?)] $(#[$cfgs])* { $($vs ($($ts),*),)* } => $expect);
996            };
997            (@case #[repr($disc:ident $(, $c:ident)?)] $(#[$cfg:meta])? { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {{
998                #[repr($disc $(, $c)?)]
999                $(#[$cfg])?
1000                #[allow(unused)] // variants and fields are never used
1001                enum Test {
1002                    $($vs ($($ts),*),)*
1003                }
1004                assert_eq!(
1005                    enum_has_padding!(Test, $disc, $([$($ts),*]),*),
1006                    $expect
1007                );
1008            }};
1009        }
1010
1011        #[allow(unused)]
1012        #[repr(align(2))]
1013        struct U16(u16);
1014
1015        #[allow(unused)]
1016        #[repr(align(4))]
1017        struct U32(u32);
1018
1019        test!(#[repr(u8)] #[repr(C)] {
1020            A(u8),
1021        } => false);
1022        test!(#[repr(u16)] #[repr(C)] {
1023            A(u8, u8),
1024            B(U16),
1025        } => false);
1026        test!(#[repr(u32)] #[repr(C)] {
1027            A(u8, u8, u8, u8),
1028            B(U16, u8, u8),
1029            C(u8, u8, U16),
1030            D(U16, U16),
1031            E(U32),
1032        } => false);
1033
1034        // `repr(int)` can pack the discriminant more efficiently
1035        test!(#[repr(u8)] {
1036            A(u8, U16),
1037        } => false);
1038        test!(#[repr(u8)] {
1039            A(u8, U16, U32),
1040        } => false);
1041
1042        // `repr(C)` cannot
1043        test!(#[repr(u8, C)] {
1044            A(u8, U16),
1045        } => true);
1046        test!(#[repr(u8, C)] {
1047            A(u8, u8, u8, U32),
1048        } => true);
1049
1050        // And field ordering can always cause problems
1051        test!(#[repr(u8)] #[repr(C)] {
1052            A(U16, u8),
1053        } => true);
1054        test!(#[repr(u8)] #[repr(C)] {
1055            A(U32, u8, u8, u8),
1056        } => true);
1057    }
1058}