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