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