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