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