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