zerocopy/util/macro_util.rs
1// Copyright 2022 The Fuchsia Authors
2//
3// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6// This file may not be copied, modified, or distributed except according to
7// those terms.
8
9//! Utilities used by macros and by `zerocopy-derive`.
10//!
11//! These are defined here `zerocopy` rather than in code generated by macros or
12//! by `zerocopy-derive` so that they can be compiled once rather than
13//! recompiled for every invocation (e.g., if they were defined in generated
14//! code, then deriving `IntoBytes` and `FromBytes` on three different types
15//! would result in the code in question being emitted and compiled six
16//! different times).
17
18#![allow(missing_debug_implementations)]
19
20use core::mem::{self, ManuallyDrop};
21
22// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
23// `cfg` when `size_of_val_raw` is stabilized.
24#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
25use core::ptr::{self, NonNull};
26
27use crate::{
28 pointer::invariant::{self, BecauseExclusive, BecauseImmutable, Invariants, ReadReason},
29 FromBytes, Immutable, IntoBytes, Ptr, TryFromBytes, ValidityError,
30};
31
32/// Projects the type of the field at `Index` in `Self`.
33///
34/// The `Index` parameter is any sort of handle that identifies the field; its
35/// definition is the obligation of the implementer.
36///
37/// # Safety
38///
39/// Unsafe code may assume that this accurately reflects the definition of
40/// `Self`.
41pub unsafe trait Field<Index> {
42 /// The type of the field at `Index`.
43 type Type: ?Sized;
44}
45
46#[cfg_attr(
47 zerocopy_diagnostic_on_unimplemented_1_78_0,
48 diagnostic::on_unimplemented(
49 message = "`{T}` has inter-field padding",
50 label = "types with padding cannot implement `IntoBytes`",
51 note = "consider using `zerocopy::Unalign` to lower the alignment of individual fields",
52 note = "consider adding explicit fields where padding would be",
53 note = "consider using `#[repr(packed)]` to remove inter-field padding"
54 )
55)]
56pub trait PaddingFree<T: ?Sized, const HAS_PADDING: bool> {}
57impl<T: ?Sized> PaddingFree<T, false> for () {}
58
59/// A type whose size is equal to `align_of::<T>()`.
60#[repr(C)]
61pub struct AlignOf<T> {
62 // This field ensures that:
63 // - The size is always at least 1 (the minimum possible alignment).
64 // - If the alignment is greater than 1, Rust has to round up to the next
65 // multiple of it in order to make sure that `Align`'s size is a multiple
66 // of that alignment. Without this field, its size could be 0, which is a
67 // valid multiple of any alignment.
68 _u: u8,
69 _a: [T; 0],
70}
71
72impl<T> AlignOf<T> {
73 #[inline(never)] // Make `missing_inline_in_public_items` happy.
74 #[cfg_attr(
75 all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
76 coverage(off)
77 )]
78 pub fn into_t(self) -> T {
79 unreachable!()
80 }
81}
82
83/// A type whose size is equal to `max(align_of::<T>(), align_of::<U>())`.
84#[repr(C)]
85pub union MaxAlignsOf<T, U> {
86 _t: ManuallyDrop<AlignOf<T>>,
87 _u: ManuallyDrop<AlignOf<U>>,
88}
89
90impl<T, U> MaxAlignsOf<T, U> {
91 #[inline(never)] // Make `missing_inline_in_public_items` happy.
92 #[cfg_attr(
93 all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
94 coverage(off)
95 )]
96 pub fn new(_t: T, _u: U) -> MaxAlignsOf<T, U> {
97 unreachable!()
98 }
99}
100
101#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
102const _64K: usize = 1 << 16;
103
104// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
105// `cfg` when `size_of_val_raw` is stabilized.
106#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
107#[repr(C, align(65536))]
108struct Aligned64kAllocation([u8; _64K]);
109
110/// A pointer to an aligned allocation of size 2^16.
111///
112/// # Safety
113///
114/// `ALIGNED_64K_ALLOCATION` is guaranteed to point to the entirety of an
115/// allocation with size and alignment 2^16, and to have valid provenance.
116// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
117// `cfg` when `size_of_val_raw` is stabilized.
118#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
119pub const ALIGNED_64K_ALLOCATION: NonNull<[u8]> = {
120 const REF: &Aligned64kAllocation = &Aligned64kAllocation([0; _64K]);
121 let ptr: *const Aligned64kAllocation = REF;
122 let ptr: *const [u8] = ptr::slice_from_raw_parts(ptr.cast(), _64K);
123 // SAFETY:
124 // - `ptr` is derived from a Rust reference, which is guaranteed to be
125 // non-null.
126 // - `ptr` is derived from an `&Aligned64kAllocation`, which has size and
127 // alignment `_64K` as promised. Its length is initialized to `_64K`,
128 // which means that it refers to the entire allocation.
129 // - `ptr` is derived from a Rust reference, which is guaranteed to have
130 // valid provenance.
131 //
132 // TODO(#429): Once `NonNull::new_unchecked` docs document that it preserves
133 // provenance, cite those docs.
134 // TODO: Replace this `as` with `ptr.cast_mut()` once our MSRV >= 1.65
135 #[allow(clippy::as_conversions)]
136 unsafe {
137 NonNull::new_unchecked(ptr as *mut _)
138 }
139};
140
141/// Computes the offset of the base of the field `$trailing_field_name` within
142/// the type `$ty`.
143///
144/// `trailing_field_offset!` produces code which is valid in a `const` context.
145// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
146// `cfg` when `size_of_val_raw` is stabilized.
147#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
148#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
149#[macro_export]
150macro_rules! trailing_field_offset {
151 ($ty:ty, $trailing_field_name:tt) => {{
152 let min_size = {
153 let zero_elems: *const [()] =
154 $crate::util::macro_util::core_reexport::ptr::slice_from_raw_parts(
155 // Work around https://github.com/rust-lang/rust-clippy/issues/12280
156 #[allow(clippy::incompatible_msrv)]
157 $crate::util::macro_util::core_reexport::ptr::NonNull::<()>::dangling()
158 .as_ptr()
159 .cast_const(),
160 0,
161 );
162 // SAFETY:
163 // - If `$ty` is `Sized`, `size_of_val_raw` is always safe to call.
164 // - Otherwise:
165 // - If `$ty` is not a slice DST, this pointer conversion will
166 // fail due to "mismatched vtable kinds", and compilation will
167 // fail.
168 // - If `$ty` is a slice DST, we have constructed `zero_elems` to
169 // have zero trailing slice elements. Per the `size_of_val_raw`
170 // docs, "For the special case where the dynamic tail length is
171 // 0, this function is safe to call." [1]
172 //
173 // [1] https://doc.rust-lang.org/nightly/std/mem/fn.size_of_val_raw.html
174 unsafe {
175 #[allow(clippy::as_conversions)]
176 $crate::util::macro_util::core_reexport::mem::size_of_val_raw(
177 zero_elems as *const $ty,
178 )
179 }
180 };
181
182 assert!(min_size <= _64K);
183
184 #[allow(clippy::as_conversions)]
185 let ptr = ALIGNED_64K_ALLOCATION.as_ptr() as *const $ty;
186
187 // SAFETY:
188 // - Thanks to the preceding `assert!`, we know that the value with zero
189 // elements fits in `_64K` bytes, and thus in the allocation addressed
190 // by `ALIGNED_64K_ALLOCATION`. The offset of the trailing field is
191 // guaranteed to be no larger than this size, so this field projection
192 // is guaranteed to remain in-bounds of its allocation.
193 // - Because the minimum size is no larger than `_64K` bytes, and
194 // because an object's size must always be a multiple of its alignment
195 // [1], we know that `$ty`'s alignment is no larger than `_64K`. The
196 // allocation addressed by `ALIGNED_64K_ALLOCATION` is guaranteed to
197 // be aligned to `_64K`, so `ptr` is guaranteed to satisfy `$ty`'s
198 // alignment.
199 // - As required by `addr_of!`, we do not write through `field`.
200 //
201 // Note that, as of [2], this requirement is technically unnecessary
202 // for Rust versions >= 1.75.0, but no harm in guaranteeing it anyway
203 // until we bump our MSRV.
204 //
205 // [1] Per https://doc.rust-lang.org/reference/type-layout.html:
206 //
207 // The size of a value is always a multiple of its alignment.
208 //
209 // [2] https://github.com/rust-lang/reference/pull/1387
210 let field = unsafe {
211 $crate::util::macro_util::core_reexport::ptr::addr_of!((*ptr).$trailing_field_name)
212 };
213 // SAFETY:
214 // - Both `ptr` and `field` are derived from the same allocated object.
215 // - By the preceding safety comment, `field` is in bounds of that
216 // allocated object.
217 // - The distance, in bytes, between `ptr` and `field` is required to be
218 // a multiple of the size of `u8`, which is trivially true because
219 // `u8`'s size is 1.
220 // - The distance, in bytes, cannot overflow `isize`. This is guaranteed
221 // because no allocated object can have a size larger than can fit in
222 // `isize`. [1]
223 // - The distance being in-bounds cannot rely on wrapping around the
224 // address space. This is guaranteed because the same is guaranteed of
225 // allocated objects. [1]
226 //
227 // [1] TODO(#429), TODO(https://github.com/rust-lang/rust/pull/116675):
228 // Once these are guaranteed in the Reference, cite it.
229 let offset = unsafe { field.cast::<u8>().offset_from(ptr.cast::<u8>()) };
230 // Guaranteed not to be lossy: `field` comes after `ptr`, so the offset
231 // from `ptr` to `field` is guaranteed to be positive.
232 assert!(offset >= 0);
233 Some(
234 #[allow(clippy::as_conversions)]
235 {
236 offset as usize
237 },
238 )
239 }};
240}
241
242/// Computes alignment of `$ty: ?Sized`.
243///
244/// `align_of!` produces code which is valid in a `const` context.
245// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this
246// `cfg` when `size_of_val_raw` is stabilized.
247#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
248#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
249#[macro_export]
250macro_rules! align_of {
251 ($ty:ty) => {{
252 // SAFETY: `OffsetOfTrailingIsAlignment` is `repr(C)`, and its layout is
253 // guaranteed [1] to begin with the single-byte layout for `_byte`,
254 // followed by the padding needed to align `_trailing`, then the layout
255 // for `_trailing`, and finally any trailing padding bytes needed to
256 // correctly-align the entire struct.
257 //
258 // This macro computes the alignment of `$ty` by counting the number of
259 // bytes preceeding `_trailing`. For instance, if the alignment of `$ty`
260 // is `1`, then no padding is required align `_trailing` and it will be
261 // located immediately after `_byte` at offset 1. If the alignment of
262 // `$ty` is 2, then a single padding byte is required before
263 // `_trailing`, and `_trailing` will be located at offset 2.
264
265 // This correspondence between offset and alignment holds for all valid
266 // Rust alignments, and we confirm this exhaustively (or, at least up to
267 // the maximum alignment supported by `trailing_field_offset!`) in
268 // `test_align_of_dst`.
269 //
270 // [1]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprc
271
272 #[repr(C)]
273 struct OffsetOfTrailingIsAlignment {
274 _byte: u8,
275 _trailing: $ty,
276 }
277
278 trailing_field_offset!(OffsetOfTrailingIsAlignment, _trailing)
279 }};
280}
281
282mod size_to_tag {
283 pub trait SizeToTag<const SIZE: usize> {
284 type Tag;
285 }
286
287 impl SizeToTag<1> for () {
288 type Tag = u8;
289 }
290 impl SizeToTag<2> for () {
291 type Tag = u16;
292 }
293 impl SizeToTag<4> for () {
294 type Tag = u32;
295 }
296 impl SizeToTag<8> for () {
297 type Tag = u64;
298 }
299 impl SizeToTag<16> for () {
300 type Tag = u128;
301 }
302}
303
304/// An alias for the unsigned integer of the given size in bytes.
305#[doc(hidden)]
306pub type SizeToTag<const SIZE: usize> = <() as size_to_tag::SizeToTag<SIZE>>::Tag;
307
308// We put `Sized` in its own module so it can have the same name as the standard
309// library `Sized` without shadowing it in the parent module.
310#[cfg(zerocopy_diagnostic_on_unimplemented_1_78_0)]
311mod __size_of {
312 #[diagnostic::on_unimplemented(
313 message = "`{Self}` is unsized",
314 label = "`IntoBytes` needs all field types to be `Sized` in order to determine whether there is inter-field padding",
315 note = "consider using `#[repr(packed)]` to remove inter-field padding",
316 note = "`IntoBytes` does not require the fields of `#[repr(packed)]` types to be `Sized`"
317 )]
318 pub trait Sized: core::marker::Sized {}
319 impl<T: core::marker::Sized> Sized for T {}
320
321 #[inline(always)]
322 #[must_use]
323 #[allow(clippy::needless_maybe_sized)]
324 pub const fn size_of<T: Sized + ?core::marker::Sized>() -> usize {
325 core::mem::size_of::<T>()
326 }
327}
328
329#[cfg(zerocopy_diagnostic_on_unimplemented_1_78_0)]
330pub use __size_of::size_of;
331#[cfg(not(zerocopy_diagnostic_on_unimplemented_1_78_0))]
332pub use core::mem::size_of;
333
334/// Does the struct type `$t` have padding?
335///
336/// `$ts` is the list of the type of every field in `$t`. `$t` must be a
337/// struct type, or else `struct_has_padding!`'s result may be meaningless.
338///
339/// Note that `struct_has_padding!`'s results are independent of `repcr` since
340/// they only consider the size of the type and the sizes of the fields.
341/// Whatever the repr, the size of the type already takes into account any
342/// padding that the compiler has decided to add. Structs with well-defined
343/// representations (such as `repr(C)`) can use this macro to check for padding.
344/// Note that while this may yield some consistent value for some `repr(Rust)`
345/// structs, it is not guaranteed across platforms or compilations.
346#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
347#[macro_export]
348macro_rules! struct_has_padding {
349 ($t:ty, [$($ts:ty),*]) => {
350 ::zerocopy::util::macro_util::size_of::<$t>() > 0 $(+ ::zerocopy::util::macro_util::size_of::<$ts>())*
351 };
352}
353
354/// Does the union type `$t` have padding?
355///
356/// `$ts` is the list of the type of every field in `$t`. `$t` must be a
357/// union type, or else `union_has_padding!`'s result may be meaningless.
358///
359/// Note that `union_has_padding!`'s results are independent of `repr` since
360/// they only consider the size of the type and the sizes of the fields.
361/// Whatever the repr, the size of the type already takes into account any
362/// padding that the compiler has decided to add. Unions with well-defined
363/// representations (such as `repr(C)`) can use this macro to check for padding.
364/// Note that while this may yield some consistent value for some `repr(Rust)`
365/// unions, it is not guaranteed across platforms or compilations.
366#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
367#[macro_export]
368macro_rules! union_has_padding {
369 ($t:ty, [$($ts:ty),*]) => {
370 false $(|| ::zerocopy::util::macro_util::size_of::<$t>() != ::zerocopy::util::macro_util::size_of::<$ts>())*
371 };
372}
373
374/// Does the enum type `$t` have padding?
375///
376/// `$disc` is the type of the enum tag, and `$ts` is a list of fields in each
377/// square-bracket-delimited variant. `$t` must be an enum, or else
378/// `enum_has_padding!`'s result may be meaningless. An enum has padding if any
379/// of its variant structs [1][2] contain padding, and so all of the variants of
380/// an enum must be "full" in order for the enum to not have padding.
381///
382/// The results of `enum_has_padding!` require that the enum is not
383/// `repr(Rust)`, as `repr(Rust)` enums may niche the enum's tag and reduce the
384/// total number of bytes required to represent the enum as a result. As long as
385/// the enum is `repr(C)`, `repr(int)`, or `repr(C, int)`, this will
386/// consistently return whether the enum contains any padding bytes.
387///
388/// [1]: https://doc.rust-lang.org/1.81.0/reference/type-layout.html#reprc-enums-with-fields
389/// [2]: https://doc.rust-lang.org/1.81.0/reference/type-layout.html#primitive-representation-of-enums-with-fields
390#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
391#[macro_export]
392macro_rules! enum_has_padding {
393 ($t:ty, $disc:ty, $([$($ts:ty),*]),*) => {
394 false $(
395 || ::zerocopy::util::macro_util::size_of::<$t>()
396 != (
397 ::zerocopy::util::macro_util::size_of::<$disc>()
398 $(+ ::zerocopy::util::macro_util::size_of::<$ts>())*
399 )
400 )*
401 }
402}
403
404/// Does `t` have alignment greater than or equal to `u`? If not, this macro
405/// produces a compile error. It must be invoked in a dead codepath. This is
406/// used in `transmute_ref!` and `transmute_mut!`.
407#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
408#[macro_export]
409macro_rules! assert_align_gt_eq {
410 ($t:ident, $u: ident) => {{
411 // The comments here should be read in the context of this macro's
412 // invocations in `transmute_ref!` and `transmute_mut!`.
413 if false {
414 // The type wildcard in this bound is inferred to be `T` because
415 // `align_of.into_t()` is assigned to `t` (which has type `T`).
416 let align_of: $crate::util::macro_util::AlignOf<_> = unreachable!();
417 $t = align_of.into_t();
418 // `max_aligns` is inferred to have type `MaxAlignsOf<T, U>` because
419 // of the inferred types of `t` and `u`.
420 let mut max_aligns = $crate::util::macro_util::MaxAlignsOf::new($t, $u);
421
422 // This transmute will only compile successfully if
423 // `align_of::<T>() == max(align_of::<T>(), align_of::<U>())` - in
424 // other words, if `align_of::<T>() >= align_of::<U>()`.
425 //
426 // SAFETY: This code is never run.
427 max_aligns = unsafe {
428 // Clippy: We can't annotate the types; this macro is designed
429 // to infer the types from the calling context.
430 #[allow(clippy::missing_transmute_annotations)]
431 $crate::util::macro_util::core_reexport::mem::transmute(align_of)
432 };
433 } else {
434 loop {}
435 }
436 }};
437}
438
439/// Do `t` and `u` have the same size? If not, this macro produces a compile
440/// error. It must be invoked in a dead codepath. This is used in
441/// `transmute_ref!` and `transmute_mut!`.
442#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`.
443#[macro_export]
444macro_rules! assert_size_eq {
445 ($t:ident, $u: ident) => {{
446 // The comments here should be read in the context of this macro's
447 // invocations in `transmute_ref!` and `transmute_mut!`.
448 if false {
449 // SAFETY: This code is never run.
450 $u = unsafe {
451 // Clippy:
452 // - It's okay to transmute a type to itself.
453 // - We can't annotate the types; this macro is designed to
454 // infer the types from the calling context.
455 #[allow(clippy::useless_transmute, clippy::missing_transmute_annotations)]
456 $crate::util::macro_util::core_reexport::mem::transmute($t)
457 };
458 } else {
459 loop {}
460 }
461 }};
462}
463
464/// Transmutes a reference of one type to a reference of another type.
465///
466/// # Safety
467///
468/// The caller must guarantee that:
469/// - `Src: IntoBytes + Immutable`
470/// - `Dst: FromBytes + Immutable`
471/// - `size_of::<Src>() == size_of::<Dst>()`
472/// - `align_of::<Src>() >= align_of::<Dst>()`
473#[inline(always)]
474pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>(
475 src: &'src Src,
476) -> &'dst Dst {
477 let src: *const Src = src;
478 let dst = src.cast::<Dst>();
479 // SAFETY:
480 // - We know that it is sound to view the target type of the input reference
481 // (`Src`) as the target type of the output reference (`Dst`) because the
482 // caller has guaranteed that `Src: IntoBytes`, `Dst: FromBytes`, and
483 // `size_of::<Src>() == size_of::<Dst>()`.
484 // - We know that there are no `UnsafeCell`s, and thus we don't have to
485 // worry about `UnsafeCell` overlap, because `Src: Immutable` and `Dst:
486 // Immutable`.
487 // - The caller has guaranteed that alignment is not increased.
488 // - We know that the returned lifetime will not outlive the input lifetime
489 // thanks to the lifetime bounds on this function.
490 //
491 // TODO(#67): Once our MSRV is 1.58, replace this `transmute` with `&*dst`.
492 #[allow(clippy::transmute_ptr_to_ref)]
493 unsafe {
494 mem::transmute(dst)
495 }
496}
497
498/// Transmutes a mutable reference of one type to a mutable reference of another
499/// type.
500///
501/// # Safety
502///
503/// The caller must guarantee that:
504/// - `Src: FromBytes + IntoBytes`
505/// - `Dst: FromBytes + IntoBytes`
506/// - `size_of::<Src>() == size_of::<Dst>()`
507/// - `align_of::<Src>() >= align_of::<Dst>()`
508// TODO(#686): Consider removing the `Immutable` requirement.
509#[inline(always)]
510pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>(
511 src: &'src mut Src,
512) -> &'dst mut Dst {
513 let src: *mut Src = src;
514 let dst = src.cast::<Dst>();
515 // SAFETY:
516 // - We know that it is sound to view the target type of the input reference
517 // (`Src`) as the target type of the output reference (`Dst`) and
518 // vice-versa because the caller has guaranteed that `Src: FromBytes +
519 // IntoBytes`, `Dst: FromBytes + IntoBytes`, and `size_of::<Src>() ==
520 // size_of::<Dst>()`.
521 // - The caller has guaranteed that alignment is not increased.
522 // - We know that the returned lifetime will not outlive the input lifetime
523 // thanks to the lifetime bounds on this function.
524 unsafe { &mut *dst }
525}
526
527/// Is a given source a valid instance of `Dst`?
528///
529/// If so, returns `src` casted to a `Ptr<Dst, _>`. Otherwise returns `None`.
530///
531/// # Safety
532///
533/// Unsafe code may assume that, if `try_cast_or_pme(src)` returns `Ok`,
534/// `*src` is a bit-valid instance of `Dst`, and that the size of `Src` is
535/// greater than or equal to the size of `Dst`.
536///
537/// Unsafe code may assume that, if `try_cast_or_pme(src)` returns `Err`, the
538/// encapsulated `Ptr` value is the original `src`. `try_cast_or_pme` cannot
539/// guarantee that the referent has not been modified, as it calls user-defined
540/// code (`TryFromBytes::is_bit_valid`).
541///
542/// # Panics
543///
544/// `try_cast_or_pme` may either produce a post-monomorphization error or a
545/// panic if `Dst` not the same size as `Src`. Otherwise, `try_cast_or_pme`
546/// panics under the same circumstances as [`is_bit_valid`].
547///
548/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
549#[doc(hidden)]
550#[inline]
551fn try_cast_or_pme<Src, Dst, I, R>(
552 src: Ptr<'_, Src, I>,
553) -> Result<
554 Ptr<'_, Dst, (I::Aliasing, invariant::Unaligned, invariant::Valid)>,
555 ValidityError<Ptr<'_, Src, I>, Dst>,
556>
557where
558 // TODO(#2226): There should be a `Src: FromBytes` bound here, but doing so
559 // requires deeper surgery.
560 Src: invariant::Read<I::Aliasing, R>,
561 Dst: TryFromBytes + invariant::Read<I::Aliasing, R>,
562 I: Invariants<Validity = invariant::Initialized>,
563 I::Aliasing: invariant::Reference,
564 R: ReadReason,
565{
566 static_assert!(Src, Dst => mem::size_of::<Dst>() == mem::size_of::<Src>());
567
568 // SAFETY: This is a pointer cast, satisfying the following properties:
569 // - `p as *mut Dst` addresses a subset of the `bytes` addressed by `src`,
570 // because we assert above that the size of `Dst` equal to the size of
571 // `Src`.
572 // - `p as *mut Dst` is a provenance-preserving cast
573 #[allow(clippy::as_conversions)]
574 let c_ptr = unsafe { src.cast_unsized(|p| p as *mut Dst) };
575
576 match c_ptr.try_into_valid() {
577 Ok(ptr) => Ok(ptr),
578 Err(err) => {
579 // Re-cast `Ptr<Dst>` to `Ptr<Src>`.
580 let ptr = err.into_src();
581 // SAFETY: This is a pointer cast, satisfying the following
582 // properties:
583 // - `p as *mut Src` addresses a subset of the `bytes` addressed by
584 // `ptr`, because we assert above that the size of `Dst` is equal
585 // to the size of `Src`.
586 // - `p as *mut Src` is a provenance-preserving cast
587 #[allow(clippy::as_conversions)]
588 let ptr = unsafe { ptr.cast_unsized(|p| p as *mut Src) };
589 // SAFETY: `ptr` is `src`, and has the same alignment invariant.
590 let ptr = unsafe { ptr.assume_alignment::<I::Alignment>() };
591 // SAFETY: `ptr` is `src` and has the same validity invariant.
592 let ptr = unsafe { ptr.assume_validity::<I::Validity>() };
593 Err(ValidityError::new(ptr.unify_invariants()))
594 }
595 }
596}
597
598/// Attempts to transmute `Src` into `Dst`.
599///
600/// A helper for `try_transmute!`.
601///
602/// # Panics
603///
604/// `try_transmute` may either produce a post-monomorphization error or a panic
605/// if `Dst` is bigger than `Src`. Otherwise, `try_transmute` panics under the
606/// same circumstances as [`is_bit_valid`].
607///
608/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
609#[inline(always)]
610pub fn try_transmute<Src, Dst>(src: Src) -> Result<Dst, ValidityError<Src, Dst>>
611where
612 Src: IntoBytes,
613 Dst: TryFromBytes,
614{
615 static_assert!(Src, Dst => mem::size_of::<Dst>() == mem::size_of::<Src>());
616
617 let mu_src = mem::MaybeUninit::new(src);
618 // SAFETY: By invariant on `&`, the following are satisfied:
619 // - `&mu_src` is valid for reads
620 // - `&mu_src` is properly aligned
621 // - `&mu_src`'s referent is bit-valid
622 let mu_src_copy = unsafe { core::ptr::read(&mu_src) };
623 // SAFETY: `MaybeUninit` has no validity constraints.
624 let mut mu_dst: mem::MaybeUninit<Dst> =
625 unsafe { crate::util::transmute_unchecked(mu_src_copy) };
626
627 let ptr = Ptr::from_mut(&mut mu_dst);
628
629 // SAFETY: Since `Src: IntoBytes`, and since `size_of::<Src>() ==
630 // size_of::<Dst>()` by the preceding assertion, all of `mu_dst`'s bytes are
631 // initialized.
632 let ptr = unsafe { ptr.assume_validity::<invariant::Initialized>() };
633
634 // SAFETY: `MaybeUninit<T>` and `T` have the same size [1], so this cast
635 // preserves the referent's size. This cast preserves provenance.
636 //
637 // [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
638 //
639 // `MaybeUninit<T>` is guaranteed to have the same size, alignment, and
640 // ABI as `T`
641 let ptr: Ptr<'_, Dst, _> =
642 unsafe { ptr.cast_unsized(|mu: *mut mem::MaybeUninit<Dst>| mu.cast()) };
643
644 if Dst::is_bit_valid(ptr.forget_aligned()) {
645 // SAFETY: Since `Dst::is_bit_valid`, we know that `ptr`'s referent is
646 // bit-valid for `Dst`. `ptr` points to `mu_dst`, and no intervening
647 // operations have mutated it, so it is a bit-valid `Dst`.
648 Ok(unsafe { mu_dst.assume_init() })
649 } else {
650 // SAFETY: `mu_src` was constructed from `src` and never modified, so it
651 // is still bit-valid.
652 Err(ValidityError::new(unsafe { mu_src.assume_init() }))
653 }
654}
655
656/// Attempts to transmute `&Src` into `&Dst`.
657///
658/// A helper for `try_transmute_ref!`.
659///
660/// # Panics
661///
662/// `try_transmute_ref` may either produce a post-monomorphization error or a
663/// panic if `Dst` is bigger or has a stricter alignment requirement than `Src`.
664/// Otherwise, `try_transmute_ref` panics under the same circumstances as
665/// [`is_bit_valid`].
666///
667/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
668#[inline(always)]
669pub fn try_transmute_ref<Src, Dst>(src: &Src) -> Result<&Dst, ValidityError<&Src, Dst>>
670where
671 Src: IntoBytes + Immutable,
672 Dst: TryFromBytes + Immutable,
673{
674 let ptr = Ptr::from_ref(src);
675 let ptr = ptr.bikeshed_recall_initialized_immutable();
676 match try_cast_or_pme::<Src, Dst, _, BecauseImmutable>(ptr) {
677 Ok(ptr) => {
678 static_assert!(Src, Dst => mem::align_of::<Dst>() <= mem::align_of::<Src>());
679 // SAFETY: We have checked that `Dst` does not have a stricter
680 // alignment requirement than `Src`.
681 let ptr = unsafe { ptr.assume_alignment::<invariant::Aligned>() };
682 Ok(ptr.as_ref())
683 }
684 Err(err) => Err(err.map_src(|ptr| {
685 // SAFETY: Because `Src: Immutable` and we create a `Ptr` via
686 // `Ptr::from_ref`, the resulting `Ptr` is a shared-and-`Immutable`
687 // `Ptr`, which does not permit mutation of its referent. Therefore,
688 // no mutation could have happened during the call to
689 // `try_cast_or_pme` (any such mutation would be unsound).
690 //
691 // `try_cast_or_pme` promises to return its original argument, and
692 // so we know that we are getting back the same `ptr` that we
693 // originally passed, and that `ptr` was a bit-valid `Src`.
694 let ptr = unsafe { ptr.assume_valid() };
695 ptr.as_ref()
696 })),
697 }
698}
699
700/// Attempts to transmute `&mut Src` into `&mut Dst`.
701///
702/// A helper for `try_transmute_mut!`.
703///
704/// # Panics
705///
706/// `try_transmute_mut` may either produce a post-monomorphization error or a
707/// panic if `Dst` is bigger or has a stricter alignment requirement than `Src`.
708/// Otherwise, `try_transmute_mut` panics under the same circumstances as
709/// [`is_bit_valid`].
710///
711/// [`is_bit_valid`]: TryFromBytes::is_bit_valid
712#[inline(always)]
713pub fn try_transmute_mut<Src, Dst>(src: &mut Src) -> Result<&mut Dst, ValidityError<&mut Src, Dst>>
714where
715 Src: FromBytes + IntoBytes,
716 Dst: TryFromBytes + IntoBytes,
717{
718 let ptr = Ptr::from_mut(src);
719 let ptr = ptr.bikeshed_recall_initialized_from_bytes();
720 match try_cast_or_pme::<Src, Dst, _, BecauseExclusive>(ptr) {
721 Ok(ptr) => {
722 static_assert!(Src, Dst => mem::align_of::<Dst>() <= mem::align_of::<Src>());
723 // SAFETY: We have checked that `Dst` does not have a stricter
724 // alignment requirement than `Src`.
725 let ptr = unsafe { ptr.assume_alignment::<invariant::Aligned>() };
726 Ok(ptr.as_mut())
727 }
728 Err(err) => Err(err.map_src(|ptr| ptr.bikeshed_recall_valid().as_mut())),
729 }
730}
731
732/// A function which emits a warning if its return value is not used.
733#[must_use]
734#[inline(always)]
735pub const fn must_use<T>(t: T) -> T {
736 t
737}
738
739// NOTE: We can't change this to a `pub use core as core_reexport` until [1] is
740// fixed or we update to a semver-breaking version (as of this writing, 0.8.0)
741// on the `main` branch.
742//
743// [1] https://github.com/obi1kenobi/cargo-semver-checks/issues/573
744pub mod core_reexport {
745 pub use core::*;
746
747 pub mod mem {
748 pub use core::mem::*;
749 }
750}
751
752#[cfg(test)]
753mod tests {
754 use super::*;
755 use crate::util::testutil::*;
756
757 #[test]
758 fn test_align_of() {
759 macro_rules! test {
760 ($ty:ty) => {
761 assert_eq!(mem::size_of::<AlignOf<$ty>>(), mem::align_of::<$ty>());
762 };
763 }
764
765 test!(());
766 test!(u8);
767 test!(AU64);
768 test!([AU64; 2]);
769 }
770
771 #[test]
772 fn test_max_aligns_of() {
773 macro_rules! test {
774 ($t:ty, $u:ty) => {
775 assert_eq!(
776 mem::size_of::<MaxAlignsOf<$t, $u>>(),
777 core::cmp::max(mem::align_of::<$t>(), mem::align_of::<$u>())
778 );
779 };
780 }
781
782 test!(u8, u8);
783 test!(u8, AU64);
784 test!(AU64, u8);
785 }
786
787 #[test]
788 fn test_typed_align_check() {
789 // Test that the type-based alignment check used in
790 // `assert_align_gt_eq!` behaves as expected.
791
792 macro_rules! assert_t_align_gteq_u_align {
793 ($t:ty, $u:ty, $gteq:expr) => {
794 assert_eq!(
795 mem::size_of::<MaxAlignsOf<$t, $u>>() == mem::size_of::<AlignOf<$t>>(),
796 $gteq
797 );
798 };
799 }
800
801 assert_t_align_gteq_u_align!(u8, u8, true);
802 assert_t_align_gteq_u_align!(AU64, AU64, true);
803 assert_t_align_gteq_u_align!(AU64, u8, true);
804 assert_t_align_gteq_u_align!(u8, AU64, false);
805 }
806
807 // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove
808 // this `cfg` when `size_of_val_raw` is stabilized.
809 #[allow(clippy::decimal_literal_representation)]
810 #[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
811 #[test]
812 fn test_trailing_field_offset() {
813 assert_eq!(mem::align_of::<Aligned64kAllocation>(), _64K);
814
815 macro_rules! test {
816 (#[$cfg:meta] ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {{
817 #[$cfg]
818 struct Test($(#[allow(dead_code)] $ts,)* #[allow(dead_code)] $trailing_field_ty);
819 assert_eq!(test!(@offset $($ts),* ; $trailing_field_ty), $expect);
820 }};
821 (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {
822 test!(#[$cfg] ($($ts),* ; $trailing_field_ty) => $expect);
823 test!($(#[$cfgs])* ($($ts),* ; $trailing_field_ty) => $expect);
824 };
825 (@offset ; $_trailing:ty) => { trailing_field_offset!(Test, 0) };
826 (@offset $_t:ty ; $_trailing:ty) => { trailing_field_offset!(Test, 1) };
827 }
828
829 test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; u8) => Some(0));
830 test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; [u8]) => Some(0));
831 test!(#[repr(C)] #[repr(C, packed)] (u8; u8) => Some(1));
832 test!(#[repr(C)] (; AU64) => Some(0));
833 test!(#[repr(C)] (; [AU64]) => Some(0));
834 test!(#[repr(C)] (u8; AU64) => Some(8));
835 test!(#[repr(C)] (u8; [AU64]) => Some(8));
836 test!(#[repr(C)] (; Nested<u8, AU64>) => Some(0));
837 test!(#[repr(C)] (; Nested<u8, [AU64]>) => Some(0));
838 test!(#[repr(C)] (u8; Nested<u8, AU64>) => Some(8));
839 test!(#[repr(C)] (u8; Nested<u8, [AU64]>) => Some(8));
840
841 // Test that `packed(N)` limits the offset of the trailing field.
842 test!(#[repr(C, packed( 1))] (u8; elain::Align< 2>) => Some( 1));
843 test!(#[repr(C, packed( 2))] (u8; elain::Align< 4>) => Some( 2));
844 test!(#[repr(C, packed( 4))] (u8; elain::Align< 8>) => Some( 4));
845 test!(#[repr(C, packed( 8))] (u8; elain::Align< 16>) => Some( 8));
846 test!(#[repr(C, packed( 16))] (u8; elain::Align< 32>) => Some( 16));
847 test!(#[repr(C, packed( 32))] (u8; elain::Align< 64>) => Some( 32));
848 test!(#[repr(C, packed( 64))] (u8; elain::Align< 128>) => Some( 64));
849 test!(#[repr(C, packed( 128))] (u8; elain::Align< 256>) => Some( 128));
850 test!(#[repr(C, packed( 256))] (u8; elain::Align< 512>) => Some( 256));
851 test!(#[repr(C, packed( 512))] (u8; elain::Align< 1024>) => Some( 512));
852 test!(#[repr(C, packed( 1024))] (u8; elain::Align< 2048>) => Some( 1024));
853 test!(#[repr(C, packed( 2048))] (u8; elain::Align< 4096>) => Some( 2048));
854 test!(#[repr(C, packed( 4096))] (u8; elain::Align< 8192>) => Some( 4096));
855 test!(#[repr(C, packed( 8192))] (u8; elain::Align< 16384>) => Some( 8192));
856 test!(#[repr(C, packed( 16384))] (u8; elain::Align< 32768>) => Some( 16384));
857 test!(#[repr(C, packed( 32768))] (u8; elain::Align< 65536>) => Some( 32768));
858 test!(#[repr(C, packed( 65536))] (u8; elain::Align< 131072>) => Some( 65536));
859 /* Alignments above 65536 are not yet supported.
860 test!(#[repr(C, packed( 131072))] (u8; elain::Align< 262144>) => Some( 131072));
861 test!(#[repr(C, packed( 262144))] (u8; elain::Align< 524288>) => Some( 262144));
862 test!(#[repr(C, packed( 524288))] (u8; elain::Align< 1048576>) => Some( 524288));
863 test!(#[repr(C, packed( 1048576))] (u8; elain::Align< 2097152>) => Some( 1048576));
864 test!(#[repr(C, packed( 2097152))] (u8; elain::Align< 4194304>) => Some( 2097152));
865 test!(#[repr(C, packed( 4194304))] (u8; elain::Align< 8388608>) => Some( 4194304));
866 test!(#[repr(C, packed( 8388608))] (u8; elain::Align< 16777216>) => Some( 8388608));
867 test!(#[repr(C, packed( 16777216))] (u8; elain::Align< 33554432>) => Some( 16777216));
868 test!(#[repr(C, packed( 33554432))] (u8; elain::Align< 67108864>) => Some( 33554432));
869 test!(#[repr(C, packed( 67108864))] (u8; elain::Align< 33554432>) => Some( 67108864));
870 test!(#[repr(C, packed( 33554432))] (u8; elain::Align<134217728>) => Some( 33554432));
871 test!(#[repr(C, packed(134217728))] (u8; elain::Align<268435456>) => Some(134217728));
872 test!(#[repr(C, packed(268435456))] (u8; elain::Align<268435456>) => Some(268435456));
873 */
874
875 // Test that `align(N)` does not limit the offset of the trailing field.
876 test!(#[repr(C, align( 1))] (u8; elain::Align< 2>) => Some( 2));
877 test!(#[repr(C, align( 2))] (u8; elain::Align< 4>) => Some( 4));
878 test!(#[repr(C, align( 4))] (u8; elain::Align< 8>) => Some( 8));
879 test!(#[repr(C, align( 8))] (u8; elain::Align< 16>) => Some( 16));
880 test!(#[repr(C, align( 16))] (u8; elain::Align< 32>) => Some( 32));
881 test!(#[repr(C, align( 32))] (u8; elain::Align< 64>) => Some( 64));
882 test!(#[repr(C, align( 64))] (u8; elain::Align< 128>) => Some( 128));
883 test!(#[repr(C, align( 128))] (u8; elain::Align< 256>) => Some( 256));
884 test!(#[repr(C, align( 256))] (u8; elain::Align< 512>) => Some( 512));
885 test!(#[repr(C, align( 512))] (u8; elain::Align< 1024>) => Some( 1024));
886 test!(#[repr(C, align( 1024))] (u8; elain::Align< 2048>) => Some( 2048));
887 test!(#[repr(C, align( 2048))] (u8; elain::Align< 4096>) => Some( 4096));
888 test!(#[repr(C, align( 4096))] (u8; elain::Align< 8192>) => Some( 8192));
889 test!(#[repr(C, align( 8192))] (u8; elain::Align< 16384>) => Some( 16384));
890 test!(#[repr(C, align( 16384))] (u8; elain::Align< 32768>) => Some( 32768));
891 test!(#[repr(C, align( 32768))] (u8; elain::Align< 65536>) => Some( 65536));
892 /* Alignments above 65536 are not yet supported.
893 test!(#[repr(C, align( 65536))] (u8; elain::Align< 131072>) => Some( 131072));
894 test!(#[repr(C, align( 131072))] (u8; elain::Align< 262144>) => Some( 262144));
895 test!(#[repr(C, align( 262144))] (u8; elain::Align< 524288>) => Some( 524288));
896 test!(#[repr(C, align( 524288))] (u8; elain::Align< 1048576>) => Some( 1048576));
897 test!(#[repr(C, align( 1048576))] (u8; elain::Align< 2097152>) => Some( 2097152));
898 test!(#[repr(C, align( 2097152))] (u8; elain::Align< 4194304>) => Some( 4194304));
899 test!(#[repr(C, align( 4194304))] (u8; elain::Align< 8388608>) => Some( 8388608));
900 test!(#[repr(C, align( 8388608))] (u8; elain::Align< 16777216>) => Some( 16777216));
901 test!(#[repr(C, align( 16777216))] (u8; elain::Align< 33554432>) => Some( 33554432));
902 test!(#[repr(C, align( 33554432))] (u8; elain::Align< 67108864>) => Some( 67108864));
903 test!(#[repr(C, align( 67108864))] (u8; elain::Align< 33554432>) => Some( 33554432));
904 test!(#[repr(C, align( 33554432))] (u8; elain::Align<134217728>) => Some(134217728));
905 test!(#[repr(C, align(134217728))] (u8; elain::Align<268435456>) => Some(268435456));
906 */
907 }
908
909 // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove
910 // this `cfg` when `size_of_val_raw` is stabilized.
911 #[allow(clippy::decimal_literal_representation)]
912 #[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
913 #[test]
914 fn test_align_of_dst() {
915 // Test that `align_of!` correctly computes the alignment of DSTs.
916 assert_eq!(align_of!([elain::Align<1>]), Some(1));
917 assert_eq!(align_of!([elain::Align<2>]), Some(2));
918 assert_eq!(align_of!([elain::Align<4>]), Some(4));
919 assert_eq!(align_of!([elain::Align<8>]), Some(8));
920 assert_eq!(align_of!([elain::Align<16>]), Some(16));
921 assert_eq!(align_of!([elain::Align<32>]), Some(32));
922 assert_eq!(align_of!([elain::Align<64>]), Some(64));
923 assert_eq!(align_of!([elain::Align<128>]), Some(128));
924 assert_eq!(align_of!([elain::Align<256>]), Some(256));
925 assert_eq!(align_of!([elain::Align<512>]), Some(512));
926 assert_eq!(align_of!([elain::Align<1024>]), Some(1024));
927 assert_eq!(align_of!([elain::Align<2048>]), Some(2048));
928 assert_eq!(align_of!([elain::Align<4096>]), Some(4096));
929 assert_eq!(align_of!([elain::Align<8192>]), Some(8192));
930 assert_eq!(align_of!([elain::Align<16384>]), Some(16384));
931 assert_eq!(align_of!([elain::Align<32768>]), Some(32768));
932 assert_eq!(align_of!([elain::Align<65536>]), Some(65536));
933 /* Alignments above 65536 are not yet supported.
934 assert_eq!(align_of!([elain::Align<131072>]), Some(131072));
935 assert_eq!(align_of!([elain::Align<262144>]), Some(262144));
936 assert_eq!(align_of!([elain::Align<524288>]), Some(524288));
937 assert_eq!(align_of!([elain::Align<1048576>]), Some(1048576));
938 assert_eq!(align_of!([elain::Align<2097152>]), Some(2097152));
939 assert_eq!(align_of!([elain::Align<4194304>]), Some(4194304));
940 assert_eq!(align_of!([elain::Align<8388608>]), Some(8388608));
941 assert_eq!(align_of!([elain::Align<16777216>]), Some(16777216));
942 assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432));
943 assert_eq!(align_of!([elain::Align<67108864>]), Some(67108864));
944 assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432));
945 assert_eq!(align_of!([elain::Align<134217728>]), Some(134217728));
946 assert_eq!(align_of!([elain::Align<268435456>]), Some(268435456));
947 */
948 }
949
950 #[test]
951 fn test_enum_casts() {
952 // Test that casting the variants of enums with signed integer reprs to
953 // unsigned integers obeys expected signed -> unsigned casting rules.
954
955 #[repr(i8)]
956 enum ReprI8 {
957 MinusOne = -1,
958 Zero = 0,
959 Min = i8::MIN,
960 Max = i8::MAX,
961 }
962
963 #[allow(clippy::as_conversions)]
964 let x = ReprI8::MinusOne as u8;
965 assert_eq!(x, u8::MAX);
966
967 #[allow(clippy::as_conversions)]
968 let x = ReprI8::Zero as u8;
969 assert_eq!(x, 0);
970
971 #[allow(clippy::as_conversions)]
972 let x = ReprI8::Min as u8;
973 assert_eq!(x, 128);
974
975 #[allow(clippy::as_conversions)]
976 let x = ReprI8::Max as u8;
977 assert_eq!(x, 127);
978 }
979
980 #[test]
981 fn test_struct_has_padding() {
982 // Test that, for each provided repr, `struct_has_padding!` reports the
983 // expected value.
984 macro_rules! test {
985 (#[$cfg:meta] ($($ts:ty),*) => $expect:expr) => {{
986 #[$cfg]
987 struct Test($(#[allow(dead_code)] $ts),*);
988 assert_eq!(struct_has_padding!(Test, [$($ts),*]), $expect);
989 }};
990 (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),*) => $expect:expr) => {
991 test!(#[$cfg] ($($ts),*) => $expect);
992 test!($(#[$cfgs])* ($($ts),*) => $expect);
993 };
994 }
995
996 test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] () => false);
997 test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8) => false);
998 test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8, ()) => false);
999 test!(#[repr(C)] #[repr(packed)] (u8, u8) => false);
1000
1001 test!(#[repr(C)] (u8, AU64) => true);
1002 // Rust won't let you put `#[repr(packed)]` on a type which contains a
1003 // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here.
1004 // It's not ideal, but it definitely has align > 1 on /some/ of our CI
1005 // targets, and this isn't a particularly complex macro we're testing
1006 // anyway.
1007 test!(#[repr(packed)] (u8, u64) => false);
1008 }
1009
1010 #[test]
1011 fn test_union_has_padding() {
1012 // Test that, for each provided repr, `union_has_padding!` reports the
1013 // expected value.
1014 macro_rules! test {
1015 (#[$cfg:meta] {$($fs:ident: $ts:ty),*} => $expect:expr) => {{
1016 #[$cfg]
1017 #[allow(unused)] // fields are never read
1018 union Test{ $($fs: $ts),* }
1019 assert_eq!(union_has_padding!(Test, [$($ts),*]), $expect);
1020 }};
1021 (#[$cfg:meta] $(#[$cfgs:meta])* {$($fs:ident: $ts:ty),*} => $expect:expr) => {
1022 test!(#[$cfg] {$($fs: $ts),*} => $expect);
1023 test!($(#[$cfgs])* {$($fs: $ts),*} => $expect);
1024 };
1025 }
1026
1027 test!(#[repr(C)] #[repr(packed)] {a: u8} => false);
1028 test!(#[repr(C)] #[repr(packed)] {a: u8, b: u8} => false);
1029
1030 // Rust won't let you put `#[repr(packed)]` on a type which contains a
1031 // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here.
1032 // It's not ideal, but it definitely has align > 1 on /some/ of our CI
1033 // targets, and this isn't a particularly complex macro we're testing
1034 // anyway.
1035 test!(#[repr(C)] #[repr(packed)] {a: u8, b: u64} => true);
1036 }
1037
1038 #[test]
1039 fn test_enum_has_padding() {
1040 // Test that, for each provided repr, `enum_has_padding!` reports the
1041 // expected value.
1042 macro_rules! test {
1043 (#[repr($disc:ident $(, $c:ident)?)] { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {
1044 test!(@case #[repr($disc $(, $c)?)] { $($vs ($($ts),*),)* } => $expect);
1045 };
1046 (#[repr($disc:ident $(, $c:ident)?)] #[$cfg:meta] $(#[$cfgs:meta])* { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {
1047 test!(@case #[repr($disc $(, $c)?)] #[$cfg] { $($vs ($($ts),*),)* } => $expect);
1048 test!(#[repr($disc $(, $c)?)] $(#[$cfgs])* { $($vs ($($ts),*),)* } => $expect);
1049 };
1050 (@case #[repr($disc:ident $(, $c:ident)?)] $(#[$cfg:meta])? { $($vs:ident ($($ts:ty),*),)* } => $expect:expr) => {{
1051 #[repr($disc $(, $c)?)]
1052 $(#[$cfg])?
1053 #[allow(unused)] // variants and fields are never used
1054 enum Test {
1055 $($vs ($($ts),*),)*
1056 }
1057 assert_eq!(
1058 enum_has_padding!(Test, $disc, $([$($ts),*]),*),
1059 $expect
1060 );
1061 }};
1062 }
1063
1064 #[allow(unused)]
1065 #[repr(align(2))]
1066 struct U16(u16);
1067
1068 #[allow(unused)]
1069 #[repr(align(4))]
1070 struct U32(u32);
1071
1072 test!(#[repr(u8)] #[repr(C)] {
1073 A(u8),
1074 } => false);
1075 test!(#[repr(u16)] #[repr(C)] {
1076 A(u8, u8),
1077 B(U16),
1078 } => false);
1079 test!(#[repr(u32)] #[repr(C)] {
1080 A(u8, u8, u8, u8),
1081 B(U16, u8, u8),
1082 C(u8, u8, U16),
1083 D(U16, U16),
1084 E(U32),
1085 } => false);
1086
1087 // `repr(int)` can pack the discriminant more efficiently
1088 test!(#[repr(u8)] {
1089 A(u8, U16),
1090 } => false);
1091 test!(#[repr(u8)] {
1092 A(u8, U16, U32),
1093 } => false);
1094
1095 // `repr(C)` cannot
1096 test!(#[repr(u8, C)] {
1097 A(u8, U16),
1098 } => true);
1099 test!(#[repr(u8, C)] {
1100 A(u8, u8, u8, U32),
1101 } => true);
1102
1103 // And field ordering can always cause problems
1104 test!(#[repr(u8)] #[repr(C)] {
1105 A(U16, u8),
1106 } => true);
1107 test!(#[repr(u8)] #[repr(C)] {
1108 A(U32, u8, u8, u8),
1109 } => true);
1110 }
1111}