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<AA: crate::pointer::invariant::Reference>($candidate: Maybe<'_, Self, AA>) -> bool {
139 $is_bit_valid
140 }
141 };
142 (@method TryFromBytes) => {
143 #[allow(clippy::missing_inline_in_public_items)]
144 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
145 fn only_derive_is_allowed_to_implement_this_trait() {}
146 #[inline(always)] fn is_bit_valid<AA: crate::pointer::invariant::Reference>(_: Maybe<'_, Self, AA>) -> bool { true }
147 };
148 (@method $trait:ident) => {
149 #[allow(clippy::missing_inline_in_public_items, dead_code)]
150 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
151 fn only_derive_is_allowed_to_implement_this_trait() {}
152 };
153 (@method $trait:ident; |$_candidate:ident| $_is_bit_valid:expr) => {
154 compile_error!("Can't provide `is_bit_valid` impl for trait other than `TryFromBytes`");
155 };
156}
157
158/// Implements `$trait` for `$ty` where `$ty: TransmuteFrom<$repr>` (and
159/// vice-versa).
160///
161/// Calling this macro is safe; the internals of the macro emit appropriate
162/// trait bounds which ensure that the given impl is sound.
163macro_rules! impl_for_transmute_from {
164 (
165 $(#[$attr:meta])*
166 $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?)?
167 => $trait:ident for $ty:ty [$($unsafe_cell:ident)? <$repr:ty>]
168 ) => {
169 const _: () = {
170 $(#[$attr])*
171 #[allow(non_local_definitions)]
172
173 // SAFETY: `is_trait<T, R>` (defined and used below) requires `T:
174 // TransmuteFrom<R>`, `R: TransmuteFrom<T>`, and `R: $trait`. It is
175 // called using `$ty` and `$repr`, ensuring that `$ty` and `$repr`
176 // have equivalent bit validity, and ensuring that `$repr: $trait`.
177 // The supported traits - `TryFromBytes`, `FromZeros`, `FromBytes`,
178 // and `IntoBytes` - are defined only in terms of the bit validity
179 // of a type. Therefore, `$repr: $trait` ensures that `$ty: $trait`
180 // is sound.
181 unsafe impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?)?> $trait for $ty {
182 #[allow(dead_code, clippy::missing_inline_in_public_items)]
183 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
184 fn only_derive_is_allowed_to_implement_this_trait() {
185 use crate::pointer::{*, invariant::Valid};
186
187 impl_for_transmute_from!(@assert_is_supported_trait $trait);
188
189 fn is_trait<T, R>()
190 where
191 T: TransmuteFrom<R, Valid, Valid> + ?Sized,
192 R: TransmuteFrom<T, Valid, Valid> + ?Sized,
193 R: $trait,
194 {
195 }
196
197 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
198 fn f<$($tyvar $(: $(? $optbound +)* $($bound +)*)?)?>() {
199 is_trait::<$ty, $repr>();
200 }
201 }
202
203 impl_for_transmute_from!(
204 @is_bit_valid
205 $(<$tyvar $(: $(? $optbound +)* $($bound +)*)?>)?
206 $trait for $ty [$($unsafe_cell)? <$repr>]
207 );
208 }
209 };
210 };
211 (@assert_is_supported_trait TryFromBytes) => {};
212 (@assert_is_supported_trait FromZeros) => {};
213 (@assert_is_supported_trait FromBytes) => {};
214 (@assert_is_supported_trait IntoBytes) => {};
215 (
216 @is_bit_valid
217 $(<$tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?>)?
218 TryFromBytes for $ty:ty [UnsafeCell<$repr:ty>]
219 ) => {
220 #[inline]
221 fn is_bit_valid<A: crate::pointer::invariant::Reference>(candidate: Maybe<'_, Self, A>) -> bool {
222 let c: Maybe<'_, Self, crate::pointer::invariant::Exclusive> = candidate.into_exclusive_or_pme();
223 let c: Maybe<'_, $repr, _> = c.transmute::<_, _, (_, (_, (BecauseExclusive, BecauseExclusive)))>();
224 // SAFETY: This macro ensures that `$repr` and `Self` have the same
225 // size and bit validity. Thus, a bit-valid instance of `$repr` is
226 // also a bit-valid instance of `Self`.
227 <$repr as TryFromBytes>::is_bit_valid(c)
228 }
229 };
230 (
231 @is_bit_valid
232 $(<$tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?>)?
233 TryFromBytes for $ty:ty [<$repr:ty>]
234 ) => {
235 #[inline]
236 fn is_bit_valid<A: crate::pointer::invariant::Reference>(candidate: Maybe<'_, Self, A>) -> bool {
237 // SAFETY: This macro ensures that `$repr` and `Self` have the same
238 // size and bit validity. Thus, a bit-valid instance of `$repr` is
239 // also a bit-valid instance of `Self`.
240 <$repr as TryFromBytes>::is_bit_valid(candidate.transmute())
241 }
242 };
243 (
244 @is_bit_valid
245 $(<$tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?>)?
246 $trait:ident for $ty:ty [$($unsafe_cell:ident)? <$repr:ty>]
247 ) => {
248 // Trait other than `TryFromBytes`; no `is_bit_valid` impl.
249 };
250}
251
252/// Implements a trait for a type, bounding on each memeber of the power set of
253/// a set of type variables. This is useful for implementing traits for tuples
254/// or `fn` types.
255///
256/// The last argument is the name of a macro which will be called in every
257/// `impl` block, and is expected to expand to the name of the type for which to
258/// implement the trait.
259///
260/// For example, the invocation:
261/// ```ignore
262/// unsafe_impl_for_power_set!(A, B => Foo for type!(...))
263/// ```
264/// ...expands to:
265/// ```ignore
266/// unsafe impl Foo for type!() { ... }
267/// unsafe impl<B> Foo for type!(B) { ... }
268/// unsafe impl<A, B> Foo for type!(A, B) { ... }
269/// ```
270macro_rules! unsafe_impl_for_power_set {
271 (
272 $first:ident $(, $rest:ident)* $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)
273 $(; |$candidate:ident| $is_bit_valid:expr)?
274 ) => {
275 unsafe_impl_for_power_set!(
276 $($rest),* $(-> $ret)? => $trait for $macro!(...)
277 $(; |$candidate| $is_bit_valid)?
278 );
279 unsafe_impl_for_power_set!(
280 @impl $first $(, $rest)* $(-> $ret)? => $trait for $macro!(...)
281 $(; |$candidate| $is_bit_valid)?
282 );
283 };
284 (
285 $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)
286 $(; |$candidate:ident| $is_bit_valid:expr)?
287 ) => {
288 unsafe_impl_for_power_set!(
289 @impl $(-> $ret)? => $trait for $macro!(...)
290 $(; |$candidate| $is_bit_valid)?
291 );
292 };
293 (
294 @impl $($vars:ident),* $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)
295 $(; |$candidate:ident| $is_bit_valid:expr)?
296 ) => {
297 unsafe_impl!(
298 $($vars,)* $($ret)? => $trait for $macro!($($vars),* $(-> $ret)?)
299 $(; |$candidate| $is_bit_valid)?
300 );
301 };
302}
303
304/// Expands to an `Option<extern "C" fn>` type with the given argument types and
305/// return type. Designed for use with `unsafe_impl_for_power_set`.
306macro_rules! opt_extern_c_fn {
307 ($($args:ident),* -> $ret:ident) => { Option<extern "C" fn($($args),*) -> $ret> };
308}
309
310/// Expands to a `Option<fn>` type with the given argument types and return
311/// type. Designed for use with `unsafe_impl_for_power_set`.
312macro_rules! opt_fn {
313 ($($args:ident),* -> $ret:ident) => { Option<fn($($args),*) -> $ret> };
314}
315
316/// Implements trait(s) for a type or verifies the given implementation by
317/// referencing an existing (derived) implementation.
318///
319/// This macro exists so that we can provide zerocopy-derive as an optional
320/// dependency and still get the benefit of using its derives to validate that
321/// our trait impls are sound.
322///
323/// When compiling without `--cfg 'feature = "derive"` and without `--cfg test`,
324/// `impl_or_verify!` emits the provided trait impl. When compiling with either
325/// of those cfgs, it is expected that the type in question is deriving the
326/// traits instead. In this case, `impl_or_verify!` emits code which validates
327/// that the given trait impl is at least as restrictive as the the impl emitted
328/// by the custom derive. This has the effect of confirming that the impl which
329/// is emitted when the `derive` feature is disabled is actually sound (on the
330/// assumption that the impl emitted by the custom derive is sound).
331///
332/// The caller is still required to provide a safety comment (e.g. using the
333/// `const _: () = unsafe` macro) . The reason for this restriction is that, while
334/// `impl_or_verify!` can guarantee that the provided impl is sound when it is
335/// compiled with the appropriate cfgs, there is no way to guarantee that it is
336/// ever compiled with those cfgs. In particular, it would be possible to
337/// accidentally place an `impl_or_verify!` call in a context that is only ever
338/// compiled when the `derive` feature is disabled. If that were to happen,
339/// there would be nothing to prevent an unsound trait impl from being emitted.
340/// Requiring a safety comment reduces the likelihood of emitting an unsound
341/// impl in this case, and also provides useful documentation for readers of the
342/// code.
343///
344/// Finally, if a `TryFromBytes::is_bit_valid` impl is provided, it must adhere
345/// to the safety preconditions of [`unsafe_impl!`].
346///
347/// ## Example
348///
349/// ```rust,ignore
350/// // Note that these derives are gated by `feature = "derive"`
351/// #[cfg_attr(any(feature = "derive", test), derive(FromZeros, FromBytes, IntoBytes, Unaligned))]
352/// #[repr(transparent)]
353/// struct Wrapper<T>(T);
354///
355/// const _: () = unsafe {
356/// /// SAFETY:
357/// /// `Wrapper<T>` is `repr(transparent)`, so it is sound to implement any
358/// /// zerocopy trait if `T` implements that trait.
359/// impl_or_verify!(T: FromZeros => FromZeros for Wrapper<T>);
360/// impl_or_verify!(T: FromBytes => FromBytes for Wrapper<T>);
361/// impl_or_verify!(T: IntoBytes => IntoBytes for Wrapper<T>);
362/// impl_or_verify!(T: Unaligned => Unaligned for Wrapper<T>);
363/// }
364/// ```
365macro_rules! impl_or_verify {
366 // The following two match arms follow the same pattern as their
367 // counterparts in `unsafe_impl!`; see the documentation on those arms for
368 // more details.
369 (
370 const $constname:ident : $constty:ident $(,)?
371 $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),*
372 => $trait:ident for $ty:ty
373 ) => {
374 impl_or_verify!(@impl { unsafe_impl!(
375 const $constname: $constty, $($tyvar $(: $(? $optbound +)* $($bound +)*)?),* => $trait for $ty
376 ); });
377 impl_or_verify!(@verify $trait, {
378 impl<const $constname: $constty, $($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {}
379 });
380 };
381 (
382 $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),*
383 => $trait:ident for $ty:ty $(; |$candidate:ident| $is_bit_valid:expr)?
384 ) => {
385 impl_or_verify!(@impl { unsafe_impl!(
386 $($tyvar $(: $(? $optbound +)* $($bound +)*)?),* => $trait for $ty
387 $(; |$candidate| $is_bit_valid)?
388 ); });
389 impl_or_verify!(@verify $trait, {
390 impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {}
391 });
392 };
393 (@impl $impl_block:tt) => {
394 #[cfg(not(any(feature = "derive", test)))]
395 { $impl_block };
396 };
397 (@verify $trait:ident, $impl_block:tt) => {
398 #[cfg(any(feature = "derive", test))]
399 {
400 trait Subtrait: $trait {}
401 $impl_block
402 };
403 };
404}
405
406/// Implements `KnownLayout` for a sized type.
407macro_rules! impl_known_layout {
408 ($(const $constvar:ident : $constty:ty, $tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => {
409 $(impl_known_layout!(@inner const $constvar: $constty, $tyvar $(: ?$optbound)? => $ty);)*
410 };
411 ($($tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => {
412 $(impl_known_layout!(@inner , $tyvar $(: ?$optbound)? => $ty);)*
413 };
414 ($($(#[$attrs:meta])* $ty:ty),*) => { $(impl_known_layout!(@inner , => $(#[$attrs])* $ty);)* };
415 (@inner $(const $constvar:ident : $constty:ty)? , $($tyvar:ident $(: ?$optbound:ident)?)? => $(#[$attrs:meta])* $ty:ty) => {
416 const _: () = {
417 use core::ptr::NonNull;
418
419 #[allow(non_local_definitions)]
420 $(#[$attrs])*
421 // SAFETY: Delegates safety to `DstLayout::for_type`.
422 unsafe impl<$($tyvar $(: ?$optbound)?)? $(, const $constvar : $constty)?> KnownLayout for $ty {
423 #[allow(clippy::missing_inline_in_public_items)]
424 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
425 fn only_derive_is_allowed_to_implement_this_trait() where Self: Sized {}
426
427 type PointerMetadata = ();
428
429 // SAFETY: `CoreMaybeUninit<T>::LAYOUT` and `T::LAYOUT` are
430 // identical because `CoreMaybeUninit<T>` has the same size and
431 // alignment as `T` [1], and `CoreMaybeUninit` admits
432 // uninitialized bytes in all positions.
433 //
434 // [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
435 //
436 // `MaybeUninit<T>` is guaranteed to have the same size,
437 // alignment, and ABI as `T`
438 type MaybeUninit = core::mem::MaybeUninit<Self>;
439
440 const LAYOUT: crate::DstLayout = crate::DstLayout::for_type::<$ty>();
441
442 // SAFETY: `.cast` preserves address and provenance.
443 //
444 // FIXME(#429): Add documentation to `.cast` that promises that
445 // it preserves provenance.
446 #[inline(always)]
447 fn raw_from_ptr_len(bytes: NonNull<u8>, _meta: ()) -> NonNull<Self> {
448 bytes.cast::<Self>()
449 }
450
451 #[inline(always)]
452 fn pointer_to_metadata(_ptr: *mut Self) -> () {
453 }
454 }
455 };
456 };
457}
458
459/// Implements `KnownLayout` for a type in terms of the implementation of
460/// another type with the same representation.
461///
462/// # Safety
463///
464/// - `$ty` and `$repr` must have the same:
465/// - Fixed prefix size
466/// - Alignment
467/// - (For DSTs) trailing slice element size
468/// - It must be valid to perform an `as` cast from `*mut $repr` to `*mut $ty`,
469/// and this operation must preserve referent size (ie, `size_of_val_raw`).
470macro_rules! unsafe_impl_known_layout {
471 ($($tyvar:ident: ?Sized + KnownLayout =>)? #[repr($repr:ty)] $ty:ty) => {{
472 use core::ptr::NonNull;
473
474 crate::util::macros::__unsafe();
475
476 #[allow(non_local_definitions)]
477 // SAFETY: The caller promises that this is sound.
478 unsafe impl<$($tyvar: ?Sized + KnownLayout)?> KnownLayout for $ty {
479 #[allow(clippy::missing_inline_in_public_items, dead_code)]
480 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
481 fn only_derive_is_allowed_to_implement_this_trait() {}
482
483 type PointerMetadata = <$repr as KnownLayout>::PointerMetadata;
484 type MaybeUninit = <$repr as KnownLayout>::MaybeUninit;
485
486 const LAYOUT: DstLayout = <$repr as KnownLayout>::LAYOUT;
487
488 // SAFETY: All operations preserve address and provenance. Caller
489 // has promised that the `as` cast preserves size.
490 //
491 // FIXME(#429): Add documentation to `NonNull::new_unchecked` that
492 // it preserves provenance.
493 #[inline(always)]
494 fn raw_from_ptr_len(bytes: NonNull<u8>, meta: <$repr as KnownLayout>::PointerMetadata) -> NonNull<Self> {
495 #[allow(clippy::as_conversions)]
496 let ptr = <$repr>::raw_from_ptr_len(bytes, meta).as_ptr() as *mut Self;
497 // SAFETY: `ptr` was converted from `bytes`, which is non-null.
498 unsafe { NonNull::new_unchecked(ptr) }
499 }
500
501 #[inline(always)]
502 fn pointer_to_metadata(ptr: *mut Self) -> Self::PointerMetadata {
503 #[allow(clippy::as_conversions)]
504 let ptr = ptr as *mut $repr;
505 <$repr>::pointer_to_metadata(ptr)
506 }
507 }
508 }};
509}
510
511/// Uses `align_of` to confirm that a type or set of types have alignment 1.
512///
513/// Note that `align_of<T>` requires `T: Sized`, so this macro doesn't work for
514/// unsized types.
515macro_rules! assert_unaligned {
516 ($($tys:ty),*) => {
517 $(
518 // We only compile this assertion under `cfg(test)` to avoid taking
519 // an extra non-dev dependency (and making this crate more expensive
520 // to compile for our dependents).
521 #[cfg(test)]
522 static_assertions::const_assert_eq!(core::mem::align_of::<$tys>(), 1);
523 )*
524 };
525}
526
527/// Emits a function definition as either `const fn` or `fn` depending on
528/// whether the current toolchain version supports `const fn` with generic trait
529/// bounds.
530macro_rules! maybe_const_trait_bounded_fn {
531 // This case handles both `self` methods (where `self` is by value) and
532 // non-method functions. Each `$args` may optionally be followed by `:
533 // $arg_tys:ty`, which can be omitted for `self`.
534 ($(#[$attr:meta])* $vis:vis const fn $name:ident($($args:ident $(: $arg_tys:ty)?),* $(,)?) $(-> $ret_ty:ty)? $body:block) => {
535 #[cfg(zerocopy_generic_bounds_in_const_fn_1_61_0)]
536 $(#[$attr])* $vis const fn $name($($args $(: $arg_tys)?),*) $(-> $ret_ty)? $body
537
538 #[cfg(not(zerocopy_generic_bounds_in_const_fn_1_61_0))]
539 $(#[$attr])* $vis fn $name($($args $(: $arg_tys)?),*) $(-> $ret_ty)? $body
540 };
541}
542
543/// Either panic (if the current Rust toolchain supports panicking in `const
544/// fn`) or evaluate a constant that will cause an array indexing error whose
545/// error message will include the format string.
546///
547/// The type that this expression evaluates to must be `Copy`, or else the
548/// non-panicking desugaring will fail to compile.
549macro_rules! const_panic {
550 (@non_panic $($_arg:tt)+) => {{
551 // This will type check to whatever type is expected based on the call
552 // site.
553 let panic: [_; 0] = [];
554 // This will always fail (since we're indexing into an array of size 0.
555 #[allow(unconditional_panic)]
556 panic[0]
557 }};
558 ($($arg:tt)+) => {{
559 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
560 panic!($($arg)+);
561 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
562 const_panic!(@non_panic $($arg)+)
563 }};
564}
565
566/// Either assert (if the current Rust toolchain supports panicking in `const
567/// fn`) or evaluate the expression and, if it evaluates to `false`, call
568/// `const_panic!`. This is used in place of `assert!` in const contexts to
569/// accommodate old toolchains.
570macro_rules! const_assert {
571 ($e:expr) => {{
572 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
573 assert!($e);
574 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
575 {
576 let e = $e;
577 if !e {
578 let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e)));
579 }
580 }
581 }};
582 ($e:expr, $($args:tt)+) => {{
583 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
584 assert!($e, $($args)+);
585 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
586 {
587 let e = $e;
588 if !e {
589 let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e), ": ", stringify!($arg)), $($args)*);
590 }
591 }
592 }};
593}
594
595/// Like `const_assert!`, but relative to `debug_assert!`.
596macro_rules! const_debug_assert {
597 ($e:expr $(, $msg:expr)?) => {{
598 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
599 debug_assert!($e $(, $msg)?);
600 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
601 {
602 // Use this (rather than `#[cfg(debug_assertions)]`) to ensure that
603 // `$e` is always compiled even if it will never be evaluated at
604 // runtime.
605 if cfg!(debug_assertions) {
606 let e = $e;
607 if !e {
608 let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e) $(, ": ", $msg)?));
609 }
610 }
611 }
612 }}
613}
614
615/// Either invoke `unreachable!()` or `loop {}` depending on whether the Rust
616/// toolchain supports panicking in `const fn`.
617macro_rules! const_unreachable {
618 () => {{
619 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
620 unreachable!();
621
622 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
623 loop {}
624 }};
625}
626
627/// Asserts at compile time that `$condition` is true for `Self` or the given
628/// `$tyvar`s. Unlike `const_assert`, this is *strictly* a compile-time check;
629/// it cannot be evaluated in a runtime context. The condition is checked after
630/// monomorphization and, upon failure, emits a compile error.
631macro_rules! static_assert {
632 (Self $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )? => $condition:expr $(, $args:tt)*) => {{
633 trait StaticAssert {
634 const ASSERT: bool;
635 }
636
637 impl<T $(: $(? $optbound +)* $($bound +)*)?> StaticAssert for T {
638 const ASSERT: bool = {
639 const_assert!($condition $(, $args)*);
640 $condition
641 };
642 }
643
644 const_assert!(<Self as StaticAssert>::ASSERT);
645 }};
646 ($($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* => $condition:expr $(, $args:tt)*) => {{
647 trait StaticAssert {
648 const ASSERT: bool;
649 }
650
651 impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?,)*> StaticAssert for ($($tyvar,)*) {
652 const ASSERT: bool = {
653 const_assert!($condition $(, $args)*);
654 $condition
655 };
656 }
657
658 const_assert!(<($($tyvar,)*) as StaticAssert>::ASSERT);
659 }};
660}
661
662/// Assert at compile time that `tyvar` does not have a zero-sized DST
663/// component.
664macro_rules! static_assert_dst_is_not_zst {
665 ($tyvar:ident) => {{
666 use crate::KnownLayout;
667 static_assert!($tyvar: ?Sized + KnownLayout => {
668 let dst_is_zst = match $tyvar::LAYOUT.size_info {
669 crate::SizeInfo::Sized { .. } => false,
670 crate::SizeInfo::SliceDst(TrailingSliceLayout { elem_size, .. }) => {
671 elem_size == 0
672 }
673 };
674 !dst_is_zst
675 }, "cannot call this method on a dynamically-sized type whose trailing slice element is zero-sized");
676 }}
677}
678
679macro_rules! cast {
680 () => {
681 |p| {
682 // SAFETY: `NonNull::as_ptr` returns a non-null pointer, so the
683 // argument to `NonNull::new_unchecked` is also non-null.
684 #[allow(clippy::as_conversions, unused_unsafe)]
685 #[allow(clippy::undocumented_unsafe_blocks)] // Clippy false positive
686 return unsafe {
687 core::ptr::NonNull::new_unchecked(core::ptr::NonNull::as_ptr(p) as *mut _)
688 };
689 }
690 };
691 ($p:ident) => {
692 cast!()($p)
693 };
694}
695
696/// Implements `TransmuteFrom` and `SizeEq` for `T` and `$wrapper<T>`.
697///
698/// # Safety
699///
700/// `T` and `$wrapper<T>` must have the same bit validity, and must have the
701/// same size in the sense of `SizeEq`.
702macro_rules! unsafe_impl_for_transparent_wrapper {
703 (T $(: ?$optbound:ident)? => $wrapper:ident<T>) => {{
704 use core::ptr::NonNull;
705 use crate::pointer::{TransmuteFrom, SizeEq, invariant::Valid};
706
707 crate::util::macros::__unsafe();
708
709 // SAFETY: The caller promises that `T` and `$wrapper<T>` have the
710 // same bit validity.
711 unsafe impl<T $(: ?$optbound)?> TransmuteFrom<T, Valid, Valid> for $wrapper<T> {}
712 // SAFETY: See previous safety comment.
713 unsafe impl<T $(: ?$optbound)?> TransmuteFrom<$wrapper<T>, Valid, Valid> for T {}
714 // SAFETY: The caller promises that `T` and `$wrapper<T>` satisfy
715 // `SizeEq`.
716 unsafe impl<T $(: ?$optbound)?> SizeEq<T> for $wrapper<T> {
717 fn cast_from_raw(t: NonNull<T>) -> NonNull<$wrapper<T>> {
718 cast!(t)
719 }
720 }
721 // SAFETY: See previous safety comment.
722 unsafe impl<T $(: ?$optbound)?> SizeEq<$wrapper<T>> for T {
723 fn cast_from_raw(t: NonNull<$wrapper<T>>) -> NonNull<T> {
724 cast!(t)
725 }
726 }
727 }};
728}
729
730macro_rules! impl_transitive_transmute_from {
731 ($($tyvar:ident $(: ?$optbound:ident)?)? => $t:ty => $u:ty => $v:ty) => {
732 const _: () = {
733 use core::ptr::NonNull;
734 use crate::pointer::{TransmuteFrom, SizeEq, invariant::Valid};
735
736 // SAFETY: Since `$u: SizeEq<$t>` and `$v: SizeEq<U>`, this impl is
737 // transitively sound.
738 unsafe impl<$($tyvar $(: ?$optbound)?)?> SizeEq<$t> for $v
739 where
740 $u: SizeEq<$t>,
741 $v: SizeEq<$u>,
742 {
743 fn cast_from_raw(t: NonNull<$t>) -> NonNull<$v> {
744 cast!(t)
745 }
746 }
747
748 // SAFETY: Since `$u: TransmuteFrom<$t, Valid, Valid>`, it is sound
749 // to transmute a bit-valid `$t` to a bit-valid `$u`. Since `$v:
750 // TransmuteFrom<$u, Valid, Valid>`, it is sound to transmute that
751 // bit-valid `$u` to a bit-valid `$v`.
752 unsafe impl<$($tyvar $(: ?$optbound)?)?> TransmuteFrom<$t, Valid, Valid> for $v
753 where
754 $u: TransmuteFrom<$t, Valid, Valid>,
755 $v: TransmuteFrom<$u, Valid, Valid>,
756 {}
757 };
758 };
759}
760
761macro_rules! impl_size_eq {
762 ($t:ty, $u:ty) => {
763 const _: () = {
764 use crate::pointer::SizeEq;
765 use core::ptr::NonNull;
766
767 static_assert!(=> mem::size_of::<$t>() == mem::size_of::<$u>());
768
769 // SAFETY: We've asserted that their sizes are equal.
770 unsafe impl SizeEq<$t> for $u {
771 fn cast_from_raw(t: NonNull<$t>) -> NonNull<$u> {
772 cast!(t)
773 }
774 }
775 // SAFETY: We've asserted that their sizes are equal.
776 unsafe impl SizeEq<$u> for $t {
777 fn cast_from_raw(u: NonNull<$u>) -> NonNull<$t> {
778 cast!(u)
779 }
780 }
781 };
782 };
783}
784
785/// A no-op `unsafe fn` for use in macro expansions.
786///
787/// Calling this function in a macro expansion ensures that the macro's caller
788/// must wrap the call in `unsafe { ... }`.
789pub(crate) const unsafe fn __unsafe() {}