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