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: $crate::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 member 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 // On some toolchains, `Subtrait` triggers the `dead_code` lint
401 // because it is implemented but never used.
402 #[allow(dead_code)]
403 trait Subtrait: $trait {}
404 $impl_block
405 };
406 };
407}
408
409/// Implements `KnownLayout` for a sized type.
410macro_rules! impl_known_layout {
411 ($(const $constvar:ident : $constty:ty, $tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => {
412 $(impl_known_layout!(@inner const $constvar: $constty, $tyvar $(: ?$optbound)? => $ty);)*
413 };
414 ($($tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => {
415 $(impl_known_layout!(@inner , $tyvar $(: ?$optbound)? => $ty);)*
416 };
417 ($($(#[$attrs:meta])* $ty:ty),*) => { $(impl_known_layout!(@inner , => $(#[$attrs])* $ty);)* };
418 (@inner $(const $constvar:ident : $constty:ty)? , $($tyvar:ident $(: ?$optbound:ident)?)? => $(#[$attrs:meta])* $ty:ty) => {
419 const _: () = {
420 use core::ptr::NonNull;
421
422 #[allow(non_local_definitions)]
423 $(#[$attrs])*
424 // SAFETY: Delegates safety to `DstLayout::for_type`.
425 unsafe impl<$($tyvar $(: ?$optbound)?)? $(, const $constvar : $constty)?> KnownLayout for $ty {
426 #[allow(clippy::missing_inline_in_public_items)]
427 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
428 fn only_derive_is_allowed_to_implement_this_trait() where Self: Sized {}
429
430 type PointerMetadata = ();
431
432 // SAFETY: `CoreMaybeUninit<T>::LAYOUT` and `T::LAYOUT` are
433 // identical because `CoreMaybeUninit<T>` has the same size and
434 // alignment as `T` [1], and `CoreMaybeUninit` admits
435 // uninitialized bytes in all positions.
436 //
437 // [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
438 //
439 // `MaybeUninit<T>` is guaranteed to have the same size,
440 // alignment, and ABI as `T`
441 type MaybeUninit = core::mem::MaybeUninit<Self>;
442
443 const LAYOUT: crate::DstLayout = crate::DstLayout::for_type::<$ty>();
444
445 // SAFETY: `.cast` preserves address and provenance.
446 //
447 // FIXME(#429): Add documentation to `.cast` that promises that
448 // it preserves provenance.
449 #[inline(always)]
450 fn raw_from_ptr_len(bytes: NonNull<u8>, _meta: ()) -> NonNull<Self> {
451 bytes.cast::<Self>()
452 }
453
454 #[inline(always)]
455 fn pointer_to_metadata(_ptr: *mut Self) -> () {
456 }
457 }
458 };
459 };
460}
461
462/// Implements `KnownLayout` for a type in terms of the implementation of
463/// another type with the same representation.
464///
465/// # Safety
466///
467/// - `$ty` and `$repr` must have the same:
468/// - Fixed prefix size
469/// - Alignment
470/// - (For DSTs) trailing slice element size
471/// - It must be valid to perform an `as` cast from `*mut $repr` to `*mut $ty`,
472/// and this operation must preserve referent size (ie, `size_of_val_raw`).
473macro_rules! unsafe_impl_known_layout {
474 ($($tyvar:ident: ?Sized + KnownLayout =>)? #[repr($repr:ty)] $ty:ty) => {{
475 use core::ptr::NonNull;
476
477 crate::util::macros::__unsafe();
478
479 #[allow(non_local_definitions)]
480 // SAFETY: The caller promises that this is sound.
481 unsafe impl<$($tyvar: ?Sized + KnownLayout)?> KnownLayout for $ty {
482 #[allow(clippy::missing_inline_in_public_items, dead_code)]
483 #[cfg_attr(all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), coverage(off))]
484 fn only_derive_is_allowed_to_implement_this_trait() {}
485
486 type PointerMetadata = <$repr as KnownLayout>::PointerMetadata;
487 type MaybeUninit = <$repr as KnownLayout>::MaybeUninit;
488
489 const LAYOUT: DstLayout = <$repr as KnownLayout>::LAYOUT;
490
491 // SAFETY: All operations preserve address and provenance. Caller
492 // has promised that the `as` cast preserves size.
493 //
494 // FIXME(#429): Add documentation to `NonNull::new_unchecked` that
495 // it preserves provenance.
496 #[inline(always)]
497 fn raw_from_ptr_len(bytes: NonNull<u8>, meta: <$repr as KnownLayout>::PointerMetadata) -> NonNull<Self> {
498 #[allow(clippy::as_conversions)]
499 let ptr = <$repr>::raw_from_ptr_len(bytes, meta).as_ptr() as *mut Self;
500 // SAFETY: `ptr` was converted from `bytes`, which is non-null.
501 unsafe { NonNull::new_unchecked(ptr) }
502 }
503
504 #[inline(always)]
505 fn pointer_to_metadata(ptr: *mut Self) -> Self::PointerMetadata {
506 #[allow(clippy::as_conversions)]
507 let ptr = ptr as *mut $repr;
508 <$repr>::pointer_to_metadata(ptr)
509 }
510 }
511 }};
512}
513
514/// Uses `align_of` to confirm that a type or set of types have alignment 1.
515///
516/// Note that `align_of<T>` requires `T: Sized`, so this macro doesn't work for
517/// unsized types.
518macro_rules! assert_unaligned {
519 ($($tys:ty),*) => {
520 $(
521 // We only compile this assertion under `cfg(test)` to avoid taking
522 // an extra non-dev dependency (and making this crate more expensive
523 // to compile for our dependents).
524 #[cfg(test)]
525 static_assertions::const_assert_eq!(core::mem::align_of::<$tys>(), 1);
526 )*
527 };
528}
529
530/// Emits a function definition as either `const fn` or `fn` depending on
531/// whether the current toolchain version supports `const fn` with generic trait
532/// bounds.
533macro_rules! maybe_const_trait_bounded_fn {
534 // This case handles both `self` methods (where `self` is by value) and
535 // non-method functions. Each `$args` may optionally be followed by `:
536 // $arg_tys:ty`, which can be omitted for `self`.
537 ($(#[$attr:meta])* $vis:vis const fn $name:ident($($args:ident $(: $arg_tys:ty)?),* $(,)?) $(-> $ret_ty:ty)? $body:block) => {
538 #[cfg(zerocopy_generic_bounds_in_const_fn_1_61_0)]
539 $(#[$attr])* $vis const fn $name($($args $(: $arg_tys)?),*) $(-> $ret_ty)? $body
540
541 #[cfg(not(zerocopy_generic_bounds_in_const_fn_1_61_0))]
542 $(#[$attr])* $vis fn $name($($args $(: $arg_tys)?),*) $(-> $ret_ty)? $body
543 };
544}
545
546/// Either panic (if the current Rust toolchain supports panicking in `const
547/// fn`) or evaluate a constant that will cause an array indexing error whose
548/// error message will include the format string.
549///
550/// The type that this expression evaluates to must be `Copy`, or else the
551/// non-panicking desugaring will fail to compile.
552macro_rules! const_panic {
553 (@non_panic $($_arg:tt)+) => {{
554 // This will type check to whatever type is expected based on the call
555 // site.
556 let panic: [_; 0] = [];
557 // This will always fail (since we're indexing into an array of size 0.
558 #[allow(unconditional_panic)]
559 panic[0]
560 }};
561 ($($arg:tt)+) => {{
562 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
563 panic!($($arg)+);
564 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
565 const_panic!(@non_panic $($arg)+)
566 }};
567}
568
569/// Either assert (if the current Rust toolchain supports panicking in `const
570/// fn`) or evaluate the expression and, if it evaluates to `false`, call
571/// `const_panic!`. This is used in place of `assert!` in const contexts to
572/// accommodate old toolchains.
573macro_rules! const_assert {
574 ($e:expr) => {{
575 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
576 assert!($e);
577 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
578 {
579 let e = $e;
580 if !e {
581 let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e)));
582 }
583 }
584 }};
585 ($e:expr, $($args:tt)+) => {{
586 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
587 assert!($e, $($args)+);
588 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
589 {
590 let e = $e;
591 if !e {
592 let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e), ": ", stringify!($arg)), $($args)*);
593 }
594 }
595 }};
596}
597
598/// Like `const_assert!`, but relative to `debug_assert!`.
599macro_rules! const_debug_assert {
600 ($e:expr $(, $msg:expr)?) => {{
601 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
602 debug_assert!($e $(, $msg)?);
603 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
604 {
605 // Use this (rather than `#[cfg(debug_assertions)]`) to ensure that
606 // `$e` is always compiled even if it will never be evaluated at
607 // runtime.
608 if cfg!(debug_assertions) {
609 let e = $e;
610 if !e {
611 let _: () = const_panic!(@non_panic concat!("assertion failed: ", stringify!($e) $(, ": ", $msg)?));
612 }
613 }
614 }
615 }}
616}
617
618/// Either invoke `unreachable!()` or `loop {}` depending on whether the Rust
619/// toolchain supports panicking in `const fn`.
620macro_rules! const_unreachable {
621 () => {{
622 #[cfg(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0)]
623 unreachable!();
624
625 #[cfg(not(zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
626 loop {}
627 }};
628}
629
630/// Asserts at compile time that `$condition` is true for `Self` or the given
631/// `$tyvar`s. Unlike `const_assert`, this is *strictly* a compile-time check;
632/// it cannot be evaluated in a runtime context. The condition is checked after
633/// monomorphization and, upon failure, emits a compile error.
634macro_rules! static_assert {
635 (Self $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )? => $condition:expr $(, $args:tt)*) => {{
636 trait StaticAssert {
637 const ASSERT: bool;
638 }
639
640 impl<T $(: $(? $optbound +)* $($bound +)*)?> StaticAssert for T {
641 const ASSERT: bool = {
642 const_assert!($condition $(, $args)*);
643 $condition
644 };
645 }
646
647 const_assert!(<Self as StaticAssert>::ASSERT);
648 }};
649 ($($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* => $condition:expr $(, $args:tt)*) => {{
650 trait StaticAssert {
651 const ASSERT: bool;
652 }
653
654 // NOTE: We use `PhantomData` so we can support unsized types.
655 impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?,)*> StaticAssert for ($(core::marker::PhantomData<$tyvar>,)*) {
656 const ASSERT: bool = {
657 const_assert!($condition $(, $args)*);
658 $condition
659 };
660 }
661
662 const_assert!(<($(core::marker::PhantomData<$tyvar>,)*) as StaticAssert>::ASSERT);
663 }};
664}
665
666/// Assert at compile time that `tyvar` does not have a zero-sized DST
667/// component.
668macro_rules! static_assert_dst_is_not_zst {
669 ($tyvar:ident) => {{
670 use crate::KnownLayout;
671 static_assert!($tyvar: ?Sized + KnownLayout => {
672 let dst_is_zst = match $tyvar::LAYOUT.size_info {
673 crate::SizeInfo::Sized { .. } => false,
674 crate::SizeInfo::SliceDst(TrailingSliceLayout { elem_size, .. }) => {
675 elem_size == 0
676 }
677 };
678 !dst_is_zst
679 }, "cannot call this method on a dynamically-sized type whose trailing slice element is zero-sized");
680 }}
681}
682
683/// # Safety
684///
685/// The caller must ensure that the cast does not grow the size of the referent.
686/// Preserving or shrinking the size of the referent are both acceptable.
687macro_rules! cast {
688 ($p:expr) => {{
689 let ptr: crate::pointer::PtrInner<'_, _> = $p;
690 let ptr = ptr.as_non_null();
691 let ptr = ptr.as_ptr();
692 #[allow(clippy::as_conversions)]
693 let ptr = ptr as *mut _;
694 #[allow(unused_unsafe)]
695 // SAFETY: `NonNull::as_ptr` returns a non-null pointer, so the argument
696 // to `NonNull::new_unchecked` is also non-null.
697 let ptr = unsafe { core::ptr::NonNull::new_unchecked(ptr) };
698 // SAFETY: The caller promises that the cast preserves or shrinks
699 // referent size. By invariant on `$p: PtrInner` (guaranteed by type
700 // annotation above), `$p` refers to a byte range entirely contained
701 // inside of a single allocation, has provenance for that whole byte
702 // range, and will not outlive the allocation. All of these conditions
703 // are preserved when preserving or shrinking referent size.
704 crate::pointer::PtrInner::new(ptr)
705 }};
706}
707
708/// Implements `TransmuteFrom` and `SizeEq` for `T` and `$wrapper<T>`.
709///
710/// # Safety
711///
712/// `T` and `$wrapper<T>` must have the same bit validity, and must have the
713/// same size in the sense of `SizeEq`.
714macro_rules! unsafe_impl_for_transparent_wrapper {
715 (T $(: ?$optbound:ident)? => $wrapper:ident<T>) => {{
716 crate::util::macros::__unsafe();
717
718 use crate::pointer::{TransmuteFrom, PtrInner, SizeEq, invariant::Valid};
719
720 // SAFETY: The caller promises that `T` and `$wrapper<T>` have the same
721 // bit validity.
722 unsafe impl<T $(: ?$optbound)?> TransmuteFrom<T, Valid, Valid> for $wrapper<T> {}
723 // SAFETY: See previous safety comment.
724 unsafe impl<T $(: ?$optbound)?> TransmuteFrom<$wrapper<T>, Valid, Valid> for T {}
725 // SAFETY: The caller promises that `T` and `$wrapper<T>` satisfy
726 // `SizeEq`.
727 unsafe impl<T $(: ?$optbound)?> SizeEq<T> for $wrapper<T> {
728 #[inline(always)]
729 fn cast_from_raw(t: PtrInner<'_, T>) -> PtrInner<'_, $wrapper<T>> {
730 // SAFETY: See previous safety comment.
731 unsafe { cast!(t) }
732 }
733 }
734 // SAFETY: See previous safety comment.
735 unsafe impl<T $(: ?$optbound)?> SizeEq<$wrapper<T>> for T {
736 #[inline(always)]
737 fn cast_from_raw(t: PtrInner<'_, $wrapper<T>>) -> PtrInner<'_, T> {
738 // SAFETY: See previous safety comment.
739 unsafe { cast!(t) }
740 }
741 }
742 }};
743}
744
745macro_rules! impl_transitive_transmute_from {
746 ($($tyvar:ident $(: ?$optbound:ident)?)? => $t:ty => $u:ty => $v:ty) => {
747 const _: () = {
748 use crate::pointer::{TransmuteFrom, PtrInner, SizeEq, invariant::Valid};
749
750 // SAFETY: Since `$u: SizeEq<$t>` and `$v: SizeEq<U>`, this impl is
751 // transitively sound.
752 unsafe impl<$($tyvar $(: ?$optbound)?)?> SizeEq<$t> for $v
753 where
754 $u: SizeEq<$t>,
755 $v: SizeEq<$u>,
756 {
757 #[inline(always)]
758 fn cast_from_raw(t: PtrInner<'_, $t>) -> PtrInner<'_, $v> {
759 let u = <$u as SizeEq<_>>::cast_from_raw(t);
760 <$v as SizeEq<_>>::cast_from_raw(u)
761 }
762 }
763
764 // SAFETY: Since `$u: TransmuteFrom<$t, Valid, Valid>`, it is sound
765 // to transmute a bit-valid `$t` to a bit-valid `$u`. Since `$v:
766 // TransmuteFrom<$u, Valid, Valid>`, it is sound to transmute that
767 // bit-valid `$u` to a bit-valid `$v`.
768 unsafe impl<$($tyvar $(: ?$optbound)?)?> TransmuteFrom<$t, Valid, Valid> for $v
769 where
770 $u: TransmuteFrom<$t, Valid, Valid>,
771 $v: TransmuteFrom<$u, Valid, Valid>,
772 {}
773 };
774 };
775}
776
777#[rustfmt::skip]
778macro_rules! impl_size_eq {
779 ($t:ty, $u:ty) => {
780 const _: () = {
781 use crate::{KnownLayout, pointer::{PtrInner, SizeEq}};
782
783 static_assert!(=> {
784 let t = <$t as KnownLayout>::LAYOUT;
785 let u = <$u as KnownLayout>::LAYOUT;
786 t.align.get() >= u.align.get() && match (t.size_info, u.size_info) {
787 (SizeInfo::Sized { size: t }, SizeInfo::Sized { size: u }) => t == u,
788 (
789 SizeInfo::SliceDst(TrailingSliceLayout { offset: t_offset, elem_size: t_elem_size }),
790 SizeInfo::SliceDst(TrailingSliceLayout { offset: u_offset, elem_size: u_elem_size })
791 ) => t_offset == u_offset && t_elem_size == u_elem_size,
792 _ => false,
793 }
794 });
795
796 // SAFETY: See inline.
797 unsafe impl SizeEq<$t> for $u {
798 #[inline(always)]
799 fn cast_from_raw(t: PtrInner<'_, $t>) -> PtrInner<'_, $u> {
800 // SAFETY: We've asserted that their
801 // `KnownLayout::LAYOUT.size_info`s are equal, and so this
802 // cast is guaranteed to preserve address and referent size.
803 // It trivially preserves provenance.
804 unsafe { cast!(t) }
805 }
806 }
807 // SAFETY: See previous safety comment.
808 unsafe impl SizeEq<$u> for $t {
809 #[inline(always)]
810 fn cast_from_raw(u: PtrInner<'_, $u>) -> PtrInner<'_, $t> {
811 // SAFETY: See previous safety comment.
812 unsafe { cast!(u) }
813 }
814 }
815 };
816 };
817}
818
819/// Invokes `$blk` in a context in which `$src<$t>` and `$dst<$u>` implement
820/// `SizeEq`.
821///
822/// This macro emits code which implements `SizeEq`, and ensures that the impl
823/// is sound via PME.
824///
825/// # Safety
826///
827/// Inside of `$blk`, the caller must only use `$src` and `$dst` as `$src<$t>`
828/// and `$dst<$u>`. The caller must not use `$src` or `$dst` to wrap any other
829/// types.
830macro_rules! unsafe_with_size_eq {
831 (<$src:ident<$t:ident>, $dst:ident<$u:ident>> $blk:expr) => {{
832 crate::util::macros::__unsafe();
833
834 use crate::{KnownLayout, pointer::PtrInner};
835
836 #[repr(transparent)]
837 struct $src<T: ?Sized>(T);
838
839 #[repr(transparent)]
840 struct $dst<U: ?Sized>(U);
841
842 // SAFETY: Since `$src<T>` is a `#[repr(transparent)]` wrapper around
843 // `T`, it has the same bit validity and size as `T`.
844 unsafe_impl_for_transparent_wrapper!(T: ?Sized => $src<T>);
845
846 // SAFETY: Since `$dst<T>` is a `#[repr(transparent)]` wrapper around
847 // `T`, it has the same bit validity and size as `T`.
848 unsafe_impl_for_transparent_wrapper!(T: ?Sized => $dst<T>);
849
850 // SAFETY: `$src<T>` is a `#[repr(transparent)]` wrapper around `T` with
851 // no added semantics.
852 unsafe impl<T: ?Sized> InvariantsEq<$src<T>> for T {}
853
854 // SAFETY: `$dst<T>` is a `#[repr(transparent)]` wrapper around `T` with
855 // no added semantics.
856 unsafe impl<T: ?Sized> InvariantsEq<$dst<T>> for T {}
857
858 // SAFETY: See inline for the soundness of this impl when
859 // `cast_from_raw` is actually instantiated (otherwise, PMEs may not be
860 // triggered).
861 //
862 // We manually instantiate `cast_from_raw` below to ensure that this PME
863 // can be triggered, and the caller promises not to use `$src` and
864 // `$dst` with any wrapped types other than `$t` and `$u` respectively.
865 unsafe impl<T: ?Sized, U: ?Sized> SizeEq<$src<T>> for $dst<U>
866 where
867 T: KnownLayout<PointerMetadata = usize>,
868 U: KnownLayout<PointerMetadata = usize>,
869 {
870 fn cast_from_raw(src: PtrInner<'_, $src<T>>) -> PtrInner<'_, Self> {
871 // SAFETY: `crate::layout::cast_from_raw` promises to satisfy
872 // the safety invariants of `SizeEq::cast_from_raw`, or to
873 // generate a PME. Since `$src<T>` and `$dst<U>` are
874 // `#[repr(transparent)]` wrappers around `T` and `U`
875 // respectively, a `cast_from_raw` impl which satisfies the
876 // conditions for casting from `NonNull<T>` to `NonNull<U>` also
877 // satisfies the conditions for casting from `NonNull<$src<T>>`
878 // to `NonNull<$dst<U>>`.
879
880 // SAFETY: By the preceding safety comment, this cast preserves
881 // referent size.
882 let src: PtrInner<'_, T> = unsafe { cast!(src) };
883 let dst: PtrInner<'_, U> = crate::layout::cast_from_raw(src);
884 // SAFETY: By the preceding safety comment, this cast preserves
885 // referent size.
886 unsafe { cast!(dst) }
887 }
888 }
889
890 // See safety comment on the preceding `unsafe impl` block for an
891 // explanation of why we need this block.
892 if 1 == 0 {
893 let ptr = <$t as KnownLayout>::raw_dangling();
894 #[allow(unused_unsafe)]
895 // SAFETY: This call is never executed.
896 let ptr = unsafe { crate::pointer::PtrInner::new(ptr) };
897 #[allow(unused_unsafe)]
898 // SAFETY: This call is never executed.
899 let ptr = unsafe { cast!(ptr) };
900 let _ = <$dst<$u> as SizeEq<$src<$t>>>::cast_from_raw(ptr);
901 }
902
903 impl_for_transmute_from!(T: ?Sized + TryFromBytes => TryFromBytes for $src<T>[<T>]);
904 impl_for_transmute_from!(T: ?Sized + FromBytes => FromBytes for $src<T>[<T>]);
905 impl_for_transmute_from!(T: ?Sized + FromZeros => FromZeros for $src<T>[<T>]);
906 impl_for_transmute_from!(T: ?Sized + IntoBytes => IntoBytes for $src<T>[<T>]);
907
908 impl_for_transmute_from!(U: ?Sized + TryFromBytes => TryFromBytes for $dst<U>[<U>]);
909 impl_for_transmute_from!(U: ?Sized + FromBytes => FromBytes for $dst<U>[<U>]);
910 impl_for_transmute_from!(U: ?Sized + FromZeros => FromZeros for $dst<U>[<U>]);
911 impl_for_transmute_from!(U: ?Sized + IntoBytes => IntoBytes for $dst<U>[<U>]);
912
913 // SAFETY: `$src<T>` is a `#[repr(transparent)]` wrapper around `T`, and
914 // so permits interior mutation exactly when `T` does.
915 unsafe_impl!(T: ?Sized + Immutable => Immutable for $src<T>);
916
917 // SAFETY: `$dst<T>` is a `#[repr(transparent)]` wrapper around `T`, and
918 // so permits interior mutation exactly when `T` does.
919 unsafe_impl!(T: ?Sized + Immutable => Immutable for $dst<T>);
920
921 $blk
922 }};
923}
924
925/// A no-op `unsafe fn` for use in macro expansions.
926///
927/// Calling this function in a macro expansion ensures that the macro's caller
928/// must wrap the call in `unsafe { ... }`.
929pub(crate) const unsafe fn __unsafe() {}