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