zerocopy/
impls.rs

1// Copyright 2024 The Fuchsia Authors
2//
3// Licensed under the 2-Clause BSD License <LICENSE-BSD or
4// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
5// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
6// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
7// This file may not be copied, modified, or distributed except according to
8// those terms.
9
10use core::{
11    cell::{Cell, UnsafeCell},
12    mem::MaybeUninit as CoreMaybeUninit,
13    ptr::NonNull,
14};
15
16use super::*;
17
18// SAFETY: Per the reference [1], "the unit tuple (`()`) ... is guaranteed as a
19// zero-sized type to have a size of 0 and an alignment of 1."
20// - `Immutable`: `()` self-evidently does not contain any `UnsafeCell`s.
21// - `TryFromBytes` (with no validator), `FromZeros`, `FromBytes`: There is only
22//   one possible sequence of 0 bytes, and `()` is inhabited.
23// - `IntoBytes`: Since `()` has size 0, it contains no padding bytes.
24// - `Unaligned`: `()` has alignment 1.
25//
26// [1] https://doc.rust-lang.org/1.81.0/reference/type-layout.html#tuple-layout
27#[allow(clippy::multiple_unsafe_ops_per_block)]
28const _: () = unsafe {
29    unsafe_impl!((): Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
30    assert_unaligned!(());
31};
32
33// SAFETY:
34// - `Immutable`: These types self-evidently do not contain any `UnsafeCell`s.
35// - `TryFromBytes` (with no validator), `FromZeros`, `FromBytes`: all bit
36//   patterns are valid for numeric types [1]
37// - `IntoBytes`: numeric types have no padding bytes [1]
38// - `Unaligned` (`u8` and `i8` only): The reference [2] specifies the size of
39//   `u8` and `i8` as 1 byte. We also know that:
40//   - Alignment is >= 1 [3]
41//   - Size is an integer multiple of alignment [4]
42//   - The only value >= 1 for which 1 is an integer multiple is 1 Therefore,
43//   the only possible alignment for `u8` and `i8` is 1.
44//
45// [1] Per https://doc.rust-lang.org/1.81.0/reference/types/numeric.html#bit-validity:
46//
47//     For every numeric type, `T`, the bit validity of `T` is equivalent to
48//     the bit validity of `[u8; size_of::<T>()]`. An uninitialized byte is
49//     not a valid `u8`.
50//
51// [2] https://doc.rust-lang.org/1.81.0/reference/type-layout.html#primitive-data-layout
52//
53// [3] Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#size-and-alignment:
54//
55//     Alignment is measured in bytes, and must be at least 1.
56//
57// [4] Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#size-and-alignment:
58//
59//     The size of a value is always a multiple of its alignment.
60//
61// FIXME(#278): Once we've updated the trait docs to refer to `u8`s rather than
62// bits or bytes, update this comment, especially the reference to [1].
63#[allow(clippy::multiple_unsafe_ops_per_block)]
64const _: () = unsafe {
65    unsafe_impl!(u8: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
66    unsafe_impl!(i8: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
67    assert_unaligned!(u8, i8);
68    unsafe_impl!(u16: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
69    unsafe_impl!(i16: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
70    unsafe_impl!(u32: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
71    unsafe_impl!(i32: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
72    unsafe_impl!(u64: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
73    unsafe_impl!(i64: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
74    unsafe_impl!(u128: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
75    unsafe_impl!(i128: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
76    unsafe_impl!(usize: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
77    unsafe_impl!(isize: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
78    unsafe_impl!(f32: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
79    unsafe_impl!(f64: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
80    #[cfg(feature = "float-nightly")]
81    unsafe_impl!(#[cfg_attr(doc_cfg, doc(cfg(feature = "float-nightly")))] f16: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
82    #[cfg(feature = "float-nightly")]
83    unsafe_impl!(#[cfg_attr(doc_cfg, doc(cfg(feature = "float-nightly")))] f128: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
84};
85
86// SAFETY:
87// - `Immutable`: `bool` self-evidently does not contain any `UnsafeCell`s.
88// - `FromZeros`: Valid since "[t]he value false has the bit pattern 0x00" [1].
89// - `IntoBytes`: Since "the boolean type has a size and alignment of 1 each"
90//   and "The value false has the bit pattern 0x00 and the value true has the
91//   bit pattern 0x01" [1]. Thus, the only byte of the bool is always
92//   initialized.
93// - `Unaligned`: Per the reference [1], "[a]n object with the boolean type has
94//   a size and alignment of 1 each."
95//
96// [1] https://doc.rust-lang.org/1.81.0/reference/types/boolean.html
97#[allow(clippy::multiple_unsafe_ops_per_block)]
98const _: () = unsafe { unsafe_impl!(bool: Immutable, FromZeros, IntoBytes, Unaligned) };
99assert_unaligned!(bool);
100
101// SAFETY: The impl must only return `true` for its argument if the original
102// `Maybe<bool>` refers to a valid `bool`. We only return true if the `u8` value
103// is 0 or 1, and both of these are valid values for `bool` [1].
104//
105// [1] Per https://doc.rust-lang.org/1.81.0/reference/types/boolean.html:
106//
107//   The value false has the bit pattern 0x00 and the value true has the bit
108//   pattern 0x01.
109const _: () = unsafe {
110    unsafe_impl!(=> TryFromBytes for bool; |byte| {
111        let byte = byte.transmute::<u8, invariant::Valid, _>();
112        *byte.unaligned_as_ref() < 2
113    })
114};
115impl_size_eq!(bool, u8);
116
117// SAFETY:
118// - `Immutable`: `char` self-evidently does not contain any `UnsafeCell`s.
119// - `FromZeros`: Per reference [1], "[a] value of type char is a Unicode scalar
120//   value (i.e. a code point that is not a surrogate), represented as a 32-bit
121//   unsigned word in the 0x0000 to 0xD7FF or 0xE000 to 0x10FFFF range" which
122//   contains 0x0000.
123// - `IntoBytes`: `char` is per reference [1] "represented as a 32-bit unsigned
124//   word" (`u32`) which is `IntoBytes`. Note that unlike `u32`, not all bit
125//   patterns are valid for `char`.
126//
127// [1] https://doc.rust-lang.org/1.81.0/reference/types/textual.html
128#[allow(clippy::multiple_unsafe_ops_per_block)]
129const _: () = unsafe { unsafe_impl!(char: Immutable, FromZeros, IntoBytes) };
130
131// SAFETY: The impl must only return `true` for its argument if the original
132// `Maybe<char>` refers to a valid `char`. `char::from_u32` guarantees that it
133// returns `None` if its input is not a valid `char` [1].
134//
135// [1] Per https://doc.rust-lang.org/core/primitive.char.html#method.from_u32:
136//
137//   `from_u32()` will return `None` if the input is not a valid value for a
138//   `char`.
139const _: () = unsafe {
140    unsafe_impl!(=> TryFromBytes for char; |c| {
141        let c = c.transmute::<Unalign<u32>, invariant::Valid, _>();
142        let c = c.read_unaligned().into_inner();
143        char::from_u32(c).is_some()
144    });
145};
146
147impl_size_eq!(char, Unalign<u32>);
148
149// SAFETY: Per the Reference [1], `str` has the same layout as `[u8]`.
150// - `Immutable`: `[u8]` does not contain any `UnsafeCell`s.
151// - `FromZeros`, `IntoBytes`, `Unaligned`: `[u8]` is `FromZeros`, `IntoBytes`,
152//   and `Unaligned`.
153//
154// Note that we don't `assert_unaligned!(str)` because `assert_unaligned!` uses
155// `align_of`, which only works for `Sized` types.
156//
157// FIXME(#429): Improve safety proof for `FromZeros` and `IntoBytes`; having the same
158// layout as `[u8]` isn't sufficient.
159//
160// [1] Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#str-layout:
161//
162//   String slices are a UTF-8 representation of characters that have the same
163//   layout as slices of type `[u8]`.
164#[allow(clippy::multiple_unsafe_ops_per_block)]
165const _: () = unsafe { unsafe_impl!(str: Immutable, FromZeros, IntoBytes, Unaligned) };
166
167// SAFETY: The impl must only return `true` for its argument if the original
168// `Maybe<str>` refers to a valid `str`. `str::from_utf8` guarantees that it
169// returns `Err` if its input is not a valid `str` [1].
170//
171// [2] Per https://doc.rust-lang.org/core/str/fn.from_utf8.html#errors:
172//
173//   Returns `Err` if the slice is not UTF-8.
174const _: () = unsafe {
175    unsafe_impl!(=> TryFromBytes for str; |c| {
176        let c = c.transmute::<[u8], invariant::Valid, _>();
177        let c = c.unaligned_as_ref();
178        core::str::from_utf8(c).is_ok()
179    })
180};
181
182impl_size_eq!(str, [u8]);
183
184macro_rules! unsafe_impl_try_from_bytes_for_nonzero {
185    ($($nonzero:ident[$prim:ty]),*) => {
186        $(
187            unsafe_impl!(=> TryFromBytes for $nonzero; |n| {
188                impl_size_eq!($nonzero, Unalign<$prim>);
189
190                let n = n.transmute::<Unalign<$prim>, invariant::Valid, _>();
191                $nonzero::new(n.read_unaligned().into_inner()).is_some()
192            });
193        )*
194    }
195}
196
197// `NonZeroXxx` is `IntoBytes`, but not `FromZeros` or `FromBytes`.
198//
199// SAFETY:
200// - `IntoBytes`: `NonZeroXxx` has the same layout as its associated primitive.
201//    Since it is the same size, this guarantees it has no padding - integers
202//    have no padding, and there's no room for padding if it can represent all
203//    of the same values except 0.
204// - `Unaligned`: `NonZeroU8` and `NonZeroI8` document that `Option<NonZeroU8>`
205//   and `Option<NonZeroI8>` both have size 1. [1] [2] This is worded in a way
206//   that makes it unclear whether it's meant as a guarantee, but given the
207//   purpose of those types, it's virtually unthinkable that that would ever
208//   change. `Option` cannot be smaller than its contained type, which implies
209//   that, and `NonZeroX8` are of size 1 or 0. `NonZeroX8` can represent
210//   multiple states, so they cannot be 0 bytes, which means that they must be 1
211//   byte. The only valid alignment for a 1-byte type is 1.
212//
213// FIXME(#429):
214// - Add quotes from documentation.
215// - Add safety comment for `Immutable`. How can we prove that `NonZeroXxx`
216//   doesn't contain any `UnsafeCell`s? It's obviously true, but it's not clear
217//   how we'd prove it short of adding text to the stdlib docs that says so
218//   explicitly, which likely wouldn't be accepted.
219//
220// [1] Per https://doc.rust-lang.org/1.81.0/std/num/type.NonZeroU8.html:
221//
222//     `NonZeroU8` is guaranteed to have the same layout and bit validity as `u8` with
223//     the exception that 0 is not a valid instance.
224//
225// [2] Per https://doc.rust-lang.org/1.81.0/std/num/type.NonZeroI8.html:
226//
227//     `NonZeroI8` is guaranteed to have the same layout and bit validity as `i8` with
228//     the exception that 0 is not a valid instance.
229#[allow(clippy::multiple_unsafe_ops_per_block)]
230const _: () = unsafe {
231    unsafe_impl!(NonZeroU8: Immutable, IntoBytes, Unaligned);
232    unsafe_impl!(NonZeroI8: Immutable, IntoBytes, Unaligned);
233    assert_unaligned!(NonZeroU8, NonZeroI8);
234    unsafe_impl!(NonZeroU16: Immutable, IntoBytes);
235    unsafe_impl!(NonZeroI16: Immutable, IntoBytes);
236    unsafe_impl!(NonZeroU32: Immutable, IntoBytes);
237    unsafe_impl!(NonZeroI32: Immutable, IntoBytes);
238    unsafe_impl!(NonZeroU64: Immutable, IntoBytes);
239    unsafe_impl!(NonZeroI64: Immutable, IntoBytes);
240    unsafe_impl!(NonZeroU128: Immutable, IntoBytes);
241    unsafe_impl!(NonZeroI128: Immutable, IntoBytes);
242    unsafe_impl!(NonZeroUsize: Immutable, IntoBytes);
243    unsafe_impl!(NonZeroIsize: Immutable, IntoBytes);
244    unsafe_impl_try_from_bytes_for_nonzero!(
245        NonZeroU8[u8],
246        NonZeroI8[i8],
247        NonZeroU16[u16],
248        NonZeroI16[i16],
249        NonZeroU32[u32],
250        NonZeroI32[i32],
251        NonZeroU64[u64],
252        NonZeroI64[i64],
253        NonZeroU128[u128],
254        NonZeroI128[i128],
255        NonZeroUsize[usize],
256        NonZeroIsize[isize]
257    );
258};
259
260// SAFETY:
261// - `TryFromBytes` (with no validator), `FromZeros`, `FromBytes`, `IntoBytes`:
262//   The Rust compiler reuses `0` value to represent `None`, so
263//   `size_of::<Option<NonZeroXxx>>() == size_of::<xxx>()`; see `NonZeroXxx`
264//   documentation.
265// - `Unaligned`: `NonZeroU8` and `NonZeroI8` document that `Option<NonZeroU8>`
266//   and `Option<NonZeroI8>` both have size 1. [1] [2] This is worded in a way
267//   that makes it unclear whether it's meant as a guarantee, but given the
268//   purpose of those types, it's virtually unthinkable that that would ever
269//   change. The only valid alignment for a 1-byte type is 1.
270//
271// [1] Per https://doc.rust-lang.org/1.81.0/std/num/type.NonZeroU8.html:
272//
273//     `Option<NonZeroU8>` is guaranteed to be compatible with `u8`, including in FFI.
274//
275//     Thanks to the null pointer optimization, `NonZeroU8` and `Option<NonZeroU8>`
276//     are guaranteed to have the same size and alignment:
277//
278// [2] Per https://doc.rust-lang.org/1.81.0/std/num/type.NonZeroI8.html:
279//
280//     `Option<NonZeroI8>` is guaranteed to be compatible with `i8`, including in FFI.
281//
282//     Thanks to the null pointer optimization, `NonZeroI8` and `Option<NonZeroI8>`
283//     are guaranteed to have the same size and alignment:
284#[allow(clippy::multiple_unsafe_ops_per_block)]
285const _: () = unsafe {
286    unsafe_impl!(Option<NonZeroU8>: TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
287    unsafe_impl!(Option<NonZeroI8>: TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
288    assert_unaligned!(Option<NonZeroU8>, Option<NonZeroI8>);
289    unsafe_impl!(Option<NonZeroU16>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
290    unsafe_impl!(Option<NonZeroI16>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
291    unsafe_impl!(Option<NonZeroU32>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
292    unsafe_impl!(Option<NonZeroI32>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
293    unsafe_impl!(Option<NonZeroU64>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
294    unsafe_impl!(Option<NonZeroI64>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
295    unsafe_impl!(Option<NonZeroU128>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
296    unsafe_impl!(Option<NonZeroI128>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
297    unsafe_impl!(Option<NonZeroUsize>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
298    unsafe_impl!(Option<NonZeroIsize>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
299};
300
301// SAFETY: While it's not fully documented, the consensus is that `Box<T>` does
302// not contain any `UnsafeCell`s for `T: Sized` [1]. This is not a complete
303// proof, but we are accepting this as a known risk per #1358.
304//
305// [1] https://github.com/rust-lang/unsafe-code-guidelines/issues/492
306#[cfg(feature = "alloc")]
307const _: () = unsafe {
308    unsafe_impl!(
309        #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
310        T: Sized => Immutable for Box<T>
311    )
312};
313
314// SAFETY: The following types can be transmuted from `[0u8; size_of::<T>()]`. [1]
315//
316// [1] Per https://doc.rust-lang.org/1.89.0/core/option/index.html#representation:
317//
318//   Rust guarantees to optimize the following types `T` such that [`Option<T>`]
319//   has the same size and alignment as `T`. In some of these cases, Rust
320//   further guarantees that `transmute::<_, Option<T>>([0u8; size_of::<T>()])`
321//   is sound and produces `Option::<T>::None`. These cases are identified by
322//   the second column:
323//
324//   | `T`                               | `transmute::<_, Option<T>>([0u8; size_of::<T>()])` sound? |
325//   |-----------------------------------|-----------------------------------------------------------|
326//   | [`Box<U>`]                        | when `U: Sized`                                           |
327//   | `&U`                              | when `U: Sized`                                           |
328//   | `&mut U`                          | when `U: Sized`                                           |
329//   | [`ptr::NonNull<U>`]               | when `U: Sized`                                           |
330//   | `fn`, `extern "C" fn`[^extern_fn] | always                                                    |
331//
332//   [^extern_fn]: this remains true for `unsafe` variants, any argument/return
333//     types, and any other ABI: `[unsafe] extern "abi" fn` (_e.g._, `extern
334//     "system" fn`)
335#[allow(clippy::multiple_unsafe_ops_per_block)]
336const _: () = unsafe {
337    #[cfg(feature = "alloc")]
338    unsafe_impl!(
339        #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
340        T => TryFromBytes for Option<Box<T>>; |c| pointer::is_zeroed(c)
341    );
342    #[cfg(feature = "alloc")]
343    unsafe_impl!(
344        #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
345        T => FromZeros for Option<Box<T>>
346    );
347    unsafe_impl!(
348        T => TryFromBytes for Option<&'_ T>; |c| pointer::is_zeroed(c)
349    );
350    unsafe_impl!(T => FromZeros for Option<&'_ T>);
351    unsafe_impl!(
352            T => TryFromBytes for Option<&'_ mut T>; |c| pointer::is_zeroed(c)
353    );
354    unsafe_impl!(T => FromZeros for Option<&'_ mut T>);
355    unsafe_impl!(
356        T => TryFromBytes for Option<NonNull<T>>; |c| pointer::is_zeroed(c)
357    );
358    unsafe_impl!(T => FromZeros for Option<NonNull<T>>);
359    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeros for opt_fn!(...));
360    unsafe_impl_for_power_set!(
361        A, B, C, D, E, F, G, H, I, J, K, L -> M => TryFromBytes for opt_fn!(...);
362        |c| pointer::is_zeroed(c)
363    );
364    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeros for opt_unsafe_fn!(...));
365    unsafe_impl_for_power_set!(
366        A, B, C, D, E, F, G, H, I, J, K, L -> M => TryFromBytes for opt_unsafe_fn!(...);
367        |c| pointer::is_zeroed(c)
368    );
369    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeros for opt_extern_c_fn!(...));
370    unsafe_impl_for_power_set!(
371        A, B, C, D, E, F, G, H, I, J, K, L -> M => TryFromBytes for opt_extern_c_fn!(...);
372        |c| pointer::is_zeroed(c)
373    );
374    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeros for opt_unsafe_extern_c_fn!(...));
375    unsafe_impl_for_power_set!(
376        A, B, C, D, E, F, G, H, I, J, K, L -> M => TryFromBytes for opt_unsafe_extern_c_fn!(...);
377        |c| pointer::is_zeroed(c)
378    );
379};
380
381// SAFETY: `[unsafe] [extern "C"] fn()` self-evidently do not contain
382// `UnsafeCell`s. This is not a proof, but we are accepting this as a known risk
383// per #1358.
384#[allow(clippy::multiple_unsafe_ops_per_block)]
385const _: () = unsafe {
386    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => Immutable for opt_fn!(...));
387    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => Immutable for opt_unsafe_fn!(...));
388    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => Immutable for opt_extern_c_fn!(...));
389    unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => Immutable for opt_unsafe_extern_c_fn!(...));
390};
391
392#[cfg(all(
393    not(no_zerocopy_target_has_atomics_1_60_0),
394    any(
395        target_has_atomic = "8",
396        target_has_atomic = "16",
397        target_has_atomic = "32",
398        target_has_atomic = "64",
399        target_has_atomic = "ptr"
400    )
401))]
402#[cfg_attr(doc_cfg, doc(cfg(rust = "1.60.0")))]
403mod atomics {
404    use super::*;
405
406    macro_rules! impl_traits_for_atomics {
407        ($($atomics:ident [$primitives:ident]),* $(,)?) => {
408            $(
409                impl_known_layout!($atomics);
410                impl_for_transmute_from!(=> TryFromBytes for $atomics [UnsafeCell<$primitives>]);
411                impl_for_transmute_from!(=> FromZeros for $atomics [UnsafeCell<$primitives>]);
412                impl_for_transmute_from!(=> FromBytes for $atomics [UnsafeCell<$primitives>]);
413                impl_for_transmute_from!(=> IntoBytes for $atomics [UnsafeCell<$primitives>]);
414            )*
415        };
416    }
417
418    /// Implements `TransmuteFrom` for `$atomic`, `$prim`, and
419    /// `UnsafeCell<$prim>`.
420    ///
421    /// # Safety
422    ///
423    /// `$atomic` must have the same size and bit validity as `$prim`.
424    macro_rules! unsafe_impl_transmute_from_for_atomic {
425        ($($($tyvar:ident)? => $atomic:ty [$prim:ty]),*) => {{
426            crate::util::macros::__unsafe();
427
428            use core::cell::UnsafeCell;
429            use crate::pointer::{SizeEq, TransmuteFrom, invariant::Valid};
430
431            $(
432                // SAFETY: The caller promised that `$atomic` and `$prim` have
433                // the same size and bit validity.
434                unsafe impl<$($tyvar)?> TransmuteFrom<$atomic, Valid, Valid> for $prim {}
435                // SAFETY: The caller promised that `$atomic` and `$prim` have
436                // the same size and bit validity.
437                unsafe impl<$($tyvar)?> TransmuteFrom<$prim, Valid, Valid> for $atomic {}
438
439                // SAFETY: The caller promised that `$atomic` and `$prim` have
440                // the same size.
441                unsafe impl<$($tyvar)?> SizeEq<$atomic> for $prim {
442                    type CastFrom = $crate::pointer::cast::CastSized;
443                }
444                // SAFETY: See previous safety comment.
445                unsafe impl<$($tyvar)?> SizeEq<$prim> for $atomic {
446                    type CastFrom = $crate::pointer::cast::CastSized;
447                }
448                // SAFETY: The caller promised that `$atomic` and `$prim` have
449                // the same size. `UnsafeCell<T>` has the same size as `T` [1].
450                //
451                // [1] Per https://doc.rust-lang.org/1.85.0/std/cell/struct.UnsafeCell.html#memory-layout:
452                //
453                //   `UnsafeCell<T>` has the same in-memory representation as
454                //   its inner type `T`. A consequence of this guarantee is that
455                //   it is possible to convert between `T` and `UnsafeCell<T>`.
456                unsafe impl<$($tyvar)?> SizeEq<$atomic> for UnsafeCell<$prim> {
457                    type CastFrom = $crate::pointer::cast::CastSized;
458                }
459                // SAFETY: See previous safety comment.
460                unsafe impl<$($tyvar)?> SizeEq<UnsafeCell<$prim>> for $atomic {
461                    type CastFrom = $crate::pointer::cast::CastSized;
462                }
463
464                // SAFETY: The caller promised that `$atomic` and `$prim` have
465                // the same bit validity. `UnsafeCell<T>` has the same bit
466                // validity as `T` [1].
467                //
468                // [1] Per https://doc.rust-lang.org/1.85.0/std/cell/struct.UnsafeCell.html#memory-layout:
469                //
470                //   `UnsafeCell<T>` has the same in-memory representation as
471                //   its inner type `T`. A consequence of this guarantee is that
472                //   it is possible to convert between `T` and `UnsafeCell<T>`.
473                unsafe impl<$($tyvar)?> TransmuteFrom<$atomic, Valid, Valid> for core::cell::UnsafeCell<$prim> {}
474                // SAFETY: See previous safety comment.
475                unsafe impl<$($tyvar)?> TransmuteFrom<core::cell::UnsafeCell<$prim>, Valid, Valid> for $atomic {}
476            )*
477        }};
478    }
479
480    #[cfg(target_has_atomic = "8")]
481    #[cfg_attr(doc_cfg, doc(cfg(target_has_atomic = "8")))]
482    mod atomic_8 {
483        use core::sync::atomic::{AtomicBool, AtomicI8, AtomicU8};
484
485        use super::*;
486
487        impl_traits_for_atomics!(AtomicU8[u8], AtomicI8[i8]);
488
489        impl_known_layout!(AtomicBool);
490
491        impl_for_transmute_from!(=> TryFromBytes for AtomicBool [UnsafeCell<bool>]);
492        impl_for_transmute_from!(=> FromZeros for AtomicBool [UnsafeCell<bool>]);
493        impl_for_transmute_from!(=> IntoBytes for AtomicBool [UnsafeCell<bool>]);
494
495        // SAFETY: Per [1], `AtomicBool`, `AtomicU8`, and `AtomicI8` have the
496        // same size as `bool`, `u8`, and `i8` respectively. Since a type's
497        // alignment cannot be smaller than 1 [2], and since its alignment
498        // cannot be greater than its size [3], the only possible value for the
499        // alignment is 1. Thus, it is sound to implement `Unaligned`.
500        //
501        // [1] Per (for example) https://doc.rust-lang.org/1.81.0/std/sync/atomic/struct.AtomicU8.html:
502        //
503        //   This type has the same size, alignment, and bit validity as the
504        //   underlying integer type
505        //
506        // [2] Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#size-and-alignment:
507        //
508        //     Alignment is measured in bytes, and must be at least 1.
509        //
510        // [3] Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#size-and-alignment:
511        //
512        //     The size of a value is always a multiple of its alignment.
513        #[allow(clippy::multiple_unsafe_ops_per_block)]
514        const _: () = unsafe {
515            unsafe_impl!(AtomicBool: Unaligned);
516            unsafe_impl!(AtomicU8: Unaligned);
517            unsafe_impl!(AtomicI8: Unaligned);
518            assert_unaligned!(AtomicBool, AtomicU8, AtomicI8);
519        };
520
521        // SAFETY: `AtomicU8`, `AtomicI8`, and `AtomicBool` have the same size
522        // and bit validity as `u8`, `i8`, and `bool` respectively [1][2][3].
523        //
524        // [1] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicU8.html:
525        //
526        //   This type has the same size, alignment, and bit validity as the
527        //   underlying integer type, `u8`.
528        //
529        // [2] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicI8.html:
530        //
531        //   This type has the same size, alignment, and bit validity as the
532        //   underlying integer type, `i8`.
533        //
534        // [3] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicBool.html:
535        //
536        //   This type has the same size, alignment, and bit validity a `bool`.
537        #[allow(clippy::multiple_unsafe_ops_per_block)]
538        const _: () = unsafe {
539            unsafe_impl_transmute_from_for_atomic!(
540                => AtomicU8 [u8],
541                => AtomicI8 [i8],
542                => AtomicBool [bool]
543            )
544        };
545    }
546
547    #[cfg(target_has_atomic = "16")]
548    #[cfg_attr(doc_cfg, doc(cfg(target_has_atomic = "16")))]
549    mod atomic_16 {
550        use core::sync::atomic::{AtomicI16, AtomicU16};
551
552        use super::*;
553
554        impl_traits_for_atomics!(AtomicU16[u16], AtomicI16[i16]);
555
556        // SAFETY: `AtomicU16` and `AtomicI16` have the same size and bit
557        // validity as `u16` and `i16` respectively [1][2].
558        //
559        // [1] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicU16.html:
560        //
561        //   This type has the same size and bit validity as the underlying
562        //   integer type, `u16`.
563        //
564        // [2] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicI16.html:
565        //
566        //   This type has the same size and bit validity as the underlying
567        //   integer type, `i16`.
568        #[allow(clippy::multiple_unsafe_ops_per_block)]
569        const _: () = unsafe {
570            unsafe_impl_transmute_from_for_atomic!(=> AtomicU16 [u16], => AtomicI16 [i16])
571        };
572    }
573
574    #[cfg(target_has_atomic = "32")]
575    #[cfg_attr(doc_cfg, doc(cfg(target_has_atomic = "32")))]
576    mod atomic_32 {
577        use core::sync::atomic::{AtomicI32, AtomicU32};
578
579        use super::*;
580
581        impl_traits_for_atomics!(AtomicU32[u32], AtomicI32[i32]);
582
583        // SAFETY: `AtomicU32` and `AtomicI32` have the same size and bit
584        // validity as `u32` and `i32` respectively [1][2].
585        //
586        // [1] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicU32.html:
587        //
588        //   This type has the same size and bit validity as the underlying
589        //   integer type, `u32`.
590        //
591        // [2] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicI32.html:
592        //
593        //   This type has the same size and bit validity as the underlying
594        //   integer type, `i32`.
595        #[allow(clippy::multiple_unsafe_ops_per_block)]
596        const _: () = unsafe {
597            unsafe_impl_transmute_from_for_atomic!(=> AtomicU32 [u32], => AtomicI32 [i32])
598        };
599    }
600
601    #[cfg(target_has_atomic = "64")]
602    #[cfg_attr(doc_cfg, doc(cfg(target_has_atomic = "64")))]
603    mod atomic_64 {
604        use core::sync::atomic::{AtomicI64, AtomicU64};
605
606        use super::*;
607
608        impl_traits_for_atomics!(AtomicU64[u64], AtomicI64[i64]);
609
610        // SAFETY: `AtomicU64` and `AtomicI64` have the same size and bit
611        // validity as `u64` and `i64` respectively [1][2].
612        //
613        // [1] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicU64.html:
614        //
615        //   This type has the same size and bit validity as the underlying
616        //   integer type, `u64`.
617        //
618        // [2] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicI64.html:
619        //
620        //   This type has the same size and bit validity as the underlying
621        //   integer type, `i64`.
622        #[allow(clippy::multiple_unsafe_ops_per_block)]
623        const _: () = unsafe {
624            unsafe_impl_transmute_from_for_atomic!(=> AtomicU64 [u64], => AtomicI64 [i64])
625        };
626    }
627
628    #[cfg(target_has_atomic = "ptr")]
629    #[cfg_attr(doc_cfg, doc(cfg(target_has_atomic = "ptr")))]
630    mod atomic_ptr {
631        use core::sync::atomic::{AtomicIsize, AtomicPtr, AtomicUsize};
632
633        use super::*;
634
635        impl_traits_for_atomics!(AtomicUsize[usize], AtomicIsize[isize]);
636
637        impl_known_layout!(T => AtomicPtr<T>);
638
639        // FIXME(#170): Implement `FromBytes` and `IntoBytes` once we implement
640        // those traits for `*mut T`.
641        impl_for_transmute_from!(T => TryFromBytes for AtomicPtr<T> [UnsafeCell<*mut T>]);
642        impl_for_transmute_from!(T => FromZeros for AtomicPtr<T> [UnsafeCell<*mut T>]);
643
644        // SAFETY: `AtomicUsize` and `AtomicIsize` have the same size and bit
645        // validity as `usize` and `isize` respectively [1][2].
646        //
647        // [1] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicUsize.html:
648        //
649        //   This type has the same size and bit validity as the underlying
650        //   integer type, `usize`.
651        //
652        // [2] Per https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicIsize.html:
653        //
654        //   This type has the same size and bit validity as the underlying
655        //   integer type, `isize`.
656        #[allow(clippy::multiple_unsafe_ops_per_block)]
657        const _: () = unsafe {
658            unsafe_impl_transmute_from_for_atomic!(=> AtomicUsize [usize], => AtomicIsize [isize])
659        };
660
661        // SAFETY: Per
662        // https://doc.rust-lang.org/1.85.0/std/sync/atomic/struct.AtomicPtr.html:
663        //
664        //   This type has the same size and bit validity as a `*mut T`.
665        #[allow(clippy::multiple_unsafe_ops_per_block)]
666        const _: () = unsafe { unsafe_impl_transmute_from_for_atomic!(T => AtomicPtr<T> [*mut T]) };
667    }
668}
669
670// SAFETY: Per reference [1]: "For all T, the following are guaranteed:
671// size_of::<PhantomData<T>>() == 0 align_of::<PhantomData<T>>() == 1". This
672// gives:
673// - `Immutable`: `PhantomData` has no fields.
674// - `TryFromBytes` (with no validator), `FromZeros`, `FromBytes`: There is only
675//   one possible sequence of 0 bytes, and `PhantomData` is inhabited.
676// - `IntoBytes`: Since `PhantomData` has size 0, it contains no padding bytes.
677// - `Unaligned`: Per the preceding reference, `PhantomData` has alignment 1.
678//
679// [1] https://doc.rust-lang.org/1.81.0/std/marker/struct.PhantomData.html#layout-1
680#[allow(clippy::multiple_unsafe_ops_per_block)]
681const _: () = unsafe {
682    unsafe_impl!(T: ?Sized => Immutable for PhantomData<T>);
683    unsafe_impl!(T: ?Sized => TryFromBytes for PhantomData<T>);
684    unsafe_impl!(T: ?Sized => FromZeros for PhantomData<T>);
685    unsafe_impl!(T: ?Sized => FromBytes for PhantomData<T>);
686    unsafe_impl!(T: ?Sized => IntoBytes for PhantomData<T>);
687    unsafe_impl!(T: ?Sized => Unaligned for PhantomData<T>);
688    assert_unaligned!(PhantomData<()>, PhantomData<u8>, PhantomData<u64>);
689};
690
691impl_for_transmute_from!(T: TryFromBytes => TryFromBytes for Wrapping<T>[<T>]);
692impl_for_transmute_from!(T: FromZeros => FromZeros for Wrapping<T>[<T>]);
693impl_for_transmute_from!(T: FromBytes => FromBytes for Wrapping<T>[<T>]);
694impl_for_transmute_from!(T: IntoBytes => IntoBytes for Wrapping<T>[<T>]);
695assert_unaligned!(Wrapping<()>, Wrapping<u8>);
696
697// SAFETY: Per [1], `Wrapping<T>` has the same layout as `T`. Since its single
698// field (of type `T`) is public, it would be a breaking change to add or remove
699// fields. Thus, we know that `Wrapping<T>` contains a `T` (as opposed to just
700// having the same size and alignment as `T`) with no pre- or post-padding.
701// Thus, `Wrapping<T>` must have `UnsafeCell`s covering the same byte ranges as
702// `Inner = T`.
703//
704// [1] Per https://doc.rust-lang.org/1.81.0/std/num/struct.Wrapping.html#layout-1:
705//
706//   `Wrapping<T>` is guaranteed to have the same layout and ABI as `T`
707const _: () = unsafe { unsafe_impl!(T: Immutable => Immutable for Wrapping<T>) };
708
709// SAFETY: Per [1] in the preceding safety comment, `Wrapping<T>` has the same
710// alignment as `T`.
711const _: () = unsafe { unsafe_impl!(T: Unaligned => Unaligned for Wrapping<T>) };
712
713// SAFETY: `TryFromBytes` (with no validator), `FromZeros`, `FromBytes`:
714// `MaybeUninit<T>` has no restrictions on its contents.
715#[allow(clippy::multiple_unsafe_ops_per_block)]
716const _: () = unsafe {
717    unsafe_impl!(T => TryFromBytes for CoreMaybeUninit<T>);
718    unsafe_impl!(T => FromZeros for CoreMaybeUninit<T>);
719    unsafe_impl!(T => FromBytes for CoreMaybeUninit<T>);
720};
721
722// SAFETY: `MaybeUninit<T>` has `UnsafeCell`s covering the same byte ranges as
723// `Inner = T`. This is not explicitly documented, but it can be inferred. Per
724// [1], `MaybeUninit<T>` has the same size as `T`. Further, note the signature
725// of `MaybeUninit::assume_init_ref` [2]:
726//
727//   pub unsafe fn assume_init_ref(&self) -> &T
728//
729// If the argument `&MaybeUninit<T>` and the returned `&T` had `UnsafeCell`s at
730// different offsets, this would be unsound. Its existence is proof that this is
731// not the case.
732//
733// [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
734//
735// `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as
736// `T`.
737//
738// [2] https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#method.assume_init_ref
739const _: () = unsafe { unsafe_impl!(T: Immutable => Immutable for CoreMaybeUninit<T>) };
740
741// SAFETY: Per [1] in the preceding safety comment, `MaybeUninit<T>` has the
742// same alignment as `T`.
743const _: () = unsafe { unsafe_impl!(T: Unaligned => Unaligned for CoreMaybeUninit<T>) };
744assert_unaligned!(CoreMaybeUninit<()>, CoreMaybeUninit<u8>);
745
746// SAFETY: `ManuallyDrop<T>` has the same layout as `T` [1]. This strongly
747// implies, but does not guarantee, that it contains `UnsafeCell`s covering the
748// same byte ranges as in `T`. However, it also implements `Defer<Target = T>`
749// [2], which provides the ability to convert `&ManuallyDrop<T> -> &T`. This,
750// combined with having the same size as `T`, implies that `ManuallyDrop<T>`
751// exactly contains a `T` with the same fields and `UnsafeCell`s covering the
752// same byte ranges, or else the `Deref` impl would permit safe code to obtain
753// different shared references to the same region of memory with different
754// `UnsafeCell` coverage, which would in turn permit interior mutation that
755// would violate the invariants of a shared reference.
756//
757// [1] Per https://doc.rust-lang.org/1.85.0/std/mem/struct.ManuallyDrop.html:
758//
759//   `ManuallyDrop<T>` is guaranteed to have the same layout and bit validity as
760//   `T`
761//
762// [2] https://doc.rust-lang.org/1.85.0/std/mem/struct.ManuallyDrop.html#impl-Deref-for-ManuallyDrop%3CT%3E
763const _: () = unsafe { unsafe_impl!(T: ?Sized + Immutable => Immutable for ManuallyDrop<T>) };
764
765impl_for_transmute_from!(T: ?Sized + TryFromBytes => TryFromBytes for ManuallyDrop<T>[<T>]);
766impl_for_transmute_from!(T: ?Sized + FromZeros => FromZeros for ManuallyDrop<T>[<T>]);
767impl_for_transmute_from!(T: ?Sized + FromBytes => FromBytes for ManuallyDrop<T>[<T>]);
768impl_for_transmute_from!(T: ?Sized + IntoBytes => IntoBytes for ManuallyDrop<T>[<T>]);
769// SAFETY: `ManuallyDrop<T>` has the same layout as `T` [1], and thus has the
770// same alignment as `T`.
771//
772// [1] Per https://doc.rust-lang.org/1.81.0/std/mem/struct.ManuallyDrop.html:
773//
774//   `ManuallyDrop<T>` is guaranteed to have the same layout and bit validity as
775//   `T`
776const _: () = unsafe { unsafe_impl!(T: ?Sized + Unaligned => Unaligned for ManuallyDrop<T>) };
777assert_unaligned!(ManuallyDrop<()>, ManuallyDrop<u8>);
778
779const _: () = {
780    #[allow(
781        non_camel_case_types,
782        missing_copy_implementations,
783        missing_debug_implementations,
784        missing_docs
785    )]
786    pub enum value {}
787
788    // SAFETY: `ManuallyDrop<T>` has a field of type `T` at offset `0` without
789    // any safety invariants beyond those of `T`.  Its existence is not
790    // explicitly documented, but it can be inferred; per [1] `ManuallyDrop<T>`
791    // has the same size and bit validity as `T`. This field is not literally
792    // public, but is effectively so; the field can be transparently:
793    //
794    //  - initialized via `ManuallyDrop::new`
795    //  - moved via `ManuallyDrop::into_inner`
796    //  - referenced via `ManuallyDrop::deref`
797    //  - exclusively referenced via `ManuallyDrop::deref_mut`
798    //
799    // We call this field `value`, both because that is both the name of this
800    // private field, and because it is the name it is referred to in the public
801    // documentation of `ManuallyDrop::new`, `ManuallyDrop::into_inner`,
802    // `ManuallyDrop::take` and `ManuallyDrop::drop`.
803    unsafe impl<T: ?Sized>
804        HasField<value, { crate::STRUCT_VARIANT_ID }, { crate::ident_id!(value) }>
805        for ManuallyDrop<T>
806    {
807        type Type = T;
808
809        #[inline]
810        fn only_derive_is_allowed_to_implement_this_trait()
811        where
812            Self: Sized,
813        {
814        }
815
816        #[inline(always)]
817        fn project(slf: PtrInner<'_, Self>) -> *mut T {
818            // SAFETY: `ManuallyDrop<T>` has the same layout and bit validity as
819            // `T` [1].
820            //
821            // [1] Per https://doc.rust-lang.org/1.85.0/std/mem/struct.ManuallyDrop.html:
822            //
823            //   `ManuallyDrop<T>` is guaranteed to have the same layout and bit
824            //   validity as `T`
825            #[allow(clippy::as_conversions)]
826            return slf.as_ptr() as *mut T;
827        }
828    }
829};
830
831impl_for_transmute_from!(T: ?Sized + TryFromBytes => TryFromBytes for Cell<T>[UnsafeCell<T>]);
832impl_for_transmute_from!(T: ?Sized + FromZeros => FromZeros for Cell<T>[UnsafeCell<T>]);
833impl_for_transmute_from!(T: ?Sized + FromBytes => FromBytes for Cell<T>[UnsafeCell<T>]);
834impl_for_transmute_from!(T: ?Sized + IntoBytes => IntoBytes for Cell<T>[UnsafeCell<T>]);
835// SAFETY: `Cell<T>` has the same in-memory representation as `T` [1], and thus
836// has the same alignment as `T`.
837//
838// [1] Per https://doc.rust-lang.org/1.81.0/core/cell/struct.Cell.html#memory-layout:
839//
840//   `Cell<T>` has the same in-memory representation as its inner type `T`.
841const _: () = unsafe { unsafe_impl!(T: ?Sized + Unaligned => Unaligned for Cell<T>) };
842
843impl_for_transmute_from!(T: ?Sized + FromZeros => FromZeros for UnsafeCell<T>[<T>]);
844impl_for_transmute_from!(T: ?Sized + FromBytes => FromBytes for UnsafeCell<T>[<T>]);
845impl_for_transmute_from!(T: ?Sized + IntoBytes => IntoBytes for UnsafeCell<T>[<T>]);
846// SAFETY: `UnsafeCell<T>` has the same in-memory representation as `T` [1], and
847// thus has the same alignment as `T`.
848//
849// [1] Per https://doc.rust-lang.org/1.81.0/core/cell/struct.UnsafeCell.html#memory-layout:
850//
851//   `UnsafeCell<T>` has the same in-memory representation as its inner type
852//   `T`.
853const _: () = unsafe { unsafe_impl!(T: ?Sized + Unaligned => Unaligned for UnsafeCell<T>) };
854assert_unaligned!(UnsafeCell<()>, UnsafeCell<u8>);
855
856// SAFETY: See safety comment in `is_bit_valid` impl.
857unsafe impl<T: TryFromBytes + ?Sized> TryFromBytes for UnsafeCell<T> {
858    #[allow(clippy::missing_inline_in_public_items)]
859    fn only_derive_is_allowed_to_implement_this_trait()
860    where
861        Self: Sized,
862    {
863    }
864
865    #[inline]
866    fn is_bit_valid<A: invariant::Reference>(candidate: Maybe<'_, Self, A>) -> bool {
867        // The only way to implement this function is using an exclusive-aliased
868        // pointer. `UnsafeCell`s cannot be read via shared-aliased pointers
869        // (other than by using `unsafe` code, which we can't use since we can't
870        // guarantee how our users are accessing or modifying the `UnsafeCell`).
871        //
872        // `is_bit_valid` is documented as panicking or failing to monomorphize
873        // if called with a shared-aliased pointer on a type containing an
874        // `UnsafeCell`. In practice, it will always be a monomorphization error.
875        // Since `is_bit_valid` is `#[doc(hidden)]` and only called directly
876        // from this crate, we only need to worry about our own code incorrectly
877        // calling `UnsafeCell::is_bit_valid`. The post-monomorphization error
878        // makes it easier to test that this is truly the case, and also means
879        // that if we make a mistake, it will cause downstream code to fail to
880        // compile, which will immediately surface the mistake and give us a
881        // chance to fix it quickly.
882        let c = candidate.into_exclusive_or_pme();
883
884        // SAFETY: Since `UnsafeCell<T>` and `T` have the same layout and bit
885        // validity, `UnsafeCell<T>` is bit-valid exactly when its wrapped `T`
886        // is. Thus, this is a sound implementation of
887        // `UnsafeCell::is_bit_valid`.
888        T::is_bit_valid(c.get_mut())
889    }
890}
891
892// SAFETY: Per the reference [1]:
893//
894//   An array of `[T; N]` has a size of `size_of::<T>() * N` and the same
895//   alignment of `T`. Arrays are laid out so that the zero-based `nth` element
896//   of the array is offset from the start of the array by `n * size_of::<T>()`
897//   bytes.
898//
899//   ...
900//
901//   Slices have the same layout as the section of the array they slice.
902//
903// In other words, the layout of a `[T]` or `[T; N]` is a sequence of `T`s laid
904// out back-to-back with no bytes in between. Therefore, `[T]` or `[T; N]` are
905// `Immutable`, `TryFromBytes`, `FromZeros`, `FromBytes`, and `IntoBytes` if `T`
906// is (respectively). Furthermore, since an array/slice has "the same alignment
907// of `T`", `[T]` and `[T; N]` are `Unaligned` if `T` is.
908//
909// Note that we don't `assert_unaligned!` for slice types because
910// `assert_unaligned!` uses `align_of`, which only works for `Sized` types.
911//
912// [1] https://doc.rust-lang.org/1.81.0/reference/type-layout.html#array-layout
913#[allow(clippy::multiple_unsafe_ops_per_block)]
914const _: () = unsafe {
915    unsafe_impl!(const N: usize, T: Immutable => Immutable for [T; N]);
916    unsafe_impl!(const N: usize, T: TryFromBytes => TryFromBytes for [T; N]; |c| {
917        // Note that this call may panic, but it would still be sound even if it
918        // did. `is_bit_valid` does not promise that it will not panic (in fact,
919        // it explicitly warns that it's a possibility), and we have not
920        // violated any safety invariants that we must fix before returning.
921        <[T] as TryFromBytes>::is_bit_valid(c.as_slice())
922    });
923    unsafe_impl!(const N: usize, T: FromZeros => FromZeros for [T; N]);
924    unsafe_impl!(const N: usize, T: FromBytes => FromBytes for [T; N]);
925    unsafe_impl!(const N: usize, T: IntoBytes => IntoBytes for [T; N]);
926    unsafe_impl!(const N: usize, T: Unaligned => Unaligned for [T; N]);
927    assert_unaligned!([(); 0], [(); 1], [u8; 0], [u8; 1]);
928    unsafe_impl!(T: Immutable => Immutable for [T]);
929    unsafe_impl!(T: TryFromBytes => TryFromBytes for [T]; |c| {
930        // SAFETY: Per the reference [1]:
931        //
932        //   An array of `[T; N]` has a size of `size_of::<T>() * N` and the
933        //   same alignment of `T`. Arrays are laid out so that the zero-based
934        //   `nth` element of the array is offset from the start of the array by
935        //   `n * size_of::<T>()` bytes.
936        //
937        //   ...
938        //
939        //   Slices have the same layout as the section of the array they slice.
940        //
941        // In other words, the layout of a `[T] is a sequence of `T`s laid out
942        // back-to-back with no bytes in between. If all elements in `candidate`
943        // are `is_bit_valid`, so too is `candidate`.
944        //
945        // Note that any of the below calls may panic, but it would still be
946        // sound even if it did. `is_bit_valid` does not promise that it will
947        // not panic (in fact, it explicitly warns that it's a possibility), and
948        // we have not violated any safety invariants that we must fix before
949        // returning.
950        c.iter().all(<T as TryFromBytes>::is_bit_valid)
951    });
952    unsafe_impl!(T: FromZeros => FromZeros for [T]);
953    unsafe_impl!(T: FromBytes => FromBytes for [T]);
954    unsafe_impl!(T: IntoBytes => IntoBytes for [T]);
955    unsafe_impl!(T: Unaligned => Unaligned for [T]);
956};
957
958// SAFETY:
959// - `Immutable`: Raw pointers do not contain any `UnsafeCell`s.
960// - `FromZeros`: For thin pointers (note that `T: Sized`), the zero pointer is
961//   considered "null". [1] No operations which require provenance are legal on
962//   null pointers, so this is not a footgun.
963// - `TryFromBytes`: By the same reasoning as for `FromZeroes`, we can implement
964//   `TryFromBytes` for thin pointers provided that
965//   [`TryFromByte::is_bit_valid`] only produces `true` for zeroed bytes.
966//
967// NOTE(#170): Implementing `FromBytes` and `IntoBytes` for raw pointers would
968// be sound, but carries provenance footguns. We want to support `FromBytes` and
969// `IntoBytes` for raw pointers eventually, but we are holding off until we can
970// figure out how to address those footguns.
971//
972// [1] Per https://doc.rust-lang.org/1.81.0/std/ptr/fn.null.html:
973//
974//   Creates a null raw pointer.
975//
976//   This function is equivalent to zero-initializing the pointer:
977//   `MaybeUninit::<*const T>::zeroed().assume_init()`.
978//
979//   The resulting pointer has the address 0.
980#[allow(clippy::multiple_unsafe_ops_per_block)]
981const _: () = unsafe {
982    unsafe_impl!(T: ?Sized => Immutable for *const T);
983    unsafe_impl!(T: ?Sized => Immutable for *mut T);
984    unsafe_impl!(T => TryFromBytes for *const T; |c| pointer::is_zeroed(c));
985    unsafe_impl!(T => FromZeros for *const T);
986    unsafe_impl!(T => TryFromBytes for *mut T; |c| pointer::is_zeroed(c));
987    unsafe_impl!(T => FromZeros for *mut T);
988};
989
990// SAFETY: `NonNull<T>` self-evidently does not contain `UnsafeCell`s. This is
991// not a proof, but we are accepting this as a known risk per #1358.
992const _: () = unsafe { unsafe_impl!(T: ?Sized => Immutable for NonNull<T>) };
993
994// SAFETY: Reference types do not contain any `UnsafeCell`s.
995#[allow(clippy::multiple_unsafe_ops_per_block)]
996const _: () = unsafe {
997    unsafe_impl!(T: ?Sized => Immutable for &'_ T);
998    unsafe_impl!(T: ?Sized => Immutable for &'_ mut T);
999};
1000
1001// SAFETY: `Option` is not `#[non_exhaustive]` [1], which means that the types
1002// in its variants cannot change, and no new variants can be added. `Option<T>`
1003// does not contain any `UnsafeCell`s outside of `T`. [1]
1004//
1005// [1] https://doc.rust-lang.org/core/option/enum.Option.html
1006const _: () = unsafe { unsafe_impl!(T: Immutable => Immutable for Option<T>) };
1007
1008// SIMD support
1009//
1010// Per the Unsafe Code Guidelines Reference [1]:
1011//
1012//   Packed SIMD vector types are `repr(simd)` homogeneous tuple-structs
1013//   containing `N` elements of type `T` where `N` is a power-of-two and the
1014//   size and alignment requirements of `T` are equal:
1015//
1016//   ```rust
1017//   #[repr(simd)]
1018//   struct Vector<T, N>(T_0, ..., T_(N - 1));
1019//   ```
1020//
1021//   ...
1022//
1023//   The size of `Vector` is `N * size_of::<T>()` and its alignment is an
1024//   implementation-defined function of `T` and `N` greater than or equal to
1025//   `align_of::<T>()`.
1026//
1027//   ...
1028//
1029//   Vector elements are laid out in source field order, enabling random access
1030//   to vector elements by reinterpreting the vector as an array:
1031//
1032//   ```rust
1033//   union U {
1034//      vec: Vector<T, N>,
1035//      arr: [T; N]
1036//   }
1037//
1038//   assert_eq!(size_of::<Vector<T, N>>(), size_of::<[T; N]>());
1039//   assert!(align_of::<Vector<T, N>>() >= align_of::<[T; N]>());
1040//
1041//   unsafe {
1042//     let u = U { vec: Vector<T, N>(t_0, ..., t_(N - 1)) };
1043//
1044//     assert_eq!(u.vec.0, u.arr[0]);
1045//     // ...
1046//     assert_eq!(u.vec.(N - 1), u.arr[N - 1]);
1047//   }
1048//   ```
1049//
1050// Given this background, we can observe that:
1051// - The size and bit pattern requirements of a SIMD type are equivalent to the
1052//   equivalent array type. Thus, for any SIMD type whose primitive `T` is
1053//   `Immutable`, `TryFromBytes`, `FromZeros`, `FromBytes`, or `IntoBytes`, that
1054//   SIMD type is also `Immutable`, `TryFromBytes`, `FromZeros`, `FromBytes`, or
1055//   `IntoBytes` respectively.
1056// - Since no upper bound is placed on the alignment, no SIMD type can be
1057//   guaranteed to be `Unaligned`.
1058//
1059// Also per [1]:
1060//
1061//   This chapter represents the consensus from issue #38. The statements in
1062//   here are not (yet) "guaranteed" not to change until an RFC ratifies them.
1063//
1064// See issue #38 [2]. While this behavior is not technically guaranteed, the
1065// likelihood that the behavior will change such that SIMD types are no longer
1066// `TryFromBytes`, `FromZeros`, `FromBytes`, or `IntoBytes` is next to zero, as
1067// that would defeat the entire purpose of SIMD types. Nonetheless, we put this
1068// behavior behind the `simd` Cargo feature, which requires consumers to opt
1069// into this stability hazard.
1070//
1071// [1] https://rust-lang.github.io/unsafe-code-guidelines/layout/packed-simd-vectors.html
1072// [2] https://github.com/rust-lang/unsafe-code-guidelines/issues/38
1073#[cfg(feature = "simd")]
1074#[cfg_attr(doc_cfg, doc(cfg(feature = "simd")))]
1075mod simd {
1076    /// Defines a module which implements `TryFromBytes`, `FromZeros`,
1077    /// `FromBytes`, and `IntoBytes` for a set of types from a module in
1078    /// `core::arch`.
1079    ///
1080    /// `$arch` is both the name of the defined module and the name of the
1081    /// module in `core::arch`, and `$typ` is the list of items from that module
1082    /// to implement `FromZeros`, `FromBytes`, and `IntoBytes` for.
1083    #[allow(unused_macros)] // `allow(unused_macros)` is needed because some
1084                            // target/feature combinations don't emit any impls
1085                            // and thus don't use this macro.
1086    macro_rules! simd_arch_mod {
1087        ($(#[cfg $cfg:tt])* $(#[cfg_attr $cfg_attr:tt])? $arch:ident, $mod:ident, $($typ:ident),*) => {
1088            $(#[cfg $cfg])*
1089            #[cfg_attr(doc_cfg, doc(cfg $($cfg)*))]
1090            $(#[cfg_attr $cfg_attr])?
1091            mod $mod {
1092                use core::arch::$arch::{$($typ),*};
1093
1094                use crate::*;
1095                impl_known_layout!($($typ),*);
1096                // SAFETY: See comment on module definition for justification.
1097                #[allow(clippy::multiple_unsafe_ops_per_block)]
1098                const _: () = unsafe {
1099                    $( unsafe_impl!($typ: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes); )*
1100                };
1101            }
1102        };
1103    }
1104
1105    #[rustfmt::skip]
1106    const _: () = {
1107        simd_arch_mod!(
1108            #[cfg(target_arch = "x86")]
1109            x86, x86, __m128, __m128d, __m128i, __m256, __m256d, __m256i
1110        );
1111        #[cfg(not(no_zerocopy_simd_x86_avx12_1_89_0))]
1112        simd_arch_mod!(
1113            #[cfg(target_arch = "x86")]
1114            #[cfg_attr(doc_cfg, doc(cfg(rust = "1.89.0")))]
1115            x86, x86_nightly, __m512bh, __m512, __m512d, __m512i
1116        );
1117        simd_arch_mod!(
1118            #[cfg(target_arch = "x86_64")]
1119            x86_64, x86_64, __m128, __m128d, __m128i, __m256, __m256d, __m256i
1120        );
1121        #[cfg(not(no_zerocopy_simd_x86_avx12_1_89_0))]
1122        simd_arch_mod!(
1123            #[cfg(target_arch = "x86_64")]
1124            #[cfg_attr(doc_cfg, doc(cfg(rust = "1.89.0")))]
1125            x86_64, x86_64_nightly, __m512bh, __m512, __m512d, __m512i
1126        );
1127        simd_arch_mod!(
1128            #[cfg(target_arch = "wasm32")]
1129            wasm32, wasm32, v128
1130        );
1131        simd_arch_mod!(
1132            #[cfg(all(feature = "simd-nightly", target_arch = "powerpc"))]
1133            powerpc, powerpc, vector_bool_long, vector_double, vector_signed_long, vector_unsigned_long
1134        );
1135        simd_arch_mod!(
1136            #[cfg(all(feature = "simd-nightly", target_arch = "powerpc64"))]
1137            powerpc64, powerpc64, vector_bool_long, vector_double, vector_signed_long, vector_unsigned_long
1138        );
1139        #[cfg(not(no_zerocopy_aarch64_simd_1_59_0))]
1140        simd_arch_mod!(
1141            // NOTE(https://github.com/rust-lang/stdarch/issues/1484): NEON intrinsics are currently
1142            // broken on big-endian platforms.
1143            #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
1144            #[cfg_attr(doc_cfg, doc(cfg(rust = "1.59.0")))]
1145            aarch64, aarch64, float32x2_t, float32x4_t, float64x1_t, float64x2_t, int8x8_t, int8x8x2_t,
1146            int8x8x3_t, int8x8x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int16x4_t,
1147            int16x8_t, int32x2_t, int32x4_t, int64x1_t, int64x2_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t,
1148            poly8x8x4_t, poly8x16_t, poly8x16x2_t, poly8x16x3_t, poly8x16x4_t, poly16x4_t, poly16x8_t,
1149            poly64x1_t, poly64x2_t, uint8x8_t, uint8x8x2_t, uint8x8x3_t, uint8x8x4_t, uint8x16_t,
1150            uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint16x4_t, uint16x4x2_t, uint16x4x3_t,
1151            uint16x4x4_t, uint16x8_t, uint32x2_t, uint32x4_t, uint64x1_t, uint64x2_t
1152        );
1153    };
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use super::*;
1159    use crate::pointer::invariant;
1160
1161    #[test]
1162    fn test_impls() {
1163        // A type that can supply test cases for testing
1164        // `TryFromBytes::is_bit_valid`. All types passed to `assert_impls!`
1165        // must implement this trait; that macro uses it to generate runtime
1166        // tests for `TryFromBytes` impls.
1167        //
1168        // All `T: FromBytes` types are provided with a blanket impl. Other
1169        // types must implement `TryFromBytesTestable` directly (ie using
1170        // `impl_try_from_bytes_testable!`).
1171        trait TryFromBytesTestable {
1172            fn with_passing_test_cases<F: Fn(Box<Self>)>(f: F);
1173            fn with_failing_test_cases<F: Fn(&mut [u8])>(f: F);
1174        }
1175
1176        impl<T: FromBytes> TryFromBytesTestable for T {
1177            fn with_passing_test_cases<F: Fn(Box<Self>)>(f: F) {
1178                // Test with a zeroed value.
1179                f(Self::new_box_zeroed().unwrap());
1180
1181                let ffs = {
1182                    let mut t = Self::new_zeroed();
1183                    let ptr: *mut T = &mut t;
1184                    // SAFETY: `T: FromBytes`
1185                    unsafe { ptr::write_bytes(ptr.cast::<u8>(), 0xFF, mem::size_of::<T>()) };
1186                    t
1187                };
1188
1189                // Test with a value initialized with 0xFF.
1190                f(Box::new(ffs));
1191            }
1192
1193            fn with_failing_test_cases<F: Fn(&mut [u8])>(_f: F) {}
1194        }
1195
1196        macro_rules! impl_try_from_bytes_testable_for_null_pointer_optimization {
1197            ($($tys:ty),*) => {
1198                $(
1199                    impl TryFromBytesTestable for Option<$tys> {
1200                        fn with_passing_test_cases<F: Fn(Box<Self>)>(f: F) {
1201                            // Test with a zeroed value.
1202                            f(Box::new(None));
1203                        }
1204
1205                        fn with_failing_test_cases<F: Fn(&mut [u8])>(f: F) {
1206                            for pos in 0..mem::size_of::<Self>() {
1207                                let mut bytes = [0u8; mem::size_of::<Self>()];
1208                                bytes[pos] = 0x01;
1209                                f(&mut bytes[..]);
1210                            }
1211                        }
1212                    }
1213                )*
1214            };
1215        }
1216
1217        // Implements `TryFromBytesTestable`.
1218        macro_rules! impl_try_from_bytes_testable {
1219            // Base case for recursion (when the list of types has run out).
1220            (=> @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => {};
1221            // Implements for type(s) with no type parameters.
1222            ($ty:ty $(,$tys:ty)* => @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => {
1223                impl TryFromBytesTestable for $ty {
1224                    impl_try_from_bytes_testable!(
1225                        @methods     @success $($success_case),*
1226                                 $(, @failure $($failure_case),*)?
1227                    );
1228                }
1229                impl_try_from_bytes_testable!($($tys),* => @success $($success_case),* $(, @failure $($failure_case),*)?);
1230            };
1231            // Implements for multiple types with no type parameters.
1232            ($($($ty:ty),* => @success $($success_case:expr), * $(, @failure $($failure_case:expr),*)?;)*) => {
1233                $(
1234                    impl_try_from_bytes_testable!($($ty),* => @success $($success_case),* $(, @failure $($failure_case),*)*);
1235                )*
1236            };
1237            // Implements only the methods; caller must invoke this from inside
1238            // an impl block.
1239            (@methods @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => {
1240                fn with_passing_test_cases<F: Fn(Box<Self>)>(_f: F) {
1241                    $(
1242                        _f(Box::<Self>::from($success_case));
1243                    )*
1244                }
1245
1246                fn with_failing_test_cases<F: Fn(&mut [u8])>(_f: F) {
1247                    $($(
1248                        let mut case = $failure_case;
1249                        _f(case.as_mut_bytes());
1250                    )*)?
1251                }
1252            };
1253        }
1254
1255        impl_try_from_bytes_testable_for_null_pointer_optimization!(
1256            Box<UnsafeCell<NotZerocopy>>,
1257            &'static UnsafeCell<NotZerocopy>,
1258            &'static mut UnsafeCell<NotZerocopy>,
1259            NonNull<UnsafeCell<NotZerocopy>>,
1260            fn(),
1261            FnManyArgs,
1262            extern "C" fn(),
1263            ECFnManyArgs
1264        );
1265
1266        macro_rules! bx {
1267            ($e:expr) => {
1268                Box::new($e)
1269            };
1270        }
1271
1272        // Note that these impls are only for types which are not `FromBytes`.
1273        // `FromBytes` types are covered by a preceding blanket impl.
1274        impl_try_from_bytes_testable!(
1275            bool => @success true, false,
1276                    @failure 2u8, 3u8, 0xFFu8;
1277            char => @success '\u{0}', '\u{D7FF}', '\u{E000}', '\u{10FFFF}',
1278                    @failure 0xD800u32, 0xDFFFu32, 0x110000u32;
1279            str  => @success "", "hello", "❤️🧡💛💚💙💜",
1280                    @failure [0, 159, 146, 150];
1281            [u8] => @success vec![].into_boxed_slice(), vec![0, 1, 2].into_boxed_slice();
1282            NonZeroU8, NonZeroI8, NonZeroU16, NonZeroI16, NonZeroU32,
1283            NonZeroI32, NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128,
1284            NonZeroUsize, NonZeroIsize
1285                => @success Self::new(1).unwrap(),
1286                   // Doing this instead of `0` ensures that we always satisfy
1287                   // the size and alignment requirements of `Self` (whereas `0`
1288                   // may be any integer type with a different size or alignment
1289                   // than some `NonZeroXxx` types).
1290                   @failure Option::<Self>::None;
1291            [bool; 0] => @success [];
1292            [bool; 1]
1293                => @success [true], [false],
1294                   @failure [2u8], [3u8], [0xFFu8];
1295            [bool]
1296                => @success vec![true, false].into_boxed_slice(), vec![false, true].into_boxed_slice(),
1297                    @failure [2u8], [3u8], [0xFFu8], [0u8, 1u8, 2u8];
1298            Unalign<bool>
1299                => @success Unalign::new(false), Unalign::new(true),
1300                   @failure 2u8, 0xFFu8;
1301            ManuallyDrop<bool>
1302                => @success ManuallyDrop::new(false), ManuallyDrop::new(true),
1303                   @failure 2u8, 0xFFu8;
1304            ManuallyDrop<[u8]>
1305                => @success bx!(ManuallyDrop::new([])), bx!(ManuallyDrop::new([0u8])), bx!(ManuallyDrop::new([0u8, 1u8]));
1306            ManuallyDrop<[bool]>
1307                => @success bx!(ManuallyDrop::new([])), bx!(ManuallyDrop::new([false])), bx!(ManuallyDrop::new([false, true])),
1308                   @failure [2u8], [3u8], [0xFFu8], [0u8, 1u8, 2u8];
1309            ManuallyDrop<[UnsafeCell<u8>]>
1310                => @success bx!(ManuallyDrop::new([UnsafeCell::new(0)])), bx!(ManuallyDrop::new([UnsafeCell::new(0), UnsafeCell::new(1)]));
1311            ManuallyDrop<[UnsafeCell<bool>]>
1312                => @success bx!(ManuallyDrop::new([UnsafeCell::new(false)])), bx!(ManuallyDrop::new([UnsafeCell::new(false), UnsafeCell::new(true)])),
1313                @failure [2u8], [3u8], [0xFFu8], [0u8, 1u8, 2u8];
1314            Wrapping<bool>
1315                => @success Wrapping(false), Wrapping(true),
1316                    @failure 2u8, 0xFFu8;
1317            *const NotZerocopy
1318                => @success ptr::null::<NotZerocopy>(),
1319                   @failure [0x01; mem::size_of::<*const NotZerocopy>()];
1320            *mut NotZerocopy
1321                => @success ptr::null_mut::<NotZerocopy>(),
1322                   @failure [0x01; mem::size_of::<*mut NotZerocopy>()];
1323        );
1324
1325        // Use the trick described in [1] to allow us to call methods
1326        // conditional on certain trait bounds.
1327        //
1328        // In all of these cases, methods return `Option<R>`, where `R` is the
1329        // return type of the method we're conditionally calling. The "real"
1330        // implementations (the ones defined in traits using `&self`) return
1331        // `Some`, and the default implementations (the ones defined as inherent
1332        // methods using `&mut self`) return `None`.
1333        //
1334        // [1] https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md
1335        mod autoref_trick {
1336            use super::*;
1337
1338            pub(super) struct AutorefWrapper<T: ?Sized>(pub(super) PhantomData<T>);
1339
1340            pub(super) trait TestIsBitValidShared<T: ?Sized> {
1341                #[allow(clippy::needless_lifetimes)]
1342                fn test_is_bit_valid_shared<'ptr, A: invariant::Reference>(
1343                    &self,
1344                    candidate: Maybe<'ptr, T, A>,
1345                ) -> Option<bool>;
1346            }
1347
1348            impl<T: TryFromBytes + Immutable + ?Sized> TestIsBitValidShared<T> for AutorefWrapper<T> {
1349                #[allow(clippy::needless_lifetimes)]
1350                fn test_is_bit_valid_shared<'ptr, A: invariant::Reference>(
1351                    &self,
1352                    candidate: Maybe<'ptr, T, A>,
1353                ) -> Option<bool> {
1354                    Some(T::is_bit_valid(candidate))
1355                }
1356            }
1357
1358            pub(super) trait TestTryFromRef<T: ?Sized> {
1359                #[allow(clippy::needless_lifetimes)]
1360                fn test_try_from_ref<'bytes>(
1361                    &self,
1362                    bytes: &'bytes [u8],
1363                ) -> Option<Option<&'bytes T>>;
1364            }
1365
1366            impl<T: TryFromBytes + Immutable + KnownLayout + ?Sized> TestTryFromRef<T> for AutorefWrapper<T> {
1367                #[allow(clippy::needless_lifetimes)]
1368                fn test_try_from_ref<'bytes>(
1369                    &self,
1370                    bytes: &'bytes [u8],
1371                ) -> Option<Option<&'bytes T>> {
1372                    Some(T::try_ref_from_bytes(bytes).ok())
1373                }
1374            }
1375
1376            pub(super) trait TestTryFromMut<T: ?Sized> {
1377                #[allow(clippy::needless_lifetimes)]
1378                fn test_try_from_mut<'bytes>(
1379                    &self,
1380                    bytes: &'bytes mut [u8],
1381                ) -> Option<Option<&'bytes mut T>>;
1382            }
1383
1384            impl<T: TryFromBytes + IntoBytes + KnownLayout + ?Sized> TestTryFromMut<T> for AutorefWrapper<T> {
1385                #[allow(clippy::needless_lifetimes)]
1386                fn test_try_from_mut<'bytes>(
1387                    &self,
1388                    bytes: &'bytes mut [u8],
1389                ) -> Option<Option<&'bytes mut T>> {
1390                    Some(T::try_mut_from_bytes(bytes).ok())
1391                }
1392            }
1393
1394            pub(super) trait TestTryReadFrom<T> {
1395                fn test_try_read_from(&self, bytes: &[u8]) -> Option<Option<T>>;
1396            }
1397
1398            impl<T: TryFromBytes> TestTryReadFrom<T> for AutorefWrapper<T> {
1399                fn test_try_read_from(&self, bytes: &[u8]) -> Option<Option<T>> {
1400                    Some(T::try_read_from_bytes(bytes).ok())
1401                }
1402            }
1403
1404            pub(super) trait TestAsBytes<T: ?Sized> {
1405                #[allow(clippy::needless_lifetimes)]
1406                fn test_as_bytes<'slf, 't>(&'slf self, t: &'t T) -> Option<&'t [u8]>;
1407            }
1408
1409            impl<T: IntoBytes + Immutable + ?Sized> TestAsBytes<T> for AutorefWrapper<T> {
1410                #[allow(clippy::needless_lifetimes)]
1411                fn test_as_bytes<'slf, 't>(&'slf self, t: &'t T) -> Option<&'t [u8]> {
1412                    Some(t.as_bytes())
1413                }
1414            }
1415        }
1416
1417        use autoref_trick::*;
1418
1419        // Asserts that `$ty` is one of a list of types which are allowed to not
1420        // provide a "real" implementation for `$fn_name`. Since the
1421        // `autoref_trick` machinery fails silently, this allows us to ensure
1422        // that the "default" impls are only being used for types which we
1423        // expect.
1424        //
1425        // Note that, since this is a runtime test, it is possible to have an
1426        // allowlist which is too restrictive if the function in question is
1427        // never called for a particular type. For example, if `as_bytes` is not
1428        // supported for a particular type, and so `test_as_bytes` returns
1429        // `None`, methods such as `test_try_from_ref` may never be called for
1430        // that type. As a result, it's possible that, for example, adding
1431        // `as_bytes` support for a type would cause other allowlist assertions
1432        // to fail. This means that allowlist assertion failures should not
1433        // automatically be taken as a sign of a bug.
1434        macro_rules! assert_on_allowlist {
1435            ($fn_name:ident($ty:ty) $(: $($tys:ty),*)?) => {{
1436                use core::any::TypeId;
1437
1438                let allowlist: &[TypeId] = &[ $($(TypeId::of::<$tys>()),*)? ];
1439                let allowlist_names: &[&str] = &[ $($(stringify!($tys)),*)? ];
1440
1441                let id = TypeId::of::<$ty>();
1442                assert!(allowlist.contains(&id), "{} is not on allowlist for {}: {:?}", stringify!($ty), stringify!($fn_name), allowlist_names);
1443            }};
1444        }
1445
1446        // Asserts that `$ty` implements any `$trait` and doesn't implement any
1447        // `!$trait`. Note that all `$trait`s must come before any `!$trait`s.
1448        //
1449        // For `T: TryFromBytes`, uses `TryFromBytesTestable` to test success
1450        // and failure cases.
1451        macro_rules! assert_impls {
1452            ($ty:ty: TryFromBytes) => {
1453                // "Default" implementations that match the "real"
1454                // implementations defined in the `autoref_trick` module above.
1455                #[allow(unused, non_local_definitions)]
1456                impl AutorefWrapper<$ty> {
1457                    #[allow(clippy::needless_lifetimes)]
1458                    fn test_is_bit_valid_shared<'ptr, A: invariant::Reference>(
1459                        &mut self,
1460                        candidate: Maybe<'ptr, $ty, A>,
1461                    ) -> Option<bool> {
1462                        assert_on_allowlist!(
1463                            test_is_bit_valid_shared($ty):
1464                            ManuallyDrop<UnsafeCell<()>>,
1465                            ManuallyDrop<[UnsafeCell<u8>]>,
1466                            ManuallyDrop<[UnsafeCell<bool>]>,
1467                            CoreMaybeUninit<NotZerocopy>,
1468                            CoreMaybeUninit<UnsafeCell<()>>,
1469                            Wrapping<UnsafeCell<()>>
1470                        );
1471
1472                        None
1473                    }
1474
1475                    #[allow(clippy::needless_lifetimes)]
1476                    fn test_try_from_ref<'bytes>(&mut self, _bytes: &'bytes [u8]) -> Option<Option<&'bytes $ty>> {
1477                        assert_on_allowlist!(
1478                            test_try_from_ref($ty):
1479                            ManuallyDrop<[UnsafeCell<bool>]>
1480                        );
1481
1482                        None
1483                    }
1484
1485                    #[allow(clippy::needless_lifetimes)]
1486                    fn test_try_from_mut<'bytes>(&mut self, _bytes: &'bytes mut [u8]) -> Option<Option<&'bytes mut $ty>> {
1487                        assert_on_allowlist!(
1488                            test_try_from_mut($ty):
1489                            Option<Box<UnsafeCell<NotZerocopy>>>,
1490                            Option<&'static UnsafeCell<NotZerocopy>>,
1491                            Option<&'static mut UnsafeCell<NotZerocopy>>,
1492                            Option<NonNull<UnsafeCell<NotZerocopy>>>,
1493                            Option<fn()>,
1494                            Option<FnManyArgs>,
1495                            Option<extern "C" fn()>,
1496                            Option<ECFnManyArgs>,
1497                            *const NotZerocopy,
1498                            *mut NotZerocopy
1499                        );
1500
1501                        None
1502                    }
1503
1504                    fn test_try_read_from(&mut self, _bytes: &[u8]) -> Option<Option<&$ty>> {
1505                        assert_on_allowlist!(
1506                            test_try_read_from($ty):
1507                            str,
1508                            ManuallyDrop<[u8]>,
1509                            ManuallyDrop<[bool]>,
1510                            ManuallyDrop<[UnsafeCell<bool>]>,
1511                            [u8],
1512                            [bool]
1513                        );
1514
1515                        None
1516                    }
1517
1518                    fn test_as_bytes(&mut self, _t: &$ty) -> Option<&[u8]> {
1519                        assert_on_allowlist!(
1520                            test_as_bytes($ty):
1521                            Option<&'static UnsafeCell<NotZerocopy>>,
1522                            Option<&'static mut UnsafeCell<NotZerocopy>>,
1523                            Option<NonNull<UnsafeCell<NotZerocopy>>>,
1524                            Option<Box<UnsafeCell<NotZerocopy>>>,
1525                            Option<fn()>,
1526                            Option<FnManyArgs>,
1527                            Option<extern "C" fn()>,
1528                            Option<ECFnManyArgs>,
1529                            CoreMaybeUninit<u8>,
1530                            CoreMaybeUninit<NotZerocopy>,
1531                            CoreMaybeUninit<UnsafeCell<()>>,
1532                            ManuallyDrop<UnsafeCell<()>>,
1533                            ManuallyDrop<[UnsafeCell<u8>]>,
1534                            ManuallyDrop<[UnsafeCell<bool>]>,
1535                            Wrapping<UnsafeCell<()>>,
1536                            *const NotZerocopy,
1537                            *mut NotZerocopy
1538                        );
1539
1540                        None
1541                    }
1542                }
1543
1544                <$ty as TryFromBytesTestable>::with_passing_test_cases(|mut val| {
1545                    // FIXME(#494): These tests only get exercised for types
1546                    // which are `IntoBytes`. Once we implement #494, we should
1547                    // be able to support non-`IntoBytes` types by zeroing
1548                    // padding.
1549
1550                    // We define `w` and `ww` since, in the case of the inherent
1551                    // methods, Rust thinks they're both borrowed mutably at the
1552                    // same time (given how we use them below). If we just
1553                    // defined a single `w` and used it for multiple operations,
1554                    // this would conflict.
1555                    //
1556                    // We `#[allow(unused_mut]` for the cases where the "real"
1557                    // impls are used, which take `&self`.
1558                    #[allow(unused_mut)]
1559                    let (mut w, mut ww) = (AutorefWrapper::<$ty>(PhantomData), AutorefWrapper::<$ty>(PhantomData));
1560
1561                    let c = Ptr::from_ref(&*val);
1562                    let c = c.forget_aligned();
1563                    // SAFETY: FIXME(#899): This is unsound. `$ty` is not
1564                    // necessarily `IntoBytes`, but that's the corner we've
1565                    // backed ourselves into by using `Ptr::from_ref`.
1566                    let c = unsafe { c.assume_initialized() };
1567                    let res = w.test_is_bit_valid_shared(c);
1568                    if let Some(res) = res {
1569                        assert!(res, "{}::is_bit_valid({:?}) (shared `Ptr`): got false, expected true", stringify!($ty), val);
1570                    }
1571
1572                    let c = Ptr::from_mut(&mut *val);
1573                    let c = c.forget_aligned();
1574                    // SAFETY: FIXME(#899): This is unsound. `$ty` is not
1575                    // necessarily `IntoBytes`, but that's the corner we've
1576                    // backed ourselves into by using `Ptr::from_ref`.
1577                    let c = unsafe { c.assume_initialized() };
1578                    let res = <$ty as TryFromBytes>::is_bit_valid(c);
1579                    assert!(res, "{}::is_bit_valid({:?}) (exclusive `Ptr`): got false, expected true", stringify!($ty), val);
1580
1581                    // `bytes` is `Some(val.as_bytes())` if `$ty: IntoBytes +
1582                    // Immutable` and `None` otherwise.
1583                    let bytes = w.test_as_bytes(&*val);
1584
1585                    // The inner closure returns
1586                    // `Some($ty::try_ref_from_bytes(bytes))` if `$ty:
1587                    // Immutable` and `None` otherwise.
1588                    let res = bytes.and_then(|bytes| ww.test_try_from_ref(bytes));
1589                    if let Some(res) = res {
1590                        assert!(res.is_some(), "{}::try_ref_from_bytes({:?}): got `None`, expected `Some`", stringify!($ty), val);
1591                    }
1592
1593                    if let Some(bytes) = bytes {
1594                        // We need to get a mutable byte slice, and so we clone
1595                        // into a `Vec`. However, we also need these bytes to
1596                        // satisfy `$ty`'s alignment requirement, which isn't
1597                        // guaranteed for `Vec<u8>`. In order to get around
1598                        // this, we create a `Vec` which is twice as long as we
1599                        // need. There is guaranteed to be an aligned byte range
1600                        // of size `size_of_val(val)` within that range.
1601                        let val = &*val;
1602                        let size = mem::size_of_val(val);
1603                        let align = mem::align_of_val(val);
1604
1605                        let mut vec = bytes.to_vec();
1606                        vec.extend(bytes);
1607                        let slc = vec.as_slice();
1608                        let offset = slc.as_ptr().align_offset(align);
1609                        let bytes_mut = &mut vec.as_mut_slice()[offset..offset+size];
1610                        bytes_mut.copy_from_slice(bytes);
1611
1612                        let res = ww.test_try_from_mut(bytes_mut);
1613                        if let Some(res) = res {
1614                            assert!(res.is_some(), "{}::try_mut_from_bytes({:?}): got `None`, expected `Some`", stringify!($ty), val);
1615                        }
1616                    }
1617
1618                    let res = bytes.and_then(|bytes| ww.test_try_read_from(bytes));
1619                    if let Some(res) = res {
1620                        assert!(res.is_some(), "{}::try_read_from_bytes({:?}): got `None`, expected `Some`", stringify!($ty), val);
1621                    }
1622                });
1623                #[allow(clippy::as_conversions)]
1624                <$ty as TryFromBytesTestable>::with_failing_test_cases(|c| {
1625                    #[allow(unused_mut)] // For cases where the "real" impls are used, which take `&self`.
1626                    let mut w = AutorefWrapper::<$ty>(PhantomData);
1627
1628                    // This is `Some($ty::try_ref_from_bytes(c))` if `$ty:
1629                    // Immutable` and `None` otherwise.
1630                    let res = w.test_try_from_ref(c);
1631                    if let Some(res) = res {
1632                        assert!(res.is_none(), "{}::try_ref_from_bytes({:?}): got Some, expected None", stringify!($ty), c);
1633                    }
1634
1635                    let res = w.test_try_from_mut(c);
1636                    if let Some(res) = res {
1637                        assert!(res.is_none(), "{}::try_mut_from_bytes({:?}): got Some, expected None", stringify!($ty), c);
1638                    }
1639
1640
1641                    let res = w.test_try_read_from(c);
1642                    if let Some(res) = res {
1643                        assert!(res.is_none(), "{}::try_read_from_bytes({:?}): got Some, expected None", stringify!($ty), c);
1644                    }
1645                });
1646
1647                #[allow(dead_code)]
1648                const _: () = { static_assertions::assert_impl_all!($ty: TryFromBytes); };
1649            };
1650            ($ty:ty: $trait:ident) => {
1651                #[allow(dead_code)]
1652                const _: () = { static_assertions::assert_impl_all!($ty: $trait); };
1653            };
1654            ($ty:ty: !$trait:ident) => {
1655                #[allow(dead_code)]
1656                const _: () = { static_assertions::assert_not_impl_any!($ty: $trait); };
1657            };
1658            ($ty:ty: $($trait:ident),* $(,)? $(!$negative_trait:ident),*) => {
1659                $(
1660                    assert_impls!($ty: $trait);
1661                )*
1662
1663                $(
1664                    assert_impls!($ty: !$negative_trait);
1665                )*
1666            };
1667        }
1668
1669        // NOTE: The negative impl assertions here are not necessarily
1670        // prescriptive. They merely serve as change detectors to make sure
1671        // we're aware of what trait impls are getting added with a given
1672        // change. Of course, some impls would be invalid (e.g., `bool:
1673        // FromBytes`), and so this change detection is very important.
1674
1675        assert_impls!(
1676            (): KnownLayout,
1677            Immutable,
1678            TryFromBytes,
1679            FromZeros,
1680            FromBytes,
1681            IntoBytes,
1682            Unaligned
1683        );
1684        assert_impls!(
1685            u8: KnownLayout,
1686            Immutable,
1687            TryFromBytes,
1688            FromZeros,
1689            FromBytes,
1690            IntoBytes,
1691            Unaligned
1692        );
1693        assert_impls!(
1694            i8: KnownLayout,
1695            Immutable,
1696            TryFromBytes,
1697            FromZeros,
1698            FromBytes,
1699            IntoBytes,
1700            Unaligned
1701        );
1702        assert_impls!(
1703            u16: KnownLayout,
1704            Immutable,
1705            TryFromBytes,
1706            FromZeros,
1707            FromBytes,
1708            IntoBytes,
1709            !Unaligned
1710        );
1711        assert_impls!(
1712            i16: KnownLayout,
1713            Immutable,
1714            TryFromBytes,
1715            FromZeros,
1716            FromBytes,
1717            IntoBytes,
1718            !Unaligned
1719        );
1720        assert_impls!(
1721            u32: KnownLayout,
1722            Immutable,
1723            TryFromBytes,
1724            FromZeros,
1725            FromBytes,
1726            IntoBytes,
1727            !Unaligned
1728        );
1729        assert_impls!(
1730            i32: KnownLayout,
1731            Immutable,
1732            TryFromBytes,
1733            FromZeros,
1734            FromBytes,
1735            IntoBytes,
1736            !Unaligned
1737        );
1738        assert_impls!(
1739            u64: KnownLayout,
1740            Immutable,
1741            TryFromBytes,
1742            FromZeros,
1743            FromBytes,
1744            IntoBytes,
1745            !Unaligned
1746        );
1747        assert_impls!(
1748            i64: KnownLayout,
1749            Immutable,
1750            TryFromBytes,
1751            FromZeros,
1752            FromBytes,
1753            IntoBytes,
1754            !Unaligned
1755        );
1756        assert_impls!(
1757            u128: KnownLayout,
1758            Immutable,
1759            TryFromBytes,
1760            FromZeros,
1761            FromBytes,
1762            IntoBytes,
1763            !Unaligned
1764        );
1765        assert_impls!(
1766            i128: KnownLayout,
1767            Immutable,
1768            TryFromBytes,
1769            FromZeros,
1770            FromBytes,
1771            IntoBytes,
1772            !Unaligned
1773        );
1774        assert_impls!(
1775            usize: KnownLayout,
1776            Immutable,
1777            TryFromBytes,
1778            FromZeros,
1779            FromBytes,
1780            IntoBytes,
1781            !Unaligned
1782        );
1783        assert_impls!(
1784            isize: KnownLayout,
1785            Immutable,
1786            TryFromBytes,
1787            FromZeros,
1788            FromBytes,
1789            IntoBytes,
1790            !Unaligned
1791        );
1792        #[cfg(feature = "float-nightly")]
1793        assert_impls!(
1794            f16: KnownLayout,
1795            Immutable,
1796            TryFromBytes,
1797            FromZeros,
1798            FromBytes,
1799            IntoBytes,
1800            !Unaligned
1801        );
1802        assert_impls!(
1803            f32: KnownLayout,
1804            Immutable,
1805            TryFromBytes,
1806            FromZeros,
1807            FromBytes,
1808            IntoBytes,
1809            !Unaligned
1810        );
1811        assert_impls!(
1812            f64: KnownLayout,
1813            Immutable,
1814            TryFromBytes,
1815            FromZeros,
1816            FromBytes,
1817            IntoBytes,
1818            !Unaligned
1819        );
1820        #[cfg(feature = "float-nightly")]
1821        assert_impls!(
1822            f128: KnownLayout,
1823            Immutable,
1824            TryFromBytes,
1825            FromZeros,
1826            FromBytes,
1827            IntoBytes,
1828            !Unaligned
1829        );
1830        assert_impls!(
1831            bool: KnownLayout,
1832            Immutable,
1833            TryFromBytes,
1834            FromZeros,
1835            IntoBytes,
1836            Unaligned,
1837            !FromBytes
1838        );
1839        assert_impls!(
1840            char: KnownLayout,
1841            Immutable,
1842            TryFromBytes,
1843            FromZeros,
1844            IntoBytes,
1845            !FromBytes,
1846            !Unaligned
1847        );
1848        assert_impls!(
1849            str: KnownLayout,
1850            Immutable,
1851            TryFromBytes,
1852            FromZeros,
1853            IntoBytes,
1854            Unaligned,
1855            !FromBytes
1856        );
1857
1858        assert_impls!(
1859            NonZeroU8: KnownLayout,
1860            Immutable,
1861            TryFromBytes,
1862            IntoBytes,
1863            Unaligned,
1864            !FromZeros,
1865            !FromBytes
1866        );
1867        assert_impls!(
1868            NonZeroI8: KnownLayout,
1869            Immutable,
1870            TryFromBytes,
1871            IntoBytes,
1872            Unaligned,
1873            !FromZeros,
1874            !FromBytes
1875        );
1876        assert_impls!(
1877            NonZeroU16: KnownLayout,
1878            Immutable,
1879            TryFromBytes,
1880            IntoBytes,
1881            !FromBytes,
1882            !Unaligned
1883        );
1884        assert_impls!(
1885            NonZeroI16: KnownLayout,
1886            Immutable,
1887            TryFromBytes,
1888            IntoBytes,
1889            !FromBytes,
1890            !Unaligned
1891        );
1892        assert_impls!(
1893            NonZeroU32: KnownLayout,
1894            Immutable,
1895            TryFromBytes,
1896            IntoBytes,
1897            !FromBytes,
1898            !Unaligned
1899        );
1900        assert_impls!(
1901            NonZeroI32: KnownLayout,
1902            Immutable,
1903            TryFromBytes,
1904            IntoBytes,
1905            !FromBytes,
1906            !Unaligned
1907        );
1908        assert_impls!(
1909            NonZeroU64: KnownLayout,
1910            Immutable,
1911            TryFromBytes,
1912            IntoBytes,
1913            !FromBytes,
1914            !Unaligned
1915        );
1916        assert_impls!(
1917            NonZeroI64: KnownLayout,
1918            Immutable,
1919            TryFromBytes,
1920            IntoBytes,
1921            !FromBytes,
1922            !Unaligned
1923        );
1924        assert_impls!(
1925            NonZeroU128: KnownLayout,
1926            Immutable,
1927            TryFromBytes,
1928            IntoBytes,
1929            !FromBytes,
1930            !Unaligned
1931        );
1932        assert_impls!(
1933            NonZeroI128: KnownLayout,
1934            Immutable,
1935            TryFromBytes,
1936            IntoBytes,
1937            !FromBytes,
1938            !Unaligned
1939        );
1940        assert_impls!(
1941            NonZeroUsize: KnownLayout,
1942            Immutable,
1943            TryFromBytes,
1944            IntoBytes,
1945            !FromBytes,
1946            !Unaligned
1947        );
1948        assert_impls!(
1949            NonZeroIsize: KnownLayout,
1950            Immutable,
1951            TryFromBytes,
1952            IntoBytes,
1953            !FromBytes,
1954            !Unaligned
1955        );
1956
1957        assert_impls!(Option<NonZeroU8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
1958        assert_impls!(Option<NonZeroI8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
1959        assert_impls!(Option<NonZeroU16>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1960        assert_impls!(Option<NonZeroI16>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1961        assert_impls!(Option<NonZeroU32>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1962        assert_impls!(Option<NonZeroI32>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1963        assert_impls!(Option<NonZeroU64>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1964        assert_impls!(Option<NonZeroI64>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1965        assert_impls!(Option<NonZeroU128>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1966        assert_impls!(Option<NonZeroI128>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1967        assert_impls!(Option<NonZeroUsize>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1968        assert_impls!(Option<NonZeroIsize>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
1969
1970        // Implements none of the ZC traits.
1971        struct NotZerocopy;
1972
1973        #[rustfmt::skip]
1974        type FnManyArgs = fn(
1975            NotZerocopy, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8,
1976        ) -> (NotZerocopy, NotZerocopy);
1977
1978        // Allowed, because we're not actually using this type for FFI.
1979        #[allow(improper_ctypes_definitions)]
1980        #[rustfmt::skip]
1981        type ECFnManyArgs = extern "C" fn(
1982            NotZerocopy, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8,
1983        ) -> (NotZerocopy, NotZerocopy);
1984
1985        #[cfg(feature = "alloc")]
1986        assert_impls!(Option<Box<UnsafeCell<NotZerocopy>>>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1987        assert_impls!(Option<Box<[UnsafeCell<NotZerocopy>]>>: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1988        assert_impls!(Option<&'static UnsafeCell<NotZerocopy>>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1989        assert_impls!(Option<&'static [UnsafeCell<NotZerocopy>]>: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1990        assert_impls!(Option<&'static mut UnsafeCell<NotZerocopy>>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1991        assert_impls!(Option<&'static mut [UnsafeCell<NotZerocopy>]>: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1992        assert_impls!(Option<NonNull<UnsafeCell<NotZerocopy>>>: KnownLayout, TryFromBytes, FromZeros, Immutable, !FromBytes, !IntoBytes, !Unaligned);
1993        assert_impls!(Option<NonNull<[UnsafeCell<NotZerocopy>]>>: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1994        assert_impls!(Option<fn()>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1995        assert_impls!(Option<FnManyArgs>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1996        assert_impls!(Option<extern "C" fn()>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1997        assert_impls!(Option<ECFnManyArgs>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
1998
1999        assert_impls!(PhantomData<NotZerocopy>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
2000        assert_impls!(PhantomData<UnsafeCell<()>>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
2001        assert_impls!(PhantomData<[u8]>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
2002
2003        assert_impls!(ManuallyDrop<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
2004        // This test is important because it allows us to test our hand-rolled
2005        // implementation of `<ManuallyDrop<T> as TryFromBytes>::is_bit_valid`.
2006        assert_impls!(ManuallyDrop<bool>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
2007        assert_impls!(ManuallyDrop<[u8]>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
2008        // This test is important because it allows us to test our hand-rolled
2009        // implementation of `<ManuallyDrop<T> as TryFromBytes>::is_bit_valid`.
2010        assert_impls!(ManuallyDrop<[bool]>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
2011        assert_impls!(ManuallyDrop<NotZerocopy>: !Immutable, !TryFromBytes, !KnownLayout, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2012        assert_impls!(ManuallyDrop<[NotZerocopy]>: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2013        assert_impls!(ManuallyDrop<UnsafeCell<()>>: KnownLayout, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned, !Immutable);
2014        assert_impls!(ManuallyDrop<[UnsafeCell<u8>]>: KnownLayout, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned, !Immutable);
2015        assert_impls!(ManuallyDrop<[UnsafeCell<bool>]>: KnownLayout, TryFromBytes, FromZeros, IntoBytes, Unaligned, !Immutable, !FromBytes);
2016
2017        assert_impls!(CoreMaybeUninit<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, Unaligned, !IntoBytes);
2018        assert_impls!(CoreMaybeUninit<NotZerocopy>: KnownLayout, TryFromBytes, FromZeros, FromBytes, !Immutable, !IntoBytes, !Unaligned);
2019        assert_impls!(CoreMaybeUninit<UnsafeCell<()>>: KnownLayout, TryFromBytes, FromZeros, FromBytes, Unaligned, !Immutable, !IntoBytes);
2020
2021        assert_impls!(Wrapping<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
2022        // This test is important because it allows us to test our hand-rolled
2023        // implementation of `<Wrapping<T> as TryFromBytes>::is_bit_valid`.
2024        assert_impls!(Wrapping<bool>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
2025        assert_impls!(Wrapping<NotZerocopy>: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2026        assert_impls!(Wrapping<UnsafeCell<()>>: KnownLayout, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned, !Immutable);
2027
2028        assert_impls!(Unalign<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
2029        // This test is important because it allows us to test our hand-rolled
2030        // implementation of `<Unalign<T> as TryFromBytes>::is_bit_valid`.
2031        assert_impls!(Unalign<bool>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
2032        assert_impls!(Unalign<NotZerocopy>: KnownLayout, Unaligned, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes);
2033
2034        assert_impls!(
2035            [u8]: KnownLayout,
2036            Immutable,
2037            TryFromBytes,
2038            FromZeros,
2039            FromBytes,
2040            IntoBytes,
2041            Unaligned
2042        );
2043        assert_impls!(
2044            [bool]: KnownLayout,
2045            Immutable,
2046            TryFromBytes,
2047            FromZeros,
2048            IntoBytes,
2049            Unaligned,
2050            !FromBytes
2051        );
2052        assert_impls!([NotZerocopy]: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2053        assert_impls!(
2054            [u8; 0]: KnownLayout,
2055            Immutable,
2056            TryFromBytes,
2057            FromZeros,
2058            FromBytes,
2059            IntoBytes,
2060            Unaligned,
2061        );
2062        assert_impls!(
2063            [NotZerocopy; 0]: KnownLayout,
2064            !Immutable,
2065            !TryFromBytes,
2066            !FromZeros,
2067            !FromBytes,
2068            !IntoBytes,
2069            !Unaligned
2070        );
2071        assert_impls!(
2072            [u8; 1]: KnownLayout,
2073            Immutable,
2074            TryFromBytes,
2075            FromZeros,
2076            FromBytes,
2077            IntoBytes,
2078            Unaligned,
2079        );
2080        assert_impls!(
2081            [NotZerocopy; 1]: KnownLayout,
2082            !Immutable,
2083            !TryFromBytes,
2084            !FromZeros,
2085            !FromBytes,
2086            !IntoBytes,
2087            !Unaligned
2088        );
2089
2090        assert_impls!(*const NotZerocopy: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2091        assert_impls!(*mut NotZerocopy: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2092        assert_impls!(*const [NotZerocopy]: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2093        assert_impls!(*mut [NotZerocopy]: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2094        assert_impls!(*const dyn Debug: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2095        assert_impls!(*mut dyn Debug: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
2096
2097        #[cfg(feature = "simd")]
2098        {
2099            #[allow(unused_macros)]
2100            macro_rules! test_simd_arch_mod {
2101                ($arch:ident, $($typ:ident),*) => {
2102                    {
2103                        use core::arch::$arch::{$($typ),*};
2104                        use crate::*;
2105                        $( assert_impls!($typ: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned); )*
2106                    }
2107                };
2108            }
2109            #[cfg(target_arch = "x86")]
2110            test_simd_arch_mod!(x86, __m128, __m128d, __m128i, __m256, __m256d, __m256i);
2111
2112            #[cfg(all(not(no_zerocopy_simd_x86_avx12_1_89_0), target_arch = "x86"))]
2113            test_simd_arch_mod!(x86, __m512bh, __m512, __m512d, __m512i);
2114
2115            #[cfg(target_arch = "x86_64")]
2116            test_simd_arch_mod!(x86_64, __m128, __m128d, __m128i, __m256, __m256d, __m256i);
2117
2118            #[cfg(all(not(no_zerocopy_simd_x86_avx12_1_89_0), target_arch = "x86_64"))]
2119            test_simd_arch_mod!(x86_64, __m512bh, __m512, __m512d, __m512i);
2120
2121            #[cfg(target_arch = "wasm32")]
2122            test_simd_arch_mod!(wasm32, v128);
2123
2124            #[cfg(all(feature = "simd-nightly", target_arch = "powerpc"))]
2125            test_simd_arch_mod!(
2126                powerpc,
2127                vector_bool_long,
2128                vector_double,
2129                vector_signed_long,
2130                vector_unsigned_long
2131            );
2132
2133            #[cfg(all(feature = "simd-nightly", target_arch = "powerpc64"))]
2134            test_simd_arch_mod!(
2135                powerpc64,
2136                vector_bool_long,
2137                vector_double,
2138                vector_signed_long,
2139                vector_unsigned_long
2140            );
2141            #[cfg(all(target_arch = "aarch64", not(no_zerocopy_aarch64_simd_1_59_0)))]
2142            #[rustfmt::skip]
2143            test_simd_arch_mod!(
2144                aarch64, float32x2_t, float32x4_t, float64x1_t, float64x2_t, int8x8_t, int8x8x2_t,
2145                int8x8x3_t, int8x8x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int16x4_t,
2146                int16x8_t, int32x2_t, int32x4_t, int64x1_t, int64x2_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t,
2147                poly8x8x4_t, poly8x16_t, poly8x16x2_t, poly8x16x3_t, poly8x16x4_t, poly16x4_t, poly16x8_t,
2148                poly64x1_t, poly64x2_t, uint8x8_t, uint8x8x2_t, uint8x8x3_t, uint8x8x4_t, uint8x16_t,
2149                uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint16x4_t, uint16x4x2_t, uint16x4x3_t,
2150                uint16x4x4_t, uint16x8_t, uint32x2_t, uint32x4_t, uint64x1_t, uint64x2_t
2151            );
2152        }
2153    }
2154}