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