zerocopy/util/
macro_util.rs

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