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