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