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
20// FIXME(#29), FIXME(https://github.com/rust-lang/rust/issues/69835): Remove
21// this `cfg` when `size_of_val_raw` is stabilized.
22#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
23#[cfg(not(target_pointer_width = "16"))]
24use core::ptr::{self, NonNull};
25use core::{marker::PhantomData, mem, num::Wrapping};
26
27use crate::{
28    pointer::{
29        cast::CastSized,
30        invariant::{Aligned, Initialized, Valid},
31        BecauseImmutable,
32    },
33    FromBytes, Immutable, IntoBytes, KnownLayout, Ptr, ReadOnly, TryFromBytes, ValidityError,
34};
35
36/// Projects the type of the field at `Index` in `Self` without regard for field
37/// privacy.
38///
39/// The `Index` parameter is any sort of handle that identifies the field; its
40/// definition is the obligation of the implementer.
41///
42/// # Safety
43///
44/// Unsafe code may assume that this accurately reflects the definition of
45/// `Self`.
46pub unsafe trait Field<Index> {
47    /// The type of the field at `Index`.
48    type Type: ?Sized;
49}
50
51#[cfg_attr(
52    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
53    diagnostic::on_unimplemented(
54        message = "`{T}` has {PADDING_BYTES} total byte(s) of padding",
55        label = "types with padding cannot implement `IntoBytes`",
56        note = "consider using `zerocopy::Unalign` to lower the alignment of individual fields",
57        note = "consider adding explicit fields where padding would be",
58        note = "consider using `#[repr(packed)]` to remove padding"
59    )
60)]
61pub trait PaddingFree<T: ?Sized, const PADDING_BYTES: usize> {}
62impl<T: ?Sized> PaddingFree<T, 0> for () {}
63
64// FIXME(#1112): In the slice DST case, we should delegate to *both*
65// `PaddingFree` *and* `DynamicPaddingFree` (and probably rename `PaddingFree`
66// to `StaticPaddingFree` or something - or introduce a third trait with that
67// name) so that we can have more clear error messages.
68
69#[cfg_attr(
70    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
71    diagnostic::on_unimplemented(
72        message = "`{T}` has one or more padding bytes",
73        label = "types with padding cannot implement `IntoBytes`",
74        note = "consider using `zerocopy::Unalign` to lower the alignment of individual fields",
75        note = "consider adding explicit fields where padding would be",
76        note = "consider using `#[repr(packed)]` to remove padding"
77    )
78)]
79pub trait DynamicPaddingFree<T: ?Sized, const HAS_PADDING: bool> {}
80impl<T: ?Sized> DynamicPaddingFree<T, false> for () {}
81
82#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
83#[cfg(not(target_pointer_width = "16"))]
84const _64K: usize = 1 << 16;
85
86// FIXME(#29), FIXME(https://github.com/rust-lang/rust/issues/69835): Remove
87// this `cfg` when `size_of_val_raw` is stabilized.
88#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
89#[cfg(not(target_pointer_width = "16"))]
90#[repr(C, align(65536))]
91struct Aligned64kAllocation([u8; _64K]);
92
93/// A pointer to an aligned allocation of size 2^16.
94///
95/// # Safety
96///
97/// `ALIGNED_64K_ALLOCATION` is guaranteed to point to the entirety of an
98/// allocation with size and alignment 2^16, and to have valid provenance.
99// FIXME(#29), FIXME(https://github.com/rust-lang/rust/issues/69835): Remove
100// this `cfg` when `size_of_val_raw` is stabilized.
101#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
102#[cfg(not(target_pointer_width = "16"))]
103pub const ALIGNED_64K_ALLOCATION: NonNull<[u8]> = {
104    const REF: &Aligned64kAllocation = &Aligned64kAllocation([0; _64K]);
105    let ptr: *const Aligned64kAllocation = REF;
106    let ptr: *const [u8] = ptr::slice_from_raw_parts(ptr.cast(), _64K);
107    // SAFETY:
108    // - `ptr` is derived from a Rust reference, which is guaranteed to be
109    //   non-null.
110    // - `ptr` is derived from an `&Aligned64kAllocation`, which has size and
111    //   alignment `_64K` as promised. Its length is initialized to `_64K`,
112    //   which means that it refers to the entire allocation.
113    // - `ptr` is derived from a Rust reference, which is guaranteed to have
114    //   valid provenance.
115    //
116    // FIXME(#429): Once `NonNull::new_unchecked` docs document that it
117    // preserves provenance, cite those docs.
118    // FIXME: Replace this `as` with `ptr.cast_mut()` once our MSRV >= 1.65
119    #[allow(clippy::as_conversions)]
120    unsafe {
121        NonNull::new_unchecked(ptr as *mut _)
122    }
123};
124
125/// Computes the offset of the base of the field `$trailing_field_name` within
126/// the type `$ty`.
127///
128/// `trailing_field_offset!` produces code which is valid in a `const` context.
129// FIXME(#29), FIXME(https://github.com/rust-lang/rust/issues/69835): Remove
130// this `cfg` when `size_of_val_raw` is stabilized.
131#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
132#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
133#[macro_export]
134macro_rules! trailing_field_offset {
135    ($ty:ty, $trailing_field_name:tt) => {{
136        let min_size = {
137            let zero_elems: *const [()] =
138                $crate::util::macro_util::core_reexport::ptr::slice_from_raw_parts(
139                    $crate::util::macro_util::core_reexport::ptr::NonNull::<()>::dangling()
140                        .as_ptr()
141                        .cast_const(),
142                    0,
143                );
144            // SAFETY:
145            // - If `$ty` is `Sized`, `size_of_val_raw` is always safe to call.
146            // - Otherwise:
147            //   - If `$ty` is not a slice DST, this pointer conversion will
148            //     fail due to "mismatched vtable kinds", and compilation will
149            //     fail.
150            //   - If `$ty` is a slice DST, we have constructed `zero_elems` to
151            //     have zero trailing slice elements. Per the `size_of_val_raw`
152            //     docs, "For the special case where the dynamic tail length is
153            //     0, this function is safe to call." [1]
154            //
155            // [1] https://doc.rust-lang.org/nightly/std/mem/fn.size_of_val_raw.html
156            unsafe {
157                #[allow(clippy::as_conversions)]
158                $crate::util::macro_util::core_reexport::mem::size_of_val_raw(
159                    zero_elems as *const $ty,
160                )
161            }
162        };
163
164        assert!(min_size <= _64K);
165
166        #[allow(clippy::as_conversions)]
167        let ptr = ALIGNED_64K_ALLOCATION.as_ptr() as *const $ty;
168
169        // SAFETY:
170        // - Thanks to the preceding `assert!`, we know that the value with zero
171        //   elements fits in `_64K` bytes, and thus in the allocation addressed
172        //   by `ALIGNED_64K_ALLOCATION`. The offset of the trailing field is
173        //   guaranteed to be no larger than this size, so this field projection
174        //   is guaranteed to remain in-bounds of its allocation.
175        // - Because the minimum size is no larger than `_64K` bytes, and
176        //   because an object's size must always be a multiple of its alignment
177        //   [1], we know that `$ty`'s alignment is no larger than `_64K`. The
178        //   allocation addressed by `ALIGNED_64K_ALLOCATION` is guaranteed to
179        //   be aligned to `_64K`, so `ptr` is guaranteed to satisfy `$ty`'s
180        //   alignment.
181        // - As required by `addr_of!`, we do not write through `field`.
182        //
183        //   Note that, as of [2], this requirement is technically unnecessary
184        //   for Rust versions >= 1.75.0, but no harm in guaranteeing it anyway
185        //   until we bump our MSRV.
186        //
187        // [1] Per https://doc.rust-lang.org/reference/type-layout.html:
188        //
189        //   The size of a value is always a multiple of its alignment.
190        //
191        // [2] https://github.com/rust-lang/reference/pull/1387
192        let field = unsafe {
193            $crate::util::macro_util::core_reexport::ptr::addr_of!((*ptr).$trailing_field_name)
194        };
195        // SAFETY:
196        // - Both `ptr` and `field` are derived from the same allocated object.
197        // - By the preceding safety comment, `field` is in bounds of that
198        //   allocated object.
199        // - The distance, in bytes, between `ptr` and `field` is required to be
200        //   a multiple of the size of `u8`, which is trivially true because
201        //   `u8`'s size is 1.
202        // - The distance, in bytes, cannot overflow `isize`. This is guaranteed
203        //   because no allocated object can have a size larger than can fit in
204        //   `isize`. [1]
205        // - The distance being in-bounds cannot rely on wrapping around the
206        //   address space. This is guaranteed because the same is guaranteed of
207        //   allocated objects. [1]
208        //
209        // [1] FIXME(#429), FIXME(https://github.com/rust-lang/rust/pull/116675):
210        //     Once these are guaranteed in the Reference, cite it.
211        let offset = unsafe { field.cast::<u8>().offset_from(ptr.cast::<u8>()) };
212        // Guaranteed not to be lossy: `field` comes after `ptr`, so the offset
213        // from `ptr` to `field` is guaranteed to be positive.
214        assert!(offset >= 0);
215        Some(
216            #[allow(clippy::as_conversions)]
217            {
218                offset as usize
219            },
220        )
221    }};
222}
223
224/// Computes alignment of `$ty: ?Sized`.
225///
226/// `align_of!` produces code which is valid in a `const` context.
227// FIXME(#29), FIXME(https://github.com/rust-lang/rust/issues/69835): Remove
228// this `cfg` when `size_of_val_raw` is stabilized.
229#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
230#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
231#[macro_export]
232macro_rules! align_of {
233    ($ty:ty) => {{
234        // SAFETY: `OffsetOfTrailingIsAlignment` is `repr(C)`, and its layout is
235        // guaranteed [1] to begin with the single-byte layout for `_byte`,
236        // followed by the padding needed to align `_trailing`, then the layout
237        // for `_trailing`, and finally any trailing padding bytes needed to
238        // correctly-align the entire struct.
239        //
240        // This macro computes the alignment of `$ty` by counting the number of
241        // bytes preceding `_trailing`. For instance, if the alignment of `$ty`
242        // is `1`, then no padding is required align `_trailing` and it will be
243        // located immediately after `_byte` at offset 1. If the alignment of
244        // `$ty` is 2, then a single padding byte is required before
245        // `_trailing`, and `_trailing` will be located at offset 2.
246
247        // This correspondence between offset and alignment holds for all valid
248        // Rust alignments, and we confirm this exhaustively (or, at least up to
249        // the maximum alignment supported by `trailing_field_offset!`) in
250        // `test_align_of_dst`.
251        //
252        // [1]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprc
253
254        #[repr(C)]
255        struct OffsetOfTrailingIsAlignment {
256            _byte: u8,
257            _trailing: $ty,
258        }
259
260        trailing_field_offset!(OffsetOfTrailingIsAlignment, _trailing)
261    }};
262}
263
264mod size_to_tag {
265    pub trait SizeToTag<const SIZE: usize> {
266        type Tag;
267    }
268
269    impl SizeToTag<1> for () {
270        type Tag = u8;
271    }
272    impl SizeToTag<2> for () {
273        type Tag = u16;
274    }
275    impl SizeToTag<4> for () {
276        type Tag = u32;
277    }
278    impl SizeToTag<8> for () {
279        type Tag = u64;
280    }
281    impl SizeToTag<16> for () {
282        type Tag = u128;
283    }
284}
285
286/// An alias for the unsigned integer of the given size in bytes.
287#[doc(hidden)]
288pub type SizeToTag<const SIZE: usize> = <() as size_to_tag::SizeToTag<SIZE>>::Tag;
289
290// We put `Sized` in its own module so it can have the same name as the standard
291// library `Sized` without shadowing it in the parent module.
292#[cfg(not(no_zerocopy_diagnostic_on_unimplemented_1_78_0))]
293mod __size_of {
294    #[diagnostic::on_unimplemented(
295        message = "`{Self}` is unsized",
296        label = "`IntoBytes` needs all field types to be `Sized` in order to determine whether there is padding",
297        note = "consider using `#[repr(packed)]` to remove padding",
298        note = "`IntoBytes` does not require the fields of `#[repr(packed)]` types to be `Sized`"
299    )]
300    pub trait Sized: core::marker::Sized {}
301    impl<T: core::marker::Sized> Sized for T {}
302
303    #[inline(always)]
304    #[must_use]
305    #[allow(clippy::needless_maybe_sized)]
306    pub const fn size_of<T: Sized + ?core::marker::Sized>() -> usize {
307        core::mem::size_of::<T>()
308    }
309}
310
311#[cfg(no_zerocopy_diagnostic_on_unimplemented_1_78_0)]
312pub use core::mem::size_of;
313
314#[cfg(not(no_zerocopy_diagnostic_on_unimplemented_1_78_0))]
315pub use __size_of::size_of;
316
317/// How many padding bytes does the struct type `$t` have?
318///
319/// `$ts` is the list of the type of every field in `$t`. `$t` must be a struct
320/// type, or else `struct_padding!`'s result may be meaningless.
321///
322/// Note that `struct_padding!`'s results are independent of `repcr` since they
323/// only consider the size of the type and the sizes of the fields. Whatever the
324/// repr, the size of the type already takes into account any padding that the
325/// compiler has decided to add. Structs with well-defined representations (such
326/// as `repr(C)`) can use this macro to check for padding. Note that while this
327/// may yield some consistent value for some `repr(Rust)` structs, it is not
328/// guaranteed across platforms or compilations.
329#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
330#[macro_export]
331macro_rules! struct_padding {
332    ($t:ty, [$($ts:ty),*]) => {
333        $crate::util::macro_util::size_of::<$t>() - (0 $(+ $crate::util::macro_util::size_of::<$ts>())*)
334    };
335}
336
337/// Does the `repr(C)` struct type `$t` have padding?
338///
339/// `$ts` is the list of the type of every field in `$t`. `$t` must be a
340/// `repr(C)` struct type, or else `struct_has_padding!`'s result may be
341/// meaningless.
342#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
343#[macro_export]
344macro_rules! repr_c_struct_has_padding {
345    ($t:ty, [$($ts:tt),*]) => {{
346        let layout = $crate::DstLayout::for_repr_c_struct(
347            $crate::util::macro_util::core_reexport::option::Option::None,
348            $crate::util::macro_util::core_reexport::option::Option::None,
349            &[$($crate::repr_c_struct_has_padding!(@field $ts),)*]
350        );
351        layout.requires_static_padding() || layout.requires_dynamic_padding()
352    }};
353    (@field ([$t:ty])) => {
354        <[$t] as $crate::KnownLayout>::LAYOUT
355    };
356    (@field ($t:ty)) => {
357        $crate::DstLayout::for_unpadded_type::<$t>()
358    };
359    (@field [$t:ty]) => {
360        <[$t] as $crate::KnownLayout>::LAYOUT
361    };
362    (@field $t:ty) => {
363        $crate::DstLayout::for_unpadded_type::<$t>()
364    };
365}
366
367/// Does the union type `$t` have padding?
368///
369/// `$ts` is the list of the type of every field in `$t`. `$t` must be a union
370/// type, or else `union_padding!`'s result may be meaningless.
371///
372/// Note that `union_padding!`'s results are independent of `repr` since they
373/// only consider the size of the type and the sizes of the fields. Whatever the
374/// repr, the size of the type already takes into account any padding that the
375/// compiler has decided to add. Unions with well-defined representations (such
376/// as `repr(C)`) can use this macro to check for padding. Note that while this
377/// may yield some consistent value for some `repr(Rust)` unions, it is not
378/// guaranteed across platforms or compilations.
379#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
380#[macro_export]
381macro_rules! union_padding {
382    ($t:ty, [$($ts:ty),*]) => {{
383        let mut max = 0;
384        $({
385            let padding = $crate::util::macro_util::size_of::<$t>() - $crate::util::macro_util::size_of::<$ts>();
386            if padding > max {
387                max = padding;
388            }
389        })*
390        max
391    }};
392}
393
394/// How many padding bytes does the enum type `$t` have?
395///
396/// `$disc` is the type of the enum tag, and `$ts` is a list of fields in each
397/// square-bracket-delimited variant. `$t` must be an enum, or else
398/// `enum_padding!`'s result may be meaningless. An enum has padding if any of
399/// its variant structs [1][2] contain padding, and so all of the variants of an
400/// enum must be "full" in order for the enum to not have padding.
401///
402/// The results of `enum_padding!` require that the enum is not `repr(Rust)`, as
403/// `repr(Rust)` enums may niche the enum's tag and reduce the total number of
404/// bytes required to represent the enum as a result. As long as the enum is
405/// `repr(C)`, `repr(int)`, or `repr(C, int)`, this will consistently return
406/// whether the enum contains any padding bytes.
407///
408/// [1]: https://doc.rust-lang.org/1.81.0/reference/type-layout.html#reprc-enums-with-fields
409/// [2]: https://doc.rust-lang.org/1.81.0/reference/type-layout.html#primitive-representation-of-enums-with-fields
410#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
411#[macro_export]
412macro_rules! enum_padding {
413    ($t:ty, $disc:ty, $([$($ts:ty),*]),*) => {{
414        let mut max = 0;
415        $({
416            let padding = $crate::util::macro_util::size_of::<$t>()
417                - (
418                    $crate::util::macro_util::size_of::<$disc>()
419                    $(+ $crate::util::macro_util::size_of::<$ts>())*
420                );
421            if padding > max {
422                max = padding;
423            }
424        })*
425        max
426    }};
427}
428
429/// Unwraps an infallible `Result`.
430#[doc(hidden)]
431#[macro_export]
432macro_rules! into_inner {
433    ($e:expr) => {
434        match $e {
435            $crate::util::macro_util::core_reexport::result::Result::Ok(e) => e,
436            $crate::util::macro_util::core_reexport::result::Result::Err(i) => match i {},
437        }
438    };
439}
440
441/// Translates an identifier or tuple index into a numeric identifier.
442#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
443#[macro_export]
444macro_rules! ident_id {
445    ($field:ident) => {
446        $crate::util::macro_util::hash_name(stringify!($field))
447    };
448    ($field:literal) => {
449        $field
450    };
451}
452
453/// Computes the hash of a string.
454///
455/// NOTE(#2749) on hash collisions: This function's output only needs to be
456/// deterministic within a particular compilation. Thus, if a user ever reports
457/// a hash collision (very unlikely given the <= 16-byte special case), we can
458/// strengthen the hash function at that point and publish a new version. Since
459/// this is computed at compile time on small strings, we can easily use more
460/// expensive and higher-quality hash functions if need be.
461#[inline(always)]
462#[must_use]
463#[allow(clippy::as_conversions, clippy::indexing_slicing, clippy::arithmetic_side_effects)]
464pub const fn hash_name(name: &str) -> i128 {
465    let name = name.as_bytes();
466
467    // We guarantee freedom from hash collisions between any two strings of
468    // length 16 or less by having the hashes of such strings be equal to
469    // their value. There is still a possibility that such strings will have
470    // the same value as the hash of a string of length > 16.
471    if name.len() <= size_of::<u128>() {
472        let mut bytes = [0u8; 16];
473
474        let mut i = 0;
475        while i < name.len() {
476            bytes[i] = name[i];
477            i += 1;
478        }
479
480        return i128::from_ne_bytes(bytes);
481    };
482
483    // An implementation of FxHasher, although returning a u128. Probably
484    // not as strong as it could be, but probably more collision resistant
485    // than normal 64-bit FxHasher.
486    let mut hash = 0u128;
487    let mut i = 0;
488    while i < name.len() {
489        // This is just FxHasher's `0x517cc1b727220a95` constant
490        // concatenated back-to-back.
491        const K: u128 = 0x517cc1b727220a95517cc1b727220a95;
492        hash = (hash.rotate_left(5) ^ (name[i] as u128)).wrapping_mul(K);
493        i += 1;
494    }
495    i128::from_ne_bytes(hash.to_ne_bytes())
496}
497
498/// Attempts to transmute `Src` into `Dst`.
499///
500/// A helper for `try_transmute!`.
501///
502/// # Panics
503///
504/// `try_transmute` may either produce a post-monomorphization error or a panic
505/// if `Dst` is bigger than `Src`. Otherwise, `try_transmute` panics under the
506/// same circumstances as [`is_bit_valid`].
507///
508/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
509#[inline(always)]
510pub fn try_transmute<Src, Dst>(src: Src) -> Result<Dst, ValidityError<Src, Dst>>
511where
512    Src: IntoBytes,
513    Dst: TryFromBytes,
514{
515    static_assert!(Src, Dst => mem::size_of::<Dst>() == mem::size_of::<Src>());
516
517    let mu_src = mem::MaybeUninit::new(src);
518    // SAFETY: `MaybeUninit` has no validity requirements.
519    let mu_dst: mem::MaybeUninit<ReadOnly<Dst>> =
520        unsafe { crate::util::transmute_unchecked(mu_src) };
521
522    let ptr = Ptr::from_ref(&mu_dst);
523
524    // SAFETY: Since `Src: IntoBytes`, and since `size_of::<Src>() ==
525    // size_of::<Dst>()` by the preceding assertion, all of `mu_dst`'s bytes are
526    // initialized. `MaybeUninit` has no validity requirements, so even if
527    // `ptr` is used to mutate its referent (which it actually can't be - it's
528    // a shared `ReadOnly` pointer), that won't violate its referent's validity.
529    let ptr = unsafe { ptr.assume_validity::<Initialized>() };
530    if Dst::is_bit_valid(ptr.cast::<_, CastSized, _>()) {
531        // SAFETY: Since `Dst::is_bit_valid`, we know that `ptr`'s referent is
532        // bit-valid for `Dst`. `ptr` points to `mu_dst`, and no intervening
533        // operations have mutated it, so it is a bit-valid `Dst`.
534        Ok(ReadOnly::into_inner(unsafe { mu_dst.assume_init() }))
535    } else {
536        // SAFETY: `MaybeUninit` has no validity requirements.
537        let mu_src: mem::MaybeUninit<Src> = unsafe { crate::util::transmute_unchecked(mu_dst) };
538        // SAFETY: `mu_dst`/`mu_src` was constructed from `src` and never
539        // modified, so it is still bit-valid.
540        Err(ValidityError::new(unsafe { mu_src.assume_init() }))
541    }
542}
543
544/// See `try_transmute_ref!` documentation.
545pub trait TryTransmuteRefDst<'a> {
546    type Dst: ?Sized;
547
548    /// See `try_transmute_ref!` documentation.
549    fn try_transmute_ref(self) -> Result<&'a Self::Dst, ValidityError<&'a Self::Src, Self::Dst>>
550    where
551        Self: TryTransmuteRefSrc<'a>,
552        Self::Src: IntoBytes + Immutable + KnownLayout,
553        Self::Dst: TryFromBytes + Immutable + KnownLayout;
554}
555
556pub trait TryTransmuteRefSrc<'a> {
557    type Src: ?Sized;
558}
559
560impl<'a, Src, Dst> TryTransmuteRefSrc<'a> for Wrap<&'a Src, &'a Dst>
561where
562    Src: ?Sized,
563    Dst: ?Sized,
564{
565    type Src = Src;
566}
567
568impl<'a, Src, Dst> TryTransmuteRefDst<'a> for Wrap<&'a Src, &'a Dst>
569where
570    Src: IntoBytes + Immutable + KnownLayout + ?Sized,
571    Dst: TryFromBytes + Immutable + KnownLayout + ?Sized,
572{
573    type Dst = Dst;
574
575    #[inline(always)]
576    fn try_transmute_ref(
577        self,
578    ) -> Result<
579        &'a Dst,
580        ValidityError<&'a <Wrap<&'a Src, &'a Dst> as TryTransmuteRefSrc<'a>>::Src, Dst>,
581    > {
582        let ptr = Ptr::from_ref(self.0);
583        #[rustfmt::skip]
584        let res = ptr.try_with(#[inline(always)] |ptr| {
585            let ptr = ptr.recall_validity::<Initialized, _>();
586            let ptr = ptr.cast::<_, crate::layout::CastFrom<Dst>, _>();
587            ptr.try_into_valid()
588        });
589        match res {
590            Ok(ptr) => {
591                static_assert!(Src: ?Sized + KnownLayout, Dst: ?Sized + KnownLayout => {
592                    Src::LAYOUT.align.get() >= Dst::LAYOUT.align.get()
593                }, "cannot transmute reference when destination type has higher alignment than source type");
594                // SAFETY: We have checked that `Dst` does not have a stricter
595                // alignment requirement than `Src`.
596                let ptr = unsafe { ptr.assume_alignment::<Aligned>() };
597                Ok(ptr.as_ref())
598            }
599            Err(err) => Err(err.map_src(Ptr::as_ref)),
600        }
601    }
602}
603
604pub trait TryTransmuteMutDst<'a> {
605    type Dst: ?Sized;
606
607    /// See `try_transmute_mut!` documentation.
608    fn try_transmute_mut(
609        self,
610    ) -> Result<&'a mut Self::Dst, ValidityError<&'a mut Self::Src, Self::Dst>>
611    where
612        Self: TryTransmuteMutSrc<'a>,
613        Self::Src: IntoBytes,
614        Self::Dst: TryFromBytes;
615}
616
617pub trait TryTransmuteMutSrc<'a> {
618    type Src: ?Sized;
619}
620
621impl<'a, Src, Dst> TryTransmuteMutSrc<'a> for Wrap<&'a mut Src, &'a mut Dst>
622where
623    Src: ?Sized,
624    Dst: ?Sized,
625{
626    type Src = Src;
627}
628
629impl<'a, Src, Dst> TryTransmuteMutDst<'a> for Wrap<&'a mut Src, &'a mut Dst>
630where
631    Src: FromBytes + IntoBytes + KnownLayout + ?Sized,
632    Dst: TryFromBytes + IntoBytes + KnownLayout + ?Sized,
633{
634    type Dst = Dst;
635
636    #[inline(always)]
637    fn try_transmute_mut(
638        self,
639    ) -> Result<
640        &'a mut Dst,
641        ValidityError<&'a mut <Wrap<&'a mut Src, &'a mut Dst> as TryTransmuteMutSrc<'a>>::Src, Dst>,
642    > {
643        let ptr = Ptr::from_mut(self.0);
644        // SAFETY: The provided closure returns the only copy of `ptr`.
645        #[rustfmt::skip]
646        let res = unsafe {
647            ptr.try_with_unchecked(#[inline(always)] |ptr| {
648                let ptr = ptr.recall_validity::<Initialized, (_, (_, _))>();
649                let ptr = ptr.cast::<_, crate::layout::CastFrom<Dst>, _>();
650                ptr.try_into_valid()
651            })
652        };
653        match res {
654            Ok(ptr) => {
655                static_assert!(Src: ?Sized + KnownLayout, Dst: ?Sized + KnownLayout => {
656                    Src::LAYOUT.align.get() >= Dst::LAYOUT.align.get()
657                }, "cannot transmute reference when destination type has higher alignment than source type");
658                // SAFETY: We have checked that `Dst` does not have a stricter
659                // alignment requirement than `Src`.
660                let ptr = unsafe { ptr.assume_alignment::<Aligned>() };
661                Ok(ptr.as_mut())
662            }
663            Err(err) => Err(err.map_src(Ptr::as_mut)),
664        }
665    }
666}
667
668// Used in `transmute_ref!` and friends.
669//
670// This permits us to use the autoref specialization trick to dispatch to
671// associated functions for `transmute_ref` and `transmute_mut` when both `Src`
672// and `Dst` are `Sized`, and to trait methods otherwise. The associated
673// functions, unlike the trait methods, do not require a `KnownLayout` bound.
674// This permits us to add support for transmuting references to unsized types
675// without breaking backwards-compatibility (on v0.8.x) with the old
676// implementation, which did not require a `KnownLayout` bound to transmute
677// sized types.
678#[derive(Copy, Clone)]
679pub struct Wrap<Src, Dst>(pub Src, pub PhantomData<Dst>);
680
681impl<Src, Dst> Wrap<Src, Dst> {
682    #[inline(always)]
683    pub const fn new(src: Src) -> Self {
684        Wrap(src, PhantomData)
685    }
686}
687
688impl<'a, Src, Dst> Wrap<&'a Src, &'a Dst>
689where
690    Src: ?Sized,
691    Dst: ?Sized,
692{
693    #[allow(clippy::must_use_candidate, clippy::missing_inline_in_public_items, clippy::empty_loop)]
694    pub const fn transmute_ref_inference_helper(self) -> &'a Dst {
695        loop {}
696    }
697}
698
699impl<'a, Src, Dst> Wrap<&'a Src, &'a Dst> {
700    /// # Safety
701    /// The caller must guarantee that:
702    /// - `Src: IntoBytes + Immutable`
703    /// - `Dst: FromBytes + Immutable`
704    ///
705    /// # PME
706    ///
707    /// Instantiating this method PMEs unless both:
708    /// - `mem::size_of::<Dst>() == mem::size_of::<Src>()`
709    /// - `mem::align_of::<Dst>() <= mem::align_of::<Src>()`
710    #[inline(always)]
711    #[must_use]
712    pub const unsafe fn transmute_ref(self) -> &'a Dst {
713        static_assert!(Src, Dst => mem::size_of::<Dst>() == mem::size_of::<Src>());
714        static_assert!(Src, Dst => mem::align_of::<Dst>() <= mem::align_of::<Src>());
715
716        let src: *const Src = self.0;
717        let dst = src.cast::<Dst>();
718        // SAFETY:
719        // - We know that it is sound to view the target type of the input
720        //   reference (`Src`) as the target type of the output reference
721        //   (`Dst`) because the caller has guaranteed that `Src: IntoBytes`,
722        //   `Dst: FromBytes`, and `size_of::<Src>() == size_of::<Dst>()`.
723        // - We know that there are no `UnsafeCell`s, and thus we don't have to
724        //   worry about `UnsafeCell` overlap, because `Src: Immutable` and
725        //   `Dst: Immutable`.
726        // - The caller has guaranteed that alignment is not increased.
727        // - We know that the returned lifetime will not outlive the input
728        //   lifetime thanks to the lifetime bounds on this function.
729        //
730        // FIXME(#67): Once our MSRV is 1.58, replace this `transmute` with
731        // `&*dst`.
732        #[allow(clippy::transmute_ptr_to_ref)]
733        unsafe {
734            mem::transmute(dst)
735        }
736    }
737
738    #[inline(always)]
739    pub fn try_transmute_ref(self) -> Result<&'a Dst, ValidityError<&'a Src, Dst>>
740    where
741        Src: IntoBytes + Immutable,
742        Dst: TryFromBytes + Immutable,
743    {
744        static_assert!(Src => mem::align_of::<Src>() == mem::align_of::<Wrapping<Src>>());
745        static_assert!(Dst => mem::align_of::<Dst>() == mem::align_of::<Wrapping<Dst>>());
746
747        // SAFETY: By the preceding assert, `Src` and `Wrapping<Src>` have the
748        // same alignment.
749        let src: &Wrapping<Src> =
750            unsafe { crate::util::transmute_ref::<_, _, BecauseImmutable>(self.0) };
751        let src = Wrap::new(src);
752        <Wrap<&'a Wrapping<Src>, &'a Wrapping<Dst>> as TryTransmuteRefDst<'a>>::try_transmute_ref(
753            src,
754        )
755        // SAFETY: By the preceding assert, `Dst` and `Wrapping<Dst>` have the
756        // same alignment.
757        .map(|dst| unsafe { crate::util::transmute_ref::<_, _, BecauseImmutable>(dst) })
758        .map_err(|err| {
759            // SAFETY: By the preceding assert, `Src` and `Wrapping<Src>` have the
760            // same alignment.
761            ValidityError::new(unsafe {
762                crate::util::transmute_ref::<_, _, BecauseImmutable>(err.into_src())
763            })
764        })
765    }
766}
767
768impl<'a, Src, Dst> Wrap<&'a mut Src, &'a mut Dst>
769where
770    Src: ?Sized,
771    Dst: ?Sized,
772{
773    #[allow(clippy::must_use_candidate, clippy::missing_inline_in_public_items, clippy::empty_loop)]
774    pub fn transmute_mut_inference_helper(self) -> &'a mut Dst {
775        loop {}
776    }
777}
778
779impl<'a, Src, Dst> Wrap<&'a mut Src, &'a mut Dst> {
780    /// Transmutes a mutable reference of one type to a mutable reference of
781    /// another type.
782    ///
783    /// # PME
784    ///
785    /// Instantiating this method PMEs unless both:
786    /// - `mem::size_of::<Dst>() == mem::size_of::<Src>()`
787    /// - `mem::align_of::<Dst>() <= mem::align_of::<Src>()`
788    #[inline(always)]
789    #[must_use]
790    pub fn transmute_mut(self) -> &'a mut Dst
791    where
792        Src: FromBytes + IntoBytes,
793        Dst: FromBytes + IntoBytes,
794    {
795        static_assert!(Src, Dst => mem::size_of::<Dst>() == mem::size_of::<Src>());
796        static_assert!(Src, Dst => mem::align_of::<Dst>() <= mem::align_of::<Src>());
797
798        let src: *mut Src = self.0;
799        let dst = src.cast::<Dst>();
800        // SAFETY:
801        // - We know that it is sound to view the target type of the input
802        //   reference (`Src`) as the target type of the output reference
803        //   (`Dst`) and vice-versa because `Src: FromBytes + IntoBytes`, `Dst:
804        //   FromBytes + IntoBytes`, and (as asserted above) `size_of::<Src>()
805        //   == size_of::<Dst>()`.
806        // - We asserted above that alignment will not increase.
807        // - We know that the returned lifetime will not outlive the input
808        //   lifetime thanks to the lifetime bounds on this function.
809        unsafe { &mut *dst }
810    }
811
812    #[inline(always)]
813    pub fn try_transmute_mut(self) -> Result<&'a mut Dst, ValidityError<&'a mut Src, Dst>>
814    where
815        Src: FromBytes + IntoBytes,
816        Dst: TryFromBytes + IntoBytes,
817    {
818        static_assert!(Src => mem::align_of::<Src>() == mem::align_of::<Wrapping<Src>>());
819        static_assert!(Dst => mem::align_of::<Dst>() == mem::align_of::<Wrapping<Dst>>());
820
821        // SAFETY: By the preceding assert, `Src` and `Wrapping<Src>` have the
822        // same alignment.
823        let src: &mut Wrapping<Src> =
824            unsafe { crate::util::transmute_mut::<_, _, (_, (_, _))>(self.0) };
825        let src = Wrap::new(src);
826        <Wrap<&'a mut Wrapping<Src>, &'a mut Wrapping<Dst>> as TryTransmuteMutDst<'a>>
827            ::try_transmute_mut(src)
828            // SAFETY: By the preceding assert, `Dst` and `Wrapping<Dst>` have the
829            // same alignment.
830            .map(|dst| unsafe { crate::util::transmute_mut::<_, _, (_, (_, _))>(dst) })
831            .map_err(|err| {
832                // SAFETY: By the preceding assert, `Src` and `Wrapping<Src>` have the
833                // same alignment.
834                ValidityError::new(unsafe {
835                    crate::util::transmute_mut::<_, _, (_, (_, _))>(err.into_src())
836                })
837            })
838    }
839}
840
841pub trait TransmuteRefDst<'a> {
842    type Dst: ?Sized;
843
844    #[must_use]
845    fn transmute_ref(self) -> &'a Self::Dst;
846}
847
848impl<'a, Src: ?Sized, Dst: ?Sized> TransmuteRefDst<'a> for Wrap<&'a Src, &'a Dst>
849where
850    Src: KnownLayout + IntoBytes + Immutable,
851    Dst: KnownLayout<PointerMetadata = usize> + FromBytes + Immutable,
852{
853    type Dst = Dst;
854
855    #[inline(always)]
856    fn transmute_ref(self) -> &'a Dst {
857        let ptr = Ptr::from_ref(self.0)
858            .recall_validity::<Initialized, _>()
859            .transmute_with::<Dst, Initialized, crate::layout::CastFrom<Dst>, (crate::pointer::BecauseMutationCompatible, _)>()
860            .recall_validity::<Valid, _>();
861
862        static_assert!(Src: ?Sized + KnownLayout, Dst: ?Sized + KnownLayout => {
863            Src::LAYOUT.align.get() >= Dst::LAYOUT.align.get()
864        }, "cannot transmute reference when destination type has higher alignment than source type");
865
866        // SAFETY: The preceding `static_assert!` ensures that
867        // `Src::LAYOUT.align >= Dst::LAYOUT.align`. Since `self` is
868        // validly-aligned for `Src`, it is also validly-aligned for `Dst`.
869        let ptr = unsafe { ptr.assume_alignment() };
870
871        ptr.as_ref()
872    }
873}
874
875pub trait TransmuteMutDst<'a> {
876    type Dst: ?Sized;
877    #[must_use]
878    fn transmute_mut(self) -> &'a mut Self::Dst;
879}
880
881impl<'a, Src: ?Sized, Dst: ?Sized> TransmuteMutDst<'a> for Wrap<&'a mut Src, &'a mut Dst>
882where
883    Src: KnownLayout + FromBytes + IntoBytes,
884    Dst: KnownLayout<PointerMetadata = usize> + FromBytes + IntoBytes,
885{
886    type Dst = Dst;
887
888    #[inline(always)]
889    fn transmute_mut(self) -> &'a mut Dst {
890        let ptr = Ptr::from_mut(self.0)
891            .recall_validity::<Initialized, (_, (_, _))>()
892            .transmute_with::<Dst, Initialized, crate::layout::CastFrom<Dst>, _>()
893            .recall_validity::<Valid, (_, (_, _))>();
894
895        static_assert!(Src: ?Sized + KnownLayout, Dst: ?Sized + KnownLayout => {
896            Src::LAYOUT.align.get() >= Dst::LAYOUT.align.get()
897        }, "cannot transmute reference when destination type has higher alignment than source type");
898
899        // SAFETY: The preceding `static_assert!` ensures that
900        // `Src::LAYOUT.align >= Dst::LAYOUT.align`. Since `self` is
901        // validly-aligned for `Src`, it is also validly-aligned for `Dst`.
902        let ptr = unsafe { ptr.assume_alignment() };
903
904        ptr.as_mut()
905    }
906}
907
908/// A function which emits a warning if its return value is not used.
909#[must_use]
910#[inline(always)]
911pub const fn must_use<T>(t: T) -> T {
912    t
913}
914
915// NOTE: We can't change this to a `pub use core as core_reexport` until [1] is
916// fixed or we update to a semver-breaking version (as of this writing, 0.8.0)
917// on the `main` branch.
918//
919// [1] https://github.com/obi1kenobi/cargo-semver-checks/issues/573
920pub mod core_reexport {
921    pub use core::*;
922
923    pub mod mem {
924        pub use core::mem::*;
925    }
926}
927
928#[cfg(test)]
929mod tests {
930    use crate::util::testutil::*;
931
932    #[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
933    mod nightly {
934        use super::super::*;
935        use crate::util::testutil::*;
936
937        // FIXME(#29), FIXME(https://github.com/rust-lang/rust/issues/69835):
938        // Remove this `cfg` when `size_of_val_raw` is stabilized.
939        #[allow(clippy::decimal_literal_representation)]
940        #[test]
941        fn test_trailing_field_offset() {
942            assert_eq!(mem::align_of::<Aligned64kAllocation>(), _64K);
943
944            macro_rules! test {
945                (#[$cfg:meta] ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {{
946                    #[$cfg]
947                    struct Test($(#[allow(dead_code)] $ts,)* #[allow(dead_code)] $trailing_field_ty);
948                    assert_eq!(test!(@offset $($ts),* ; $trailing_field_ty), $expect);
949                }};
950                (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {
951                    test!(#[$cfg] ($($ts),* ; $trailing_field_ty) => $expect);
952                    test!($(#[$cfgs])* ($($ts),* ; $trailing_field_ty) => $expect);
953                };
954                (@offset ; $_trailing:ty) => { trailing_field_offset!(Test, 0) };
955                (@offset $_t:ty ; $_trailing:ty) => { trailing_field_offset!(Test, 1) };
956            }
957
958            test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; u8) => Some(0));
959            test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; [u8]) => Some(0));
960            test!(#[repr(C)] #[repr(C, packed)] (u8; u8) => Some(1));
961            test!(#[repr(C)] (; AU64) => Some(0));
962            test!(#[repr(C)] (; [AU64]) => Some(0));
963            test!(#[repr(C)] (u8; AU64) => Some(8));
964            test!(#[repr(C)] (u8; [AU64]) => Some(8));
965
966            #[derive(
967                Immutable, FromBytes, Eq, PartialEq, Ord, PartialOrd, Default, Debug, Copy, Clone,
968            )]
969            #[repr(C)]
970            pub(crate) struct Nested<T, U: ?Sized> {
971                _t: T,
972                _u: U,
973            }
974
975            test!(#[repr(C)] (; Nested<u8, AU64>) => Some(0));
976            test!(#[repr(C)] (; Nested<u8, [AU64]>) => Some(0));
977            test!(#[repr(C)] (u8; Nested<u8, AU64>) => Some(8));
978            test!(#[repr(C)] (u8; Nested<u8, [AU64]>) => Some(8));
979
980            // Test that `packed(N)` limits the offset of the trailing field.
981            test!(#[repr(C, packed(        1))] (u8; elain::Align<        2>) => Some(        1));
982            test!(#[repr(C, packed(        2))] (u8; elain::Align<        4>) => Some(        2));
983            test!(#[repr(C, packed(        4))] (u8; elain::Align<        8>) => Some(        4));
984            test!(#[repr(C, packed(        8))] (u8; elain::Align<       16>) => Some(        8));
985            test!(#[repr(C, packed(       16))] (u8; elain::Align<       32>) => Some(       16));
986            test!(#[repr(C, packed(       32))] (u8; elain::Align<       64>) => Some(       32));
987            test!(#[repr(C, packed(       64))] (u8; elain::Align<      128>) => Some(       64));
988            test!(#[repr(C, packed(      128))] (u8; elain::Align<      256>) => Some(      128));
989            test!(#[repr(C, packed(      256))] (u8; elain::Align<      512>) => Some(      256));
990            test!(#[repr(C, packed(      512))] (u8; elain::Align<     1024>) => Some(      512));
991            test!(#[repr(C, packed(     1024))] (u8; elain::Align<     2048>) => Some(     1024));
992            test!(#[repr(C, packed(     2048))] (u8; elain::Align<     4096>) => Some(     2048));
993            test!(#[repr(C, packed(     4096))] (u8; elain::Align<     8192>) => Some(     4096));
994            test!(#[repr(C, packed(     8192))] (u8; elain::Align<    16384>) => Some(     8192));
995            test!(#[repr(C, packed(    16384))] (u8; elain::Align<    32768>) => Some(    16384));
996            test!(#[repr(C, packed(    32768))] (u8; elain::Align<    65536>) => Some(    32768));
997            test!(#[repr(C, packed(    65536))] (u8; elain::Align<   131072>) => Some(    65536));
998            /* Alignments above 65536 are not yet supported.
999            test!(#[repr(C, packed(   131072))] (u8; elain::Align<   262144>) => Some(   131072));
1000            test!(#[repr(C, packed(   262144))] (u8; elain::Align<   524288>) => Some(   262144));
1001            test!(#[repr(C, packed(   524288))] (u8; elain::Align<  1048576>) => Some(   524288));
1002            test!(#[repr(C, packed(  1048576))] (u8; elain::Align<  2097152>) => Some(  1048576));
1003            test!(#[repr(C, packed(  2097152))] (u8; elain::Align<  4194304>) => Some(  2097152));
1004            test!(#[repr(C, packed(  4194304))] (u8; elain::Align<  8388608>) => Some(  4194304));
1005            test!(#[repr(C, packed(  8388608))] (u8; elain::Align< 16777216>) => Some(  8388608));
1006            test!(#[repr(C, packed( 16777216))] (u8; elain::Align< 33554432>) => Some( 16777216));
1007            test!(#[repr(C, packed( 33554432))] (u8; elain::Align< 67108864>) => Some( 33554432));
1008            test!(#[repr(C, packed( 67108864))] (u8; elain::Align< 33554432>) => Some( 67108864));
1009            test!(#[repr(C, packed( 33554432))] (u8; elain::Align<134217728>) => Some( 33554432));
1010            test!(#[repr(C, packed(134217728))] (u8; elain::Align<268435456>) => Some(134217728));
1011            test!(#[repr(C, packed(268435456))] (u8; elain::Align<268435456>) => Some(268435456));
1012            */
1013
1014            // Test that `align(N)` does not limit the offset of the trailing field.
1015            test!(#[repr(C, align(        1))] (u8; elain::Align<        2>) => Some(        2));
1016            test!(#[repr(C, align(        2))] (u8; elain::Align<        4>) => Some(        4));
1017            test!(#[repr(C, align(        4))] (u8; elain::Align<        8>) => Some(        8));
1018            test!(#[repr(C, align(        8))] (u8; elain::Align<       16>) => Some(       16));
1019            test!(#[repr(C, align(       16))] (u8; elain::Align<       32>) => Some(       32));
1020            test!(#[repr(C, align(       32))] (u8; elain::Align<       64>) => Some(       64));
1021            test!(#[repr(C, align(       64))] (u8; elain::Align<      128>) => Some(      128));
1022            test!(#[repr(C, align(      128))] (u8; elain::Align<      256>) => Some(      256));
1023            test!(#[repr(C, align(      256))] (u8; elain::Align<      512>) => Some(      512));
1024            test!(#[repr(C, align(      512))] (u8; elain::Align<     1024>) => Some(     1024));
1025            test!(#[repr(C, align(     1024))] (u8; elain::Align<     2048>) => Some(     2048));
1026            test!(#[repr(C, align(     2048))] (u8; elain::Align<     4096>) => Some(     4096));
1027            test!(#[repr(C, align(     4096))] (u8; elain::Align<     8192>) => Some(     8192));
1028            test!(#[repr(C, align(     8192))] (u8; elain::Align<    16384>) => Some(    16384));
1029            test!(#[repr(C, align(    16384))] (u8; elain::Align<    32768>) => Some(    32768));
1030            test!(#[repr(C, align(    32768))] (u8; elain::Align<    65536>) => Some(    65536));
1031            /* Alignments above 65536 are not yet supported.
1032            test!(#[repr(C, align(    65536))] (u8; elain::Align<   131072>) => Some(   131072));
1033            test!(#[repr(C, align(   131072))] (u8; elain::Align<   262144>) => Some(   262144));
1034            test!(#[repr(C, align(   262144))] (u8; elain::Align<   524288>) => Some(   524288));
1035            test!(#[repr(C, align(   524288))] (u8; elain::Align<  1048576>) => Some(  1048576));
1036            test!(#[repr(C, align(  1048576))] (u8; elain::Align<  2097152>) => Some(  2097152));
1037            test!(#[repr(C, align(  2097152))] (u8; elain::Align<  4194304>) => Some(  4194304));
1038            test!(#[repr(C, align(  4194304))] (u8; elain::Align<  8388608>) => Some(  8388608));
1039            test!(#[repr(C, align(  8388608))] (u8; elain::Align< 16777216>) => Some( 16777216));
1040            test!(#[repr(C, align( 16777216))] (u8; elain::Align< 33554432>) => Some( 33554432));
1041            test!(#[repr(C, align( 33554432))] (u8; elain::Align< 67108864>) => Some( 67108864));
1042            test!(#[repr(C, align( 67108864))] (u8; elain::Align< 33554432>) => Some( 33554432));
1043            test!(#[repr(C, align( 33554432))] (u8; elain::Align<134217728>) => Some(134217728));
1044            test!(#[repr(C, align(134217728))] (u8; elain::Align<268435456>) => Some(268435456));
1045            */
1046        }
1047
1048        // FIXME(#29), FIXME(https://github.com/rust-lang/rust/issues/69835):
1049        // Remove this `cfg` when `size_of_val_raw` is stabilized.
1050        #[allow(clippy::decimal_literal_representation)]
1051        #[test]
1052        fn test_align_of_dst() {
1053            // Test that `align_of!` correctly computes the alignment of DSTs.
1054            assert_eq!(align_of!([elain::Align<1>]), Some(1));
1055            assert_eq!(align_of!([elain::Align<2>]), Some(2));
1056            assert_eq!(align_of!([elain::Align<4>]), Some(4));
1057            assert_eq!(align_of!([elain::Align<8>]), Some(8));
1058            assert_eq!(align_of!([elain::Align<16>]), Some(16));
1059            assert_eq!(align_of!([elain::Align<32>]), Some(32));
1060            assert_eq!(align_of!([elain::Align<64>]), Some(64));
1061            assert_eq!(align_of!([elain::Align<128>]), Some(128));
1062            assert_eq!(align_of!([elain::Align<256>]), Some(256));
1063            assert_eq!(align_of!([elain::Align<512>]), Some(512));
1064            assert_eq!(align_of!([elain::Align<1024>]), Some(1024));
1065            assert_eq!(align_of!([elain::Align<2048>]), Some(2048));
1066            assert_eq!(align_of!([elain::Align<4096>]), Some(4096));
1067            assert_eq!(align_of!([elain::Align<8192>]), Some(8192));
1068            assert_eq!(align_of!([elain::Align<16384>]), Some(16384));
1069            assert_eq!(align_of!([elain::Align<32768>]), Some(32768));
1070            assert_eq!(align_of!([elain::Align<65536>]), Some(65536));
1071            /* Alignments above 65536 are not yet supported.
1072            assert_eq!(align_of!([elain::Align<131072>]), Some(131072));
1073            assert_eq!(align_of!([elain::Align<262144>]), Some(262144));
1074            assert_eq!(align_of!([elain::Align<524288>]), Some(524288));
1075            assert_eq!(align_of!([elain::Align<1048576>]), Some(1048576));
1076            assert_eq!(align_of!([elain::Align<2097152>]), Some(2097152));
1077            assert_eq!(align_of!([elain::Align<4194304>]), Some(4194304));
1078            assert_eq!(align_of!([elain::Align<8388608>]), Some(8388608));
1079            assert_eq!(align_of!([elain::Align<16777216>]), Some(16777216));
1080            assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432));
1081            assert_eq!(align_of!([elain::Align<67108864>]), Some(67108864));
1082            assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432));
1083            assert_eq!(align_of!([elain::Align<134217728>]), Some(134217728));
1084            assert_eq!(align_of!([elain::Align<268435456>]), Some(268435456));
1085            */
1086        }
1087    }
1088
1089    #[test]
1090    fn test_enum_casts() {
1091        // Test that casting the variants of enums with signed integer reprs to
1092        // unsigned integers obeys expected signed -> unsigned casting rules.
1093
1094        #[repr(i8)]
1095        enum ReprI8 {
1096            MinusOne = -1,
1097            Zero = 0,
1098            Min = i8::MIN,
1099            Max = i8::MAX,
1100        }
1101
1102        #[allow(clippy::as_conversions)]
1103        let x = ReprI8::MinusOne as u8;
1104        assert_eq!(x, u8::MAX);
1105
1106        #[allow(clippy::as_conversions)]
1107        let x = ReprI8::Zero as u8;
1108        assert_eq!(x, 0);
1109
1110        #[allow(clippy::as_conversions)]
1111        let x = ReprI8::Min as u8;
1112        assert_eq!(x, 128);
1113
1114        #[allow(clippy::as_conversions)]
1115        let x = ReprI8::Max as u8;
1116        assert_eq!(x, 127);
1117    }
1118
1119    #[test]
1120    fn test_struct_padding() {
1121        // Test that, for each provided repr, `struct_padding!` reports the
1122        // expected value.
1123        macro_rules! test {
1124            (#[$cfg:meta] ($($ts:ty),*) => $expect:expr) => {{
1125                #[$cfg]
1126                #[allow(dead_code)]
1127                struct Test($($ts),*);
1128                assert_eq!(struct_padding!(Test, [$($ts),*]), $expect);
1129            }};
1130            (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),*) => $expect:expr) => {
1131                test!(#[$cfg] ($($ts),*) => $expect);
1132                test!($(#[$cfgs])* ($($ts),*) => $expect);
1133            };
1134        }
1135
1136        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] () => 0);
1137        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8) => 0);
1138        test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8, ()) => 0);
1139        test!(#[repr(C)] #[repr(packed)] (u8, u8) => 0);
1140
1141        test!(#[repr(C)] (u8, AU64) => 7);
1142        // Rust won't let you put `#[repr(packed)]` on a type which contains a
1143        // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here.
1144        // It's not ideal, but it definitely has align > 1 on /some/ of our CI
1145        // targets, and this isn't a particularly complex macro we're testing
1146        // anyway.
1147        test!(#[repr(packed)] (u8, u64) => 0);
1148    }
1149
1150    #[test]
1151    fn test_repr_c_struct_padding() {
1152        // Test that, for each provided repr, `repr_c_struct_padding!` reports
1153        // the expected value.
1154        macro_rules! test {
1155            (($($ts:tt),*) => $expect:expr) => {{
1156                #[repr(C)]
1157                #[allow(dead_code)]
1158                struct Test($($ts),*);
1159                assert_eq!(repr_c_struct_has_padding!(Test, [$($ts),*]), $expect);
1160            }};
1161        }
1162
1163        // Test static padding
1164        test!(() => false);
1165        test!(([u8]) => false);
1166        test!((u8) => false);
1167        test!((u8, [u8]) => false);
1168        test!((u8, ()) => false);
1169        test!((u8, (), [u8]) => false);
1170        test!((u8, u8) => false);
1171        test!((u8, u8, [u8]) => false);
1172
1173        test!((u8, AU64) => true);
1174        test!((u8, AU64, [u8]) => true);
1175
1176        // Test dynamic padding
1177        test!((AU64, [AU64]) => false);
1178        test!((u8, [AU64]) => true);
1179
1180        #[repr(align(4))]
1181        struct AU32(#[allow(unused)] u32);
1182        test!((AU64, [AU64]) => false);
1183        test!((AU64, [AU32]) => true);
1184    }
1185
1186    #[test]
1187    fn test_union_padding() {
1188        // Test that, for each provided repr, `union_padding!` reports the
1189        // expected value.
1190        macro_rules! test {
1191            (#[$cfg:meta] {$($fs:ident: $ts:ty),*} => $expect:expr) => {{
1192                #[$cfg]
1193                #[allow(unused)] // fields are never read
1194                union Test{ $($fs: $ts),* }
1195                assert_eq!(union_padding!(Test, [$($ts),*]), $expect);
1196            }};
1197            (#[$cfg:meta] $(#[$cfgs:meta])* {$($fs:ident: $ts:ty),*} => $expect:expr) => {
1198                test!(#[$cfg] {$($fs: $ts),*} => $expect);
1199                test!($(#[$cfgs])* {$($fs: $ts),*} => $expect);
1200            };
1201        }
1202
1203        test!(#[repr(C)] #[repr(packed)] {a: u8} => 0);
1204        test!(#[repr(C)] #[repr(packed)] {a: u8, b: u8} => 0);
1205
1206        // Rust won't let you put `#[repr(packed)]` on a type which contains a
1207        // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here.
1208        // It's not ideal, but it definitely has align > 1 on /some/ of our CI
1209        // targets, and this isn't a particularly complex macro we're testing
1210        // anyway.
1211        test!(#[repr(C)] #[repr(packed)] {a: u8, b: u64} => 7);
1212    }
1213
1214    #[test]
1215    fn test_enum_padding() {
1216        // Test that, for each provided repr, `enum_has_padding!` reports the
1217        // expected value.
1218        macro_rules! test {
1219            (#[repr($disc:ident $(, $c:ident)?)] { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {
1220                test!(@case #[repr($disc $(, $c)?)] { $($vs ($($ts),*),)* } => $expect);
1221            };
1222            (#[repr($disc:ident $(, $c:ident)?)] #[$cfg:meta] $(#[$cfgs:meta])* { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {
1223                test!(@case #[repr($disc $(, $c)?)] #[$cfg] { $($vs ($($ts),*),)* } => $expect);
1224                test!(#[repr($disc $(, $c)?)] $(#[$cfgs])* { $($vs ($($ts),*),)* } => $expect);
1225            };
1226            (@case #[repr($disc:ident $(, $c:ident)?)] $(#[$cfg:meta])? { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {{
1227                #[repr($disc $(, $c)?)]
1228                $(#[$cfg])?
1229                #[allow(unused)] // variants and fields are never used
1230                enum Test {
1231                    $($vs ($($ts),*),)*
1232                }
1233                assert_eq!(
1234                    enum_padding!(Test, $disc, $([$($ts),*]),*),
1235                    $expect
1236                );
1237            }};
1238        }
1239
1240        #[allow(unused)]
1241        #[repr(align(2))]
1242        struct U16(u16);
1243
1244        #[allow(unused)]
1245        #[repr(align(4))]
1246        struct U32(u32);
1247
1248        test!(#[repr(u8)] #[repr(C)] {
1249            A(u8),
1250        } => 0);
1251        test!(#[repr(u16)] #[repr(C)] {
1252            A(u8, u8),
1253            B(U16),
1254        } => 0);
1255        test!(#[repr(u32)] #[repr(C)] {
1256            A(u8, u8, u8, u8),
1257            B(U16, u8, u8),
1258            C(u8, u8, U16),
1259            D(U16, U16),
1260            E(U32),
1261        } => 0);
1262
1263        // `repr(int)` can pack the discriminant more efficiently
1264        test!(#[repr(u8)] {
1265            A(u8, U16),
1266        } => 0);
1267        test!(#[repr(u8)] {
1268            A(u8, U16, U32),
1269        } => 0);
1270
1271        // `repr(C)` cannot
1272        test!(#[repr(u8, C)] {
1273            A(u8, U16),
1274        } => 2);
1275        test!(#[repr(u8, C)] {
1276            A(u8, u8, u8, U32),
1277        } => 4);
1278
1279        // And field ordering can always cause problems
1280        test!(#[repr(u8)] #[repr(C)] {
1281            A(U16, u8),
1282        } => 2);
1283        test!(#[repr(u8)] #[repr(C)] {
1284            A(U32, u8, u8, u8),
1285        } => 4);
1286    }
1287}