Skip to main content

zerocopy/
impls.rs

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