Skip to main content

zerocopy/util/
macros.rs

1// Copyright 2023 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/// Unsafely implements trait(s) for a type.
10///
11/// # Safety
12///
13/// The trait impl must be sound.
14///
15/// When implementing `TryFromBytes`:
16/// - If no `is_bit_valid` impl is provided, then it must be valid for
17///   `is_bit_valid` to unconditionally return `true`. In other words, it must
18///   be the case that any initialized sequence of bytes constitutes a valid
19///   instance of `$ty`.
20/// - If an `is_bit_valid` impl is provided, then the impl of `is_bit_valid`
21///   must only return `true` if its argument refers to a valid `$ty`.
22macro_rules! unsafe_impl {
23    // Implement `$trait` for `$ty` with no bounds.
24    ($(#[$attr:meta])* $ty:ty: $trait:ident $(; |$candidate:ident| $is_bit_valid:expr)?) => {{
25        crate::util::macros::__unsafe();
26
27        $(#[$attr])*
28        // SAFETY: The caller promises that this is sound.
29        unsafe impl $trait for $ty {
30            unsafe_impl!(@method $trait $(; |$candidate| $is_bit_valid)?);
31        }
32    }};
33
34    // Implement all `$traits` for `$ty` with no bounds.
35    //
36    // The 2 arms under this one are there so we can apply
37    // N attributes for each one of M trait implementations.
38    // The simple solution of:
39    //
40    // ($(#[$attrs:meta])* $ty:ty: $($traits:ident),*) => {
41    //     $( unsafe_impl!( $(#[$attrs])* $ty: $traits ) );*
42    // }
43    //
44    // Won't work. The macro processor sees that the outer repetition
45    // contains both $attrs and $traits and expects them to match the same
46    // amount of fragments.
47    //
48    // To solve this we must:
49    // 1. Pack the attributes into a single token tree fragment we can match over.
50    // 2. Expand the traits.
51    // 3. Unpack and expand the attributes.
52    ($(#[$attrs:meta])* $ty:ty: $($traits:ident),*) => {
53        unsafe_impl!(@impl_traits_with_packed_attrs { $(#[$attrs])* } $ty: $($traits),*)
54    };
55
56    (@impl_traits_with_packed_attrs $attrs:tt $ty:ty: $($traits:ident),*) => {{
57        $( unsafe_impl!(@unpack_attrs $attrs $ty: $traits); )*
58    }};
59
60    (@unpack_attrs { $(#[$attrs:meta])* } $ty:ty: $traits:ident) => {
61        unsafe_impl!($(#[$attrs])* $ty: $traits);
62    };
63
64    // This arm is identical to the following one, except it contains a
65    // preceding `const`. If we attempt to handle these with a single arm, there
66    // is an inherent ambiguity between `const` (the keyword) and `const` (the
67    // ident match for `$tyvar:ident`).
68    //
69    // To explain how this works, consider the following invocation:
70    //
71    //   unsafe_impl!(const N: usize, T: ?Sized + Copy => Clone for Foo<T>);
72    //
73    // In this invocation, here are the assignments to meta-variables:
74    //
75    //   |---------------|------------|
76    //   | Meta-variable | Assignment |
77    //   |---------------|------------|
78    //   | $constname    |  N         |
79    //   | $constty      |  usize     |
80    //   | $tyvar        |  T         |
81    //   | $optbound     |  Sized     |
82    //   | $bound        |  Copy      |
83    //   | $trait        |  Clone     |
84    //   | $ty           |  Foo<T>    |
85    //   |---------------|------------|
86    //
87    // The following arm has the same behavior with the exception of the lack of
88    // support for a leading `const` parameter.
89    (
90        $(#[$attr:meta])*
91        const $constname:ident : $constty:ident $(,)?
92        $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),*
93        => $trait:ident for $ty:ty $(; |$candidate:ident| $is_bit_valid:expr)?
94    ) => {
95        unsafe_impl!(
96            @inner
97            $(#[$attr])*
98            @const $constname: $constty,
99            $($tyvar $(: $(? $optbound +)* + $($bound +)*)?,)*
100            => $trait for $ty $(; |$candidate| $is_bit_valid)?
101        );
102    };
103    (
104        $(#[$attr:meta])*
105        $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),*
106        => $trait:ident for $ty:ty $(; |$candidate:ident| $is_bit_valid:expr)?
107    ) => {{
108        unsafe_impl!(
109            @inner
110            $(#[$attr])*
111            $($tyvar $(: $(? $optbound +)* + $($bound +)*)?,)*
112            => $trait for $ty $(; |$candidate| $is_bit_valid)?
113        );
114    }};
115    (
116        @inner
117        $(#[$attr:meta])*
118        $(@const $constname:ident : $constty:ident,)*
119        $($tyvar:ident $(: $(? $optbound:ident +)* + $($bound:ident +)* )?,)*
120        => $trait:ident for $ty:ty $(; |$candidate:ident| $is_bit_valid:expr)?
121    ) => {{
122        crate::util::macros::__unsafe();
123
124        $(#[$attr])*
125        #[allow(non_local_definitions)]
126        // SAFETY: The caller promises that this is sound.
127        unsafe impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),* $(, const $constname: $constty,)*> $trait for $ty {
128            unsafe_impl!(@method $trait $(; |$candidate| $is_bit_valid)?);
129        }
130    }};
131
132    (@method TryFromBytes ; |$candidate:ident| $is_bit_valid:expr) => {
133        #[allow(clippy::missing_inline_in_public_items, dead_code)]
134        #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
135        fn only_derive_is_allowed_to_implement_this_trait() {}
136
137        #[inline]
138        fn is_bit_valid<Alignment>($candidate: Maybe<'_, Self, Alignment>) -> bool
139        where
140            Alignment: crate::invariant::Alignment,
141        {
142            $is_bit_valid
143        }
144    };
145    (@method TryFromBytes) => {
146        #[allow(clippy::missing_inline_in_public_items)]
147        #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
148        fn only_derive_is_allowed_to_implement_this_trait() {}
149        #[inline(always)]
150        fn is_bit_valid<Alignment>(_candidate: Maybe<'_, Self, Alignment>) -> bool
151        where
152            Alignment: crate::invariant::Alignment,
153        {
154            true
155        }
156    };
157    (@method $trait:ident) => {
158        #[allow(clippy::missing_inline_in_public_items, dead_code)]
159        #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
160        fn only_derive_is_allowed_to_implement_this_trait() {}
161    };
162    (@method $trait:ident; |$_candidate:ident| $_is_bit_valid:expr) => {
163        compile_error!("Can't provide `is_bit_valid` impl for trait other than `TryFromBytes`");
164    };
165}
166
167/// Implements `$trait` for `$ty` where `$ty: TransmuteFrom<$repr>` (and
168/// vice-versa).
169///
170/// Calling this macro is safe; the internals of the macro emit appropriate
171/// trait bounds which ensure that the given impl is sound.
172macro_rules! impl_for_transmute_from {
173    (
174        $(#[$attr:meta])*
175        $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?)?
176        => $trait:ident for $ty:ty [$repr:ty]
177    ) => {
178        const _: () = {
179            $(#[$attr])*
180            #[allow(non_local_definitions)]
181
182            // SAFETY: `is_trait<T, R>` (defined and used below) requires `T:
183            // TransmuteFrom<R>`, `R: TransmuteFrom<T>`, and `R: $trait`. It is
184            // called using `$ty` and `$repr`, ensuring that `$ty` and `$repr`
185            // have equivalent bit validity, and ensuring that `$repr: $trait`.
186            // The supported traits - `TryFromBytes`, `FromZeros`, `FromBytes`,
187            // and `IntoBytes` - are defined only in terms of the bit validity
188            // of a type. Therefore, `$repr: $trait` ensures that `$ty: $trait`
189            // is sound.
190            unsafe impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?)?> $trait for $ty {
191                #[allow(dead_code, clippy::missing_inline_in_public_items)]
192                #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
193                fn only_derive_is_allowed_to_implement_this_trait() {
194                    use crate::pointer::{*, invariant::Valid};
195
196                    impl_for_transmute_from!(@assert_is_supported_trait $trait);
197
198                    fn is_trait<T, R>()
199                    where
200                        T: TransmuteFrom<R, Valid, Valid> + ?Sized,
201                        R: TransmuteFrom<T, Valid, Valid> + ?Sized,
202                        R: $trait,
203                    {
204                    }
205
206                    #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
207                    fn f<$($tyvar $(: $(? $optbound +)* $($bound +)*)?)?>() {
208                        is_trait::<$ty, $repr>();
209                    }
210                }
211
212                impl_for_transmute_from!(
213                    @is_bit_valid
214                    $(<$tyvar $(: $(? $optbound +)* $($bound +)*)?>)?
215                    $trait for $ty [$repr]
216                );
217            }
218        };
219    };
220    (@assert_is_supported_trait TryFromBytes) => {};
221    (@assert_is_supported_trait FromZeros) => {};
222    (@assert_is_supported_trait FromBytes) => {};
223    (@assert_is_supported_trait IntoBytes) => {};
224    (
225        @is_bit_valid
226        $(<$tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?>)?
227        TryFromBytes for $ty:ty [$repr:ty]
228    ) => {
229        #[inline(always)]
230        fn is_bit_valid<Alignment>(candidate: $crate::Maybe<'_, Self, Alignment>) -> bool
231        where
232            Alignment: $crate::invariant::Alignment,
233        {
234            // SAFETY: This macro ensures that `$repr` and `Self` have the same
235            // size and bit validity. Thus, a bit-valid instance of `$repr` is
236            // also a bit-valid instance of `Self`.
237            <$repr as TryFromBytes>::is_bit_valid(candidate.transmute::<_, _, BecauseImmutable>())
238        }
239    };
240    (
241        @is_bit_valid
242        $(<$tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?>)?
243        $trait:ident for $ty:ty [$repr:ty]
244    ) => {
245        // Trait other than `TryFromBytes`; no `is_bit_valid` impl.
246    };
247}
248
249/// Implements a trait for a type, bounding on each member of the power set of
250/// a set of type variables. This is useful for implementing traits for tuples
251/// or `fn` types.
252///
253/// The last argument is the name of a macro which will be called in every
254/// `impl` block, and is expected to expand to the name of the type for which to
255/// implement the trait.
256///
257/// For example, the invocation:
258/// ```ignore
259/// unsafe_impl_for_power_set!(A, B => Foo for type!(...))
260/// ```
261/// ...expands to:
262/// ```ignore
263/// unsafe impl       Foo for type!()     { ... }
264/// unsafe impl<B>    Foo for type!(B)    { ... }
265/// unsafe impl<A, B> Foo for type!(A, B) { ... }
266/// ```
267macro_rules! unsafe_impl_for_power_set {
268    (
269        $first:ident $(, $rest:ident)* $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)
270        $(; |$candidate:ident| $is_bit_valid:expr)?
271    ) => {
272        unsafe_impl_for_power_set!(
273            $($rest),* $(-> $ret)? => $trait for $macro!(...)
274            $(; |$candidate| $is_bit_valid)?
275        );
276        unsafe_impl_for_power_set!(
277            @impl $first $(, $rest)* $(-> $ret)? => $trait for $macro!(...)
278            $(; |$candidate| $is_bit_valid)?
279        );
280    };
281    (
282        $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)
283        $(; |$candidate:ident| $is_bit_valid:expr)?
284    ) => {
285        unsafe_impl_for_power_set!(
286            @impl $(-> $ret)? => $trait for $macro!(...)
287            $(; |$candidate| $is_bit_valid)?
288        );
289    };
290    (
291        @impl $($vars:ident),* $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)
292        $(; |$candidate:ident| $is_bit_valid:expr)?
293    ) => {
294        unsafe_impl!(
295            $($vars,)* $($ret)? => $trait for $macro!($($vars),* $(-> $ret)?)
296            $(; |$candidate| $is_bit_valid)?
297        );
298    };
299}
300
301/// Expands to an `Option<extern "C" fn>` type with the given argument types and
302/// return type. Designed for use with `unsafe_impl_for_power_set`.
303macro_rules! opt_extern_c_fn {
304    ($($args:ident),* -> $ret:ident) => { Option<extern "C" fn($($args),*) -> $ret> };
305}
306
307/// Expands to an `Option<unsafe extern "C" fn>` type with the given argument
308/// types and return type. Designed for use with `unsafe_impl_for_power_set`.
309macro_rules! opt_unsafe_extern_c_fn {
310    ($($args:ident),* -> $ret:ident) => { Option<unsafe extern "C" fn($($args),*) -> $ret> };
311}
312
313/// Expands to an `Option<fn>` type with the given argument types and return
314/// type. Designed for use with `unsafe_impl_for_power_set`.
315macro_rules! opt_fn {
316    ($($args:ident),* -> $ret:ident) => { Option<fn($($args),*) -> $ret> };
317}
318
319/// Expands to an `Option<unsafe fn>` type with the given argument types and
320/// return type. Designed for use with `unsafe_impl_for_power_set`.
321macro_rules! opt_unsafe_fn {
322    ($($args:ident),* -> $ret:ident) => { Option<unsafe fn($($args),*) -> $ret> };
323}
324
325// This `allow` is needed because, when testing, we export this macro so it can
326// be used in `doctests`.
327#[allow(rustdoc::private_intra_doc_links)]
328/// Implements trait(s) for a type or verifies the given implementation by
329/// referencing an existing (derived) implementation.
330///
331/// This macro exists so that we can provide zerocopy-derive as an optional
332/// dependency and still get the benefit of using its derives to validate that
333/// our trait impls are sound.
334///
335/// When compiling without `--cfg 'feature = "derive"` and without `--cfg test`,
336/// `impl_or_verify!` emits the provided trait impl. When compiling with either
337/// of those cfgs, it is expected that the type in question is deriving the
338/// traits instead. In this case, `impl_or_verify!` emits code which validates
339/// that the given trait impl is at least as restrictive as the the impl emitted
340/// by the custom derive. This has the effect of confirming that the impl which
341/// is emitted when the `derive` feature is disabled is actually sound (on the
342/// assumption that the impl emitted by the custom derive is sound).
343///
344/// The caller is still required to provide a safety comment (e.g. using the
345/// `const _: () = unsafe` macro). The reason for this restriction is that,
346/// while `impl_or_verify!` can guarantee that the provided impl is sound when
347/// it is compiled with the appropriate cfgs, there is no way to guarantee that
348/// it is ever compiled with those cfgs. In particular, it would be possible to
349/// accidentally place an `impl_or_verify!` call in a context that is only ever
350/// compiled when the `derive` feature is disabled. If that were to happen,
351/// there would be nothing to prevent an unsound trait impl from being emitted.
352/// Requiring a safety comment reduces the likelihood of emitting an unsound
353/// impl in this case, and also provides useful documentation for readers of the
354/// code.
355///
356/// Finally, if a `TryFromBytes::is_bit_valid` impl is provided, it must adhere
357/// to the safety preconditions of [`unsafe_impl!`].
358///
359/// ## Example
360///
361/// ```rust,ignore
362/// // Note that these derives are gated by `feature = "derive"`
363/// #[cfg_attr(any(feature = "derive", test), derive(FromZeros, FromBytes, IntoBytes, Unaligned))]
364/// #[repr(transparent)]
365/// struct Wrapper<T>(T);
366///
367/// const _: () = unsafe {
368///     /// SAFETY:
369///     /// `Wrapper<T>` is `repr(transparent)`, so it is sound to implement any
370///     /// zerocopy trait if `T` implements that trait.
371///     impl_or_verify!(T: FromZeros => FromZeros for Wrapper<T>);
372///     impl_or_verify!(T: FromBytes => FromBytes for Wrapper<T>);
373///     impl_or_verify!(T: IntoBytes => IntoBytes for Wrapper<T>);
374///     impl_or_verify!(T: Unaligned => Unaligned for Wrapper<T>);
375/// }
376/// ```
377#[cfg_attr(__ZEROCOPY_INTERNAL_USE_ONLY_DEV_MODE, macro_export)] // Used in `doctests.rs`
378macro_rules! impl_or_verify {
379    // The following two match arms follow the same pattern as their
380    // counterparts in `unsafe_impl!`; see the documentation on those arms for
381    // more details.
382    (
383        const $constname:ident : $constty:ident $(,)?
384        $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),*
385        => $trait:ident for $ty:ty
386    ) => {
387        impl_or_verify!(@impl { unsafe_impl!(
388            const $constname: $constty, $($tyvar $(: $(? $optbound +)* $($bound +)*)?),* => $trait for $ty
389        ); });
390        impl_or_verify!(@verify $trait, {
391            impl<const $constname: $constty, $($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {}
392        });
393    };
394    (
395        $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),*
396        => $trait:ident for $ty:ty $(; |$candidate:ident| $is_bit_valid:expr)?
397    ) => {
398        impl_or_verify!(@impl { unsafe_impl!(
399            $($tyvar $(: $(? $optbound +)* $($bound +)*)?),* => $trait for $ty
400            $(; |$candidate| $is_bit_valid)?
401        ); });
402        impl_or_verify!(@verify $trait, {
403            impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {}
404        });
405    };
406    (@impl $impl_block:tt) => {
407        #[cfg(not(any(feature = "derive", test)))]
408        { $impl_block };
409    };
410    (@verify $trait:ident, $impl_block:tt) => {
411        #[cfg(any(feature = "derive", test))]
412        {
413            // On some toolchains, `Subtrait` triggers the `dead_code` lint
414            // because it is implemented but never used.
415            #[allow(dead_code)]
416            trait Subtrait: $trait {}
417            $impl_block
418        };
419    };
420}
421
422/// Implements `KnownLayout` for a sized type.
423macro_rules! impl_known_layout {
424    ($(const $constvar:ident : $constty:ty, $tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => {
425        $(impl_known_layout!(@inner const $constvar: $constty, $tyvar $(: ?$optbound)? => $ty);)*
426    };
427    ($($tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => {
428        $(impl_known_layout!(@inner , $tyvar $(: ?$optbound)? => $ty);)*
429    };
430    ($($(#[$attrs:meta])* $ty:ty),*) => { $(impl_known_layout!(@inner , => $(#[$attrs])* $ty);)* };
431    (@inner $(const $constvar:ident : $constty:ty)? , $($tyvar:ident $(: ?$optbound:ident)?)? => $(#[$attrs:meta])* $ty:ty) => {
432        const _: () = {
433            use core::ptr::NonNull;
434
435            #[allow(non_local_definitions)]
436            $(#[$attrs])*
437            // SAFETY: Delegates safety to `DstLayout::for_type`.
438            unsafe impl<$($tyvar $(: ?$optbound)?)? $(, const $constvar : $constty)?> KnownLayout for $ty {
439                #[allow(clippy::missing_inline_in_public_items)]
440                #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
441                fn only_derive_is_allowed_to_implement_this_trait() where Self: Sized {}
442
443                type PointerMetadata = ();
444
445                // SAFETY: `CoreMaybeUninit<T>::LAYOUT` and `T::LAYOUT` are
446                // identical because `CoreMaybeUninit<T>` has the same size and
447                // alignment as `T` [1], and `CoreMaybeUninit` admits
448                // uninitialized bytes in all positions.
449                //
450                // [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
451                //
452                //   `MaybeUninit<T>` is guaranteed to have the same size,
453                //   alignment, and ABI as `T`
454                type MaybeUninit = core::mem::MaybeUninit<Self>;
455
456                const LAYOUT: crate::DstLayout = crate::DstLayout::for_type::<$ty>();
457
458                // SAFETY: `.cast` preserves address and provenance.
459                //
460                // FIXME(#429): Add documentation to `.cast` that promises that
461                // it preserves provenance.
462                #[inline(always)]
463                fn raw_from_ptr_len(bytes: NonNull<u8>, _meta: ()) -> NonNull<Self> {
464                    bytes.cast::<Self>()
465                }
466
467                #[inline(always)]
468                fn pointer_to_metadata(_ptr: *mut Self) -> () {
469                }
470            }
471        };
472    };
473}
474
475/// Implements `KnownLayout` for a type in terms of the implementation of
476/// another type with the same representation.
477///
478/// # Safety
479///
480/// - `$ty` and `$repr` must have the same:
481///   - Fixed prefix size
482///   - Alignment
483///   - (For DSTs) trailing slice element size
484/// - It must be valid to perform an `as` cast from `*mut $repr` to `*mut $ty`,
485///   and this operation must preserve referent size (ie, `size_of_val_raw`).
486macro_rules! unsafe_impl_known_layout {
487    ($($tyvar:ident: ?Sized + KnownLayout =>)? #[repr($repr:ty)] $ty:ty) => {{
488        use core::ptr::NonNull;
489
490        crate::util::macros::__unsafe();
491
492        #[allow(non_local_definitions)]
493        // SAFETY: The caller promises that this is sound.
494        unsafe impl<$($tyvar: ?Sized + KnownLayout)?> KnownLayout for $ty {
495            #[allow(clippy::missing_inline_in_public_items, dead_code)]
496            #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
497            fn only_derive_is_allowed_to_implement_this_trait() {}
498
499            type PointerMetadata = <$repr as KnownLayout>::PointerMetadata;
500            type MaybeUninit = <$repr as KnownLayout>::MaybeUninit;
501
502            const LAYOUT: DstLayout = <$repr as KnownLayout>::LAYOUT;
503
504            // SAFETY: All operations preserve address and provenance. Caller
505            // has promised that the `as` cast preserves size.
506            //
507            // FIXME(#429): Add documentation to `NonNull::new_unchecked` that
508            // it preserves provenance.
509            #[inline(always)]
510            fn raw_from_ptr_len(bytes: NonNull<u8>, meta: <$repr as KnownLayout>::PointerMetadata) -> NonNull<Self> {
511                #[allow(clippy::as_conversions)]
512                let ptr = <$repr>::raw_from_ptr_len(bytes, meta).as_ptr() as *mut Self;
513                // SAFETY: `ptr` was converted from `bytes`, which is non-null.
514                unsafe { NonNull::new_unchecked(ptr) }
515            }
516
517            #[inline(always)]
518            fn pointer_to_metadata(ptr: *mut Self) -> Self::PointerMetadata {
519                #[allow(clippy::as_conversions)]
520                let ptr = ptr as *mut $repr;
521                <$repr>::pointer_to_metadata(ptr)
522            }
523        }
524    }};
525}
526
527/// Uses `align_of` to confirm that a type or set of types have alignment 1.
528///
529/// Note that `align_of<T>` requires `T: Sized`, so this macro doesn't work for
530/// unsized types.
531macro_rules! assert_unaligned {
532    ($($tys:ty),*) => {
533        $(
534            // We only compile this assertion under `cfg(test)` to avoid taking
535            // an extra non-dev dependency (and making this crate more expensive
536            // to compile for our dependents).
537            #[cfg(test)]
538            static_assertions::const_assert_eq!(core::mem::align_of::<$tys>(), 1);
539        )*
540    };
541}
542
543/// Emits a function definition as either `const fn` or `fn` depending on
544/// whether the current toolchain version supports `const fn` with generic trait
545/// bounds.
546macro_rules! maybe_const_trait_bounded_fn {
547    // This case handles both `self` methods (where `self` is by value) and
548    // non-method functions. Each `$args` may optionally be followed by `:
549    // $arg_tys:ty`, which can be omitted for `self`.
550    ($(#[$attr:meta])* $vis:vis const fn $name:ident($($args:ident $(: $arg_tys:ty)?),* $(,)?) $(-> $ret_ty:ty)? $body:block) => {
551        #[cfg(not(no_zerocopy_generic_bounds_in_const_fn_1_61_0))]
552        $(#[$attr])* $vis const fn $name($($args $(: $arg_tys)?),*) $(-> $ret_ty)? $body
553
554        #[cfg(no_zerocopy_generic_bounds_in_const_fn_1_61_0)]
555        $(#[$attr])* $vis fn $name($($args $(: $arg_tys)?),*) $(-> $ret_ty)? $body
556    };
557}
558
559/// Either panic (if the current Rust toolchain supports panicking in `const
560/// fn`) or evaluate a constant that will cause an array indexing error whose
561/// error message will include the format string.
562///
563/// The type that this expression evaluates to must be `Copy`, or else the
564/// non-panicking desugaring will fail to compile.
565macro_rules! const_panic {
566    (@non_panic $($_arg:tt)+) => {{
567        // This will type check to whatever type is expected based on the call
568        // site.
569        let panic: [_; 0] = [];
570        // This will always fail (since we're indexing into an array of size 0.
571        #[allow(unconditional_panic)]
572        panic[0]
573    }};
574    ($($arg:tt)+) => {{
575        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
576        panic!($($arg)+);
577        #[cfg(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
578        const_panic!(@non_panic $($arg)+)
579    }};
580}
581
582/// Either assert (if the current Rust toolchain supports panicking in `const
583/// fn`) or evaluate the expression and, if it evaluates to `false`, call
584/// `const_panic!`. This is used in place of `assert!` in const contexts to
585/// accommodate old toolchains.
586macro_rules! const_assert {
587    ($e:expr) => {{
588        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
589        assert!($e);
590        #[cfg(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
591        {
592            let e = $e;
593            if !e {
594                let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e)));
595            }
596        }
597    }};
598    ($e:expr, $($args:tt)+) => {{
599        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
600        assert!($e, $($args)+);
601        #[cfg(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
602        {
603            let e = $e;
604            if !e {
605                let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e), ": ", stringify!($arg)), $($args)*);
606            }
607        }
608    }};
609}
610
611/// Like `const_assert!`, but relative to `debug_assert!`.
612macro_rules! const_debug_assert {
613    ($e:expr $(, $msg:expr)?) => {{
614        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
615        debug_assert!($e $(, $msg)?);
616        #[cfg(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
617        {
618            // Use this (rather than `#[cfg(debug_assertions)]`) to ensure that
619            // `$e` is always compiled even if it will never be evaluated at
620            // runtime.
621            if cfg!(debug_assertions) {
622                let e = $e;
623                if !e {
624                    let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e) $(, ": ", $msg)?));
625                }
626            }
627        }
628    }}
629}
630
631/// Either invoke `unreachable!()` or `loop {}` depending on whether the Rust
632/// toolchain supports panicking in `const fn`.
633macro_rules! const_unreachable {
634    () => {{
635        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
636        unreachable!();
637
638        #[cfg(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
639        loop {}
640    }};
641}
642
643/// Asserts at compile time that `$condition` is true for `Self` or the given
644/// `$tyvar`s. Unlike `const_assert`, this is *strictly* a compile-time check;
645/// it cannot be evaluated in a runtime context. The condition is checked after
646/// monomorphization and, upon failure, emits a compile error.
647macro_rules! static_assert {
648    (Self $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )? => $condition:expr $(, $args:tt)*) => {{
649        trait StaticAssert {
650            const ASSERT: bool;
651        }
652
653        impl<T $(: $(? $optbound +)* $($bound +)*)?> StaticAssert for T {
654            const ASSERT: bool = {
655                const_assert!($condition $(, $args)*);
656                $condition
657            };
658        }
659
660        const_assert!(<Self as StaticAssert>::ASSERT);
661    }};
662    ($($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* => $condition:expr $(, $args:tt)*) => {{
663        trait StaticAssert {
664            const ASSERT: bool;
665        }
666
667        // NOTE: We use `PhantomData` so we can support unsized types.
668        impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?,)*> StaticAssert for ($(core::marker::PhantomData<$tyvar>,)*) {
669            const ASSERT: bool = {
670                const_assert!($condition $(, $args)*);
671                $condition
672            };
673        }
674
675        const_assert!(<($(core::marker::PhantomData<$tyvar>,)*) as StaticAssert>::ASSERT);
676    }};
677}
678
679/// Assert at compile time that `tyvar` does not have a zero-sized DST
680/// component.
681macro_rules! static_assert_dst_is_not_zst {
682    ($tyvar:ident) => {{
683        use crate::KnownLayout;
684        static_assert!($tyvar: ?Sized + KnownLayout => {
685            let dst_is_zst = match $tyvar::LAYOUT.size_info {
686                crate::SizeInfo::Sized { .. } => false,
687                crate::SizeInfo::SliceDst(TrailingSliceLayout { elem_size, .. }) => {
688                    elem_size == 0
689                }
690            };
691            !dst_is_zst
692        }, "cannot call this method on a dynamically-sized type whose trailing slice element is zero-sized");
693    }}
694}
695
696/// Defines a named [`Cast`] implementation.
697///
698/// # Safety
699///
700/// The caller must ensure that, given `src: *mut $src`, `src as *mut $dst` is a
701/// size-preserving or size-shrinking cast.
702///
703/// [`Cast`]: crate::pointer::cast::Cast
704#[macro_export]
705#[doc(hidden)]
706macro_rules! define_cast {
707    // We require the caller to provide an `unsafe` block as part of the input
708    // syntax since a call to `define_cast!` is useless inside of an `unsafe`
709    // block (since it would introduce a type which can't be named outside of
710    // the context of that block).
711    (unsafe { $vis:vis $name:ident $(<$tyvar:ident $(: ?$optbound:ident)?>)? = $src:ty => $dst:ty }) => {
712        #[allow(missing_debug_implementations, missing_copy_implementations, unreachable_pub)]
713        $vis enum $name {}
714
715        // SAFETY: The caller promises that `src as *mut $src` is a size-
716        // preserving or size-shrinking cast. All operations preserve
717        // provenance.
718        unsafe impl $(<$tyvar $(: ?$optbound)?>)? $crate::pointer::cast::Project<$src, $dst> for $name {
719            fn project(src: $crate::pointer::PtrInner<'_, $src>) -> *mut $dst {
720                #[allow(clippy::as_conversions)]
721                return src.as_ptr() as *mut $dst;
722            }
723        }
724
725        // SAFETY: The impl of `Project::project` preserves referent address.
726        unsafe impl $(<$tyvar $(: ?$optbound)?>)? $crate::pointer::cast::Cast<$src, $dst> for $name {}
727    };
728}
729
730/// Implements `TransmuteFrom` and `SizeEq` for `T` and `$wrapper<T>`.
731///
732/// # Safety
733///
734/// `T` and `$wrapper<T>` must have the same bit validity, and must have the
735/// same size in the sense of `CastExact` (specifically, both a
736/// `T`-to-`$wrapper<T>` cast and a `$wrapper<T>`-to-`T` cast must be
737/// size-preserving).
738macro_rules! unsafe_impl_for_transparent_wrapper {
739    ($vis:vis T $(: ?$optbound:ident)? => $wrapper:ident<T>) => {{
740        crate::util::macros::__unsafe();
741
742        use crate::pointer::{TransmuteFrom, cast::{CastExact, TransitiveProject}, SizeEq, invariant::Valid};
743        use crate::wrappers::ReadOnly;
744
745        // SAFETY: The caller promises that `T` and `$wrapper<T>` have the same
746        // bit validity.
747        unsafe impl<T $(: ?$optbound)?> TransmuteFrom<T, Valid, Valid> for $wrapper<T> {}
748        // SAFETY: See previous safety comment.
749        unsafe impl<T $(: ?$optbound)?> TransmuteFrom<$wrapper<T>, Valid, Valid> for T {}
750        // SAFETY: The caller promises that a `T` to `$wrapper<T>` cast is
751        // size-preserving.
752        define_cast!(unsafe { $vis CastToWrapper<T $(: ?$optbound)? > = T => $wrapper<T> });
753        // SAFETY: The caller promises that a `T` to `$wrapper<T>` cast is
754        // size-preserving.
755        unsafe impl<T $(: ?$optbound)?> CastExact<T, $wrapper<T>> for CastToWrapper {}
756        // SAFETY: The caller promises that a `$wrapper<T>` to `T` cast is
757        // size-preserving.
758        define_cast!(unsafe { $vis CastFromWrapper<T $(: ?$optbound)? > = $wrapper<T> => T });
759        // SAFETY: The caller promises that a `$wrapper<T>` to `T` cast is
760        // size-preserving.
761        unsafe impl<T $(: ?$optbound)?> CastExact<$wrapper<T>, T> for CastFromWrapper {}
762
763        impl<T $(: ?$optbound)?> SizeEq<T> for $wrapper<T> {
764            type CastFrom = CastToWrapper;
765        }
766        impl<T $(: ?$optbound)?> SizeEq<$wrapper<T>> for T {
767            type CastFrom = CastFromWrapper;
768        }
769
770        impl<T $(: ?$optbound)?> SizeEq<ReadOnly<T>> for $wrapper<T> {
771            type CastFrom = TransitiveProject<
772                T,
773                <T as SizeEq<ReadOnly<T>>>::CastFrom,
774                CastToWrapper,
775            >;
776        }
777        impl<T $(: ?$optbound)?> SizeEq<$wrapper<T>> for ReadOnly<T> {
778            type CastFrom = TransitiveProject<
779                T,
780                CastFromWrapper,
781                <ReadOnly<T> as SizeEq<T>>::CastFrom,
782            >;
783        }
784
785        impl<T $(: ?$optbound)?> SizeEq<ReadOnly<T>> for ReadOnly<$wrapper<T>> {
786            type CastFrom = TransitiveProject<
787                $wrapper<T>,
788                <$wrapper<T> as SizeEq<ReadOnly<T>>>::CastFrom,
789                <ReadOnly<$wrapper<T>> as SizeEq<$wrapper<T>>>::CastFrom,
790            >;
791        }
792        impl<T $(: ?$optbound)?> SizeEq<ReadOnly<$wrapper<T>>> for ReadOnly<T> {
793            type CastFrom = TransitiveProject<
794                $wrapper<T>,
795                <$wrapper<T> as SizeEq<ReadOnly<$wrapper<T>>>>::CastFrom,
796                <ReadOnly<T> as SizeEq<$wrapper<T>>>::CastFrom,
797            >;
798        }
799    }};
800}
801
802macro_rules! impl_transitive_transmute_from {
803    ($($tyvar:ident $(: ?$optbound:ident)?)? => $t:ty => $u:ty => $v:ty) => {
804        const _: () = {
805            use crate::pointer::{TransmuteFrom, SizeEq, invariant::Valid};
806
807            impl<$($tyvar $(: ?$optbound)?)?> SizeEq<$t> for $v
808            where
809                $u: SizeEq<$t>,
810                $v: SizeEq<$u>,
811            {
812                type CastFrom = cast::TransitiveProject<
813                    $u,
814                    <$u as SizeEq<$t>>::CastFrom,
815                    <$v as SizeEq<$u>>::CastFrom
816                >;
817            }
818
819            // SAFETY: Since `$u: TransmuteFrom<$t, Valid, Valid>`, it is sound
820            // to transmute a bit-valid `$t` to a bit-valid `$u`. Since `$v:
821            // TransmuteFrom<$u, Valid, Valid>`, it is sound to transmute that
822            // bit-valid `$u` to a bit-valid `$v`.
823            unsafe impl<$($tyvar $(: ?$optbound)?)?> TransmuteFrom<$t, Valid, Valid> for $v
824            where
825                $u: TransmuteFrom<$t, Valid, Valid>,
826                $v: TransmuteFrom<$u, Valid, Valid>,
827            {}
828        };
829    };
830}
831
832/// A no-op `unsafe fn` for use in macro expansions.
833///
834/// Calling this function in a macro expansion ensures that the macro's caller
835/// must wrap the call in `unsafe { ... }`.
836#[inline(always)]
837pub(crate) const unsafe fn __unsafe() {}