Skip to main content

zerocopy/
lib.rs

1// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0 OR MIT
2//
3// Copyright 2018 The Fuchsia Authors
4//
5// Licensed under the 2-Clause BSD License <LICENSE-BSD or
6// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
7// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
8// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
9// This file may not be copied, modified, or distributed except according to
10// those terms.
11
12// After updating the following doc comment, make sure to run the following
13// command to update `README.md` based on its contents:
14//
15//   (cd .. && cargo -q run --manifest-path tools/generate-readme/Cargo.toml) > README.md
16
17//! ***<span style="font-size: 140%">Fast, safe, <span
18//! style="color:red;">compile error</span>. Pick two.</span>***
19//!
20//! Zerocopy makes zero-cost memory manipulation effortless. We write `unsafe`
21//! so you don't have to.
22//!
23//! *For an overview of what's changed from zerocopy 0.7, check out our [release
24//! notes][release-notes], which include a step-by-step upgrading guide.*
25//!
26//! *Have questions? Need more out of zerocopy? Submit a [customer request
27//! issue][customer-request-issue] or ask the maintainers on
28//! [GitHub][github-q-a] or [Discord][discord]!*
29//!
30//! [customer-request-issue]: https://github.com/google/zerocopy/issues/new/choose
31//! [release-notes]: https://github.com/google/zerocopy/discussions/1680
32//! [github-q-a]: https://github.com/google/zerocopy/discussions/categories/q-a
33//! [discord]: https://discord.gg/MAvWH2R6zk
34//!
35//! # Overview
36//!
37//! ##### Conversion Traits
38//!
39//! Zerocopy provides four derivable traits for zero-cost conversions:
40//! - [`TryFromBytes`] indicates that a type may safely be converted from
41//!   certain byte sequences (conditional on runtime checks)
42//! - [`FromZeros`] indicates that a sequence of zero bytes represents a valid
43//!   instance of a type
44//! - [`FromBytes`] indicates that a type may safely be converted from an
45//!   arbitrary byte sequence
46//! - [`IntoBytes`] indicates that a type may safely be converted *to* a byte
47//!   sequence
48//!
49//! These traits support sized types, slices, and [slice DSTs][slice-dsts].
50//!
51//! [slice-dsts]: KnownLayout#dynamically-sized-types
52//!
53//! ##### Marker Traits
54//!
55//! Zerocopy provides three derivable marker traits that do not provide any
56//! functionality themselves, but are required to call certain methods provided
57//! by the conversion traits:
58//! - [`KnownLayout`] indicates that zerocopy can reason about certain layout
59//!   qualities of a type
60//! - [`Immutable`] indicates that a type is free from interior mutability,
61//!   except by ownership or an exclusive (`&mut`) borrow
62//! - [`Unaligned`] indicates that a type's alignment requirement is 1
63//!
64//! You should generally derive these marker traits whenever possible.
65//!
66//! ##### Conversion Macros
67//!
68//! Zerocopy provides six macros for safe casting between types:
69//!
70//! - ([`try_`][try_transmute])[`transmute`] (conditionally) converts a value of
71//!   one type to a value of another type of the same size
72//! - ([`try_`][try_transmute_mut])[`transmute_mut`] (conditionally) converts a
73//!   mutable reference of one type to a mutable reference of another type of
74//!   the same size
75//! - ([`try_`][try_transmute_ref])[`transmute_ref`] (conditionally) converts a
76//!   mutable or immutable reference of one type to an immutable reference of
77//!   another type of the same size
78//!
79//! These macros perform *compile-time* size and alignment checks, meaning that
80//! unconditional casts have zero cost at runtime. Conditional casts do not need
81//! to validate size or alignment runtime, but do need to validate contents.
82//!
83//! These macros cannot be used in generic contexts. For generic conversions,
84//! use the methods defined by the [conversion traits](#conversion-traits).
85//!
86//! ##### Byteorder-Aware Numerics
87//!
88//! Zerocopy provides byte-order aware integer types that support these
89//! conversions; see the [`byteorder`] module. These types are especially useful
90//! for network parsing.
91//!
92//! # Cargo Features
93//!
94//! - **`alloc`**
95//!   By default, `zerocopy` is `no_std`. When the `alloc` feature is enabled,
96//!   the `alloc` crate is added as a dependency, and some allocation-related
97//!   functionality is added.
98//!
99//! - **`std`**
100//!   By default, `zerocopy` is `no_std`. When the `std` feature is enabled, the
101//!   `std` crate is added as a dependency (ie, `no_std` is disabled), and
102//!   support for some `std` types is added. `std` implies `alloc`.
103//!
104//! - **`derive`**
105//!   Provides derives for the core marker traits via the `zerocopy-derive`
106//!   crate. These derives are re-exported from `zerocopy`, so it is not
107//!   necessary to depend on `zerocopy-derive` directly.
108//!
109//!   However, you may experience better compile times if you instead directly
110//!   depend on both `zerocopy` and `zerocopy-derive` in your `Cargo.toml`,
111//!   since doing so will allow Rust to compile these crates in parallel. To do
112//!   so, do *not* enable the `derive` feature, and list both dependencies in
113//!   your `Cargo.toml` with the same leading non-zero version number; e.g:
114//!
115//!   ```toml
116//!   [dependencies]
117//!   zerocopy = "0.X"
118//!   zerocopy-derive = "0.X"
119//!   ```
120//!
121//!   To avoid the risk of [duplicate import errors][duplicate-import-errors] if
122//!   one of your dependencies enables zerocopy's `derive` feature, import
123//!   derives as `use zerocopy_derive::*` rather than by name (e.g., `use
124//!   zerocopy_derive::FromBytes`).
125//!
126//! - **`simd`**
127//!   When the `simd` feature is enabled, `FromZeros`, `FromBytes`, and
128//!   `IntoBytes` impls are emitted for all stable SIMD types which exist on the
129//!   target platform. Note that the layout of SIMD types is not yet stabilized,
130//!   so these impls may be removed in the future if layout changes make them
131//!   invalid. For more information, see the Unsafe Code Guidelines Reference
132//!   page on the [layout of packed SIMD vectors][simd-layout].
133//!
134//! - **`simd-nightly`**
135//!   Enables the `simd` feature and adds support for SIMD types which are only
136//!   available on nightly. Since these types are unstable, support for any type
137//!   may be removed at any point in the future.
138//!
139//! - **`float-nightly`**
140//!   Adds support for the unstable `f16` and `f128` types. These types are
141//!   not yet fully implemented and may not be supported on all platforms.
142//!
143//! [duplicate-import-errors]: https://github.com/google/zerocopy/issues/1587
144//! [simd-layout]: https://rust-lang.github.io/unsafe-code-guidelines/layout/packed-simd-vectors.html
145//!
146//! # Build Tuning
147//!
148//! ## `--cfg zerocopy_inline_always`
149//!
150//! Upgrades `#[inline]` to `#[inline(always)]` on many of zerocopy's public
151//! functions and methods. This provides a narrowly-scoped alternative that
152//! *may* improve the optimization of hot paths using zerocopy without the broad
153//! compile-time penalties of configuring `codegen-units=1`.
154//!
155//! # Security Ethos
156//!
157//! Zerocopy is expressly designed for use in security-critical contexts. We
158//! strive to ensure that that zerocopy code is sound under Rust's current
159//! memory model, and *any future memory model*. We ensure this by:
160//! - **...not 'guessing' about Rust's semantics.**
161//!   We annotate `unsafe` code with a precise rationale for its soundness that
162//!   cites a relevant section of Rust's official documentation. When Rust's
163//!   documented semantics are unclear, we work with the Rust Operational
164//!   Semantics Team to clarify Rust's documentation.
165//! - **...rigorously testing our implementation.**
166//!   We run tests using [Miri], ensuring that zerocopy is sound across a wide
167//!   array of supported target platforms of varying endianness and pointer
168//!   width, and across both current and experimental memory models of Rust.
169//! - **...formally proving the correctness of our implementation.**
170//!   We apply formal verification tools like [Kani][kani] to prove zerocopy's
171//!   correctness.
172//!
173//! For more information, see our full [soundness policy].
174//!
175//! [Miri]: https://github.com/rust-lang/miri
176//! [Kani]: https://github.com/model-checking/kani
177//! [soundness policy]: https://github.com/google/zerocopy/blob/main/zerocopy/POLICIES.md#soundness
178//!
179//! # Relationship to Project Safe Transmute
180//!
181//! [Project Safe Transmute] is an official initiative of the Rust Project to
182//! develop language-level support for safer transmutation. The Project consults
183//! with crates like zerocopy to identify aspects of safer transmutation that
184//! would benefit from compiler support, and has developed an [experimental,
185//! compiler-supported analysis][mcp-transmutability] which determines whether,
186//! for a given type, any value of that type may be soundly transmuted into
187//! another type. Once this functionality is sufficiently mature, zerocopy
188//! intends to replace its internal transmutability analysis (implemented by our
189//! custom derives) with the compiler-supported one. This change will likely be
190//! an implementation detail that is invisible to zerocopy's users.
191//!
192//! Project Safe Transmute will not replace the need for most of zerocopy's
193//! higher-level abstractions. The experimental compiler analysis is a tool for
194//! checking the soundness of `unsafe` code, not a tool to avoid writing
195//! `unsafe` code altogether. For the foreseeable future, crates like zerocopy
196//! will still be required in order to provide higher-level abstractions on top
197//! of the building block provided by Project Safe Transmute.
198//!
199//! [Project Safe Transmute]: https://rust-lang.github.io/rfcs/2835-project-safe-transmute.html
200//! [mcp-transmutability]: https://github.com/rust-lang/compiler-team/issues/411
201//!
202//! # MSRV
203//!
204//! See our [MSRV policy].
205//!
206//! [MSRV policy]: https://github.com/google/zerocopy/blob/main/zerocopy/POLICIES.md#msrv
207//!
208//! # Changelog
209//!
210//! Zerocopy uses [GitHub Releases].
211//!
212//! [GitHub Releases]: https://github.com/google/zerocopy/releases
213//!
214//! # Thanks
215//!
216//! Zerocopy is maintained by engineers at Google with help from [many wonderful
217//! contributors][contributors]. Thank you to everyone who has lent a hand in
218//! making Rust a little more secure!
219//!
220//! [contributors]: https://github.com/google/zerocopy/graphs/contributors
221
222// Sometimes we want to use lints which were added after our MSRV.
223// `unknown_lints` is `warn` by default and we deny warnings in CI, so without
224// this attribute, any unknown lint would cause a CI failure when testing with
225// our MSRV.
226#![allow(unknown_lints, non_local_definitions, unreachable_patterns)]
227#![deny(renamed_and_removed_lints)]
228#![deny(
229    anonymous_parameters,
230    deprecated_in_future,
231    late_bound_lifetime_arguments,
232    missing_copy_implementations,
233    missing_debug_implementations,
234    missing_docs,
235    path_statements,
236    patterns_in_fns_without_body,
237    rust_2018_idioms,
238    trivial_numeric_casts,
239    unreachable_pub,
240    unsafe_op_in_unsafe_fn,
241    unused_extern_crates,
242    // We intentionally choose not to deny `unused_qualifications`. When items
243    // are added to the prelude (e.g., `core::mem::size_of`), this has the
244    // consequence of making some uses trigger this lint on the latest toolchain
245    // (e.g., `mem::size_of`), but fixing it (e.g. by replacing with `size_of`)
246    // does not work on older toolchains.
247    //
248    // We tested a more complicated fix in #1413, but ultimately decided that,
249    // since this lint is just a minor style lint, the complexity isn't worth it
250    // - it's fine to occasionally have unused qualifications slip through,
251    // especially since these do not affect our user-facing API in any way.
252    variant_size_differences
253)]
254#![cfg_attr(
255    __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS,
256    deny(implicit_provenance_casts)
257)]
258#![deny(
259    clippy::all,
260    clippy::alloc_instead_of_core,
261    clippy::arithmetic_side_effects,
262    clippy::as_underscore,
263    clippy::assertions_on_result_states,
264    clippy::as_conversions,
265    clippy::correctness,
266    clippy::dbg_macro,
267    clippy::decimal_literal_representation,
268    clippy::double_must_use,
269    clippy::get_unwrap,
270    clippy::indexing_slicing,
271    clippy::missing_inline_in_public_items,
272    clippy::missing_safety_doc,
273    clippy::multiple_unsafe_ops_per_block,
274    clippy::must_use_candidate,
275    clippy::must_use_unit,
276    clippy::obfuscated_if_else,
277    clippy::perf,
278    clippy::print_stdout,
279    clippy::return_self_not_must_use,
280    clippy::std_instead_of_core,
281    clippy::style,
282    clippy::suspicious,
283    clippy::todo,
284    clippy::undocumented_unsafe_blocks,
285    clippy::unimplemented,
286    clippy::unnested_or_patterns,
287    clippy::unwrap_used,
288    clippy::use_debug
289)]
290// `clippy::incompatible_msrv` (implied by `clippy::suspicious`): This sometimes
291// has false positives, and we test on our MSRV in CI, so it doesn't help us
292// anyway.
293#![allow(clippy::needless_lifetimes, clippy::type_complexity, clippy::incompatible_msrv)]
294#![deny(
295    rustdoc::bare_urls,
296    rustdoc::broken_intra_doc_links,
297    rustdoc::invalid_codeblock_attributes,
298    rustdoc::invalid_html_tags,
299    rustdoc::invalid_rust_codeblocks,
300    rustdoc::missing_crate_level_docs,
301    rustdoc::private_intra_doc_links
302)]
303// In test code, it makes sense to weight more heavily towards concise, readable
304// code over correct or debuggable code.
305#![cfg_attr(any(test, kani), allow(
306    // In tests, you get line numbers and have access to source code, so panic
307    // messages are less important. You also often unwrap a lot, which would
308    // make expect'ing instead very verbose.
309    clippy::unwrap_used,
310    // In tests, there's no harm to "panic risks" - the worst that can happen is
311    // that your test will fail, and you'll fix it. By contrast, panic risks in
312    // production code introduce the possibly of code panicking unexpectedly "in
313    // the field".
314    clippy::arithmetic_side_effects,
315    clippy::indexing_slicing,
316))]
317#![cfg_attr(not(any(test, kani, feature = "std")), no_std)]
318#![cfg_attr(
319    all(feature = "simd-nightly", any(target_arch = "powerpc", target_arch = "powerpc64")),
320    feature(stdarch_powerpc)
321)]
322#![cfg_attr(feature = "float-nightly", feature(f16, f128))]
323#![cfg_attr(doc_cfg, feature(doc_cfg))]
324#![cfg_attr(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS, feature(coverage_attribute))]
325#![cfg_attr(all(test, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS), feature(test))]
326
327// This is a hack to allow zerocopy-derive derives to work in this crate. They
328// assume that zerocopy is linked as an extern crate, so they access items from
329// it as `zerocopy::Xxx`. This makes that still work.
330#[cfg(any(feature = "derive", test))]
331extern crate self as zerocopy;
332
333#[cfg(all(test, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS))]
334extern crate test;
335
336#[doc(hidden)]
337#[macro_use]
338pub mod util;
339
340pub mod byte_slice;
341pub mod byteorder;
342mod deprecated;
343
344#[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_DEV_MODE)]
345pub mod doctests;
346
347// This module is `pub` so that zerocopy's error types and error handling
348// documentation is grouped together in a cohesive module. In practice, we
349// expect most users to use the re-export of `error`'s items to avoid identifier
350// stuttering.
351pub mod error;
352mod impls;
353#[doc(hidden)]
354pub mod layout;
355mod macros;
356#[cfg_attr(not(zerocopy_unstable_ptr), doc(hidden))]
357#[cfg_attr(doc_cfg, doc(cfg(zerocopy_unstable_ptr)))]
358pub mod pointer;
359mod r#ref;
360mod split_at;
361// FIXME(#252): If we make this pub, come up with a better name.
362mod wrappers;
363
364use core::{
365    cell::{Cell, UnsafeCell},
366    cmp::Ordering,
367    fmt::{self, Debug, Display, Formatter},
368    hash::Hasher,
369    marker::PhantomData,
370    mem::{self, ManuallyDrop, MaybeUninit as CoreMaybeUninit},
371    num::{
372        NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
373        NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Wrapping,
374    },
375    ops::{Deref, DerefMut},
376    ptr::{self, NonNull},
377    slice,
378};
379#[cfg(feature = "std")]
380use std::io;
381
382#[doc(hidden)]
383pub use crate::pointer::{
384    invariant::{self, BecauseExclusive},
385    PtrInner,
386};
387pub use crate::{
388    byte_slice::*,
389    byteorder::*,
390    error::*,
391    r#ref::*,
392    split_at::{Split, SplitAt},
393    wrappers::*,
394};
395
396#[cfg(any(feature = "alloc", test))]
397extern crate alloc;
398#[cfg(any(feature = "alloc", test))]
399use alloc::{boxed::Box, vec::Vec};
400#[cfg(all(not(no_zerocopy_allocator_api_1_100_0), feature = "alloc"))]
401use core::alloc::Allocator;
402#[cfg(any(feature = "alloc", test))]
403use core::alloc::Layout;
404
405// Used by `KnownLayout`.
406#[doc(hidden)]
407pub use crate::layout::*;
408// Used by `TryFromBytes::is_safe`.
409#[doc(hidden)]
410pub use crate::pointer::{invariant::BecauseImmutable, Maybe, Ptr};
411// For each trait polyfill, as soon as the corresponding feature is stable, the
412// polyfill import will be unused because method/function resolution will prefer
413// the inherent method/function over a trait method/function. Thus, we suppress
414// the `unused_imports` warning.
415//
416// See the documentation on `util::polyfills` for more information.
417#[allow(unused_imports)]
418use crate::util::polyfills::{self, NonNullExt as _, NumExt as _};
419#[cfg_attr(not(zerocopy_unstable_ptr), doc(hidden))]
420#[cfg_attr(doc_cfg, doc(cfg(zerocopy_unstable_ptr)))]
421pub use crate::util::MetadataOf;
422
423#[cfg(all(test, not(__ZEROCOPY_INTERNAL_USE_ONLY_DEV_MODE)))]
424const _: () = {
425    #[deprecated = "Development of zerocopy using cargo is not supported. Please use `cargo.sh` or `win-cargo.bat` instead."]
426    #[allow(unused)]
427    const WARNING: () = ();
428    #[warn(deprecated)]
429    WARNING
430};
431
432#[cfg(all(any(feature = "derive", test), zerocopy_unstable_linux))]
433pub use zerocopy_derive::most_traits;
434/// Implements [`KnownLayout`].
435///
436/// This derive analyzes various aspects of a type's layout that are needed for
437/// some of zerocopy's APIs. It can be applied to structs, enums, and unions;
438/// e.g.:
439///
440/// ```
441/// # use zerocopy_derive::KnownLayout;
442/// #[derive(KnownLayout)]
443/// struct MyStruct {
444/// # /*
445///     ...
446/// # */
447/// }
448///
449/// #[derive(KnownLayout)]
450/// enum MyEnum {
451/// #   V00,
452/// # /*
453///     ...
454/// # */
455/// }
456///
457/// #[derive(KnownLayout)]
458/// union MyUnion {
459/// #   variant: u8,
460/// # /*
461///     ...
462/// # */
463/// }
464/// ```
465///
466/// # Limitations
467///
468/// This derive cannot currently be applied to unsized structs without an
469/// explicit `repr` attribute.
470///
471/// Some invocations of this derive run afoul of a [known bug] in Rust's type
472/// privacy checker. For example, this code:
473///
474/// ```compile_fail,E0446
475/// use zerocopy::*;
476/// # use zerocopy_derive::*;
477///
478/// #[derive(KnownLayout)]
479/// #[repr(C)]
480/// pub struct PublicType {
481///     leading: Foo,
482///     trailing: Bar,
483/// }
484///
485/// #[derive(KnownLayout)]
486/// struct Foo;
487///
488/// #[derive(KnownLayout)]
489/// struct Bar;
490/// ```
491///
492/// ...results in a compilation error:
493///
494/// ```text
495/// error[E0446]: private type `Bar` in public interface
496///  --> examples/bug.rs:3:10
497///    |
498/// 3  | #[derive(KnownLayout)]
499///    |          ^^^^^^^^^^^ can't leak private type
500/// ...
501/// 14 | struct Bar;
502///    | ---------- `Bar` declared as private
503///    |
504///    = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info)
505/// ```
506///
507/// This issue arises when `#[derive(KnownLayout)]` is applied to `repr(C)`
508/// structs whose trailing field type is less public than the enclosing struct.
509///
510/// To work around this, mark the trailing field type `pub` and annotate it with
511/// `#[doc(hidden)]`; e.g.:
512///
513/// ```no_run
514/// use zerocopy::*;
515/// # use zerocopy_derive::*;
516///
517/// #[derive(KnownLayout)]
518/// #[repr(C)]
519/// pub struct PublicType {
520///     leading: Foo,
521///     trailing: Bar,
522/// }
523///
524/// #[derive(KnownLayout)]
525/// struct Foo;
526///
527/// #[doc(hidden)]
528/// #[derive(KnownLayout)]
529/// pub struct Bar; // <- `Bar` is now also `pub`
530/// ```
531///
532/// [known bug]: https://github.com/rust-lang/rust/issues/45713
533#[cfg(any(feature = "derive", test))]
534#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
535pub use zerocopy_derive::KnownLayout;
536// These exist so that code which was written against the old names will get
537// less confusing error messages when they upgrade to a more recent version of
538// zerocopy. On our MSRV toolchain, the error messages read, for example:
539//
540//   error[E0603]: trait `FromZeroes` is private
541//       --> examples/deprecated.rs:1:15
542//        |
543//   1    | use zerocopy::FromZeroes;
544//        |               ^^^^^^^^^^ private trait
545//        |
546//   note: the trait `FromZeroes` is defined here
547//       --> /Users/josh/workspace/zerocopy/src/lib.rs:1845:5
548//        |
549//   1845 | use FromZeros as FromZeroes;
550//        |     ^^^^^^^^^^^^^^^^^^^^^^^
551//
552// The "note" provides enough context to make it easy to figure out how to fix
553// the error.
554#[allow(unused)]
555use {FromZeros as FromZeroes, IntoBytes as AsBytes, Ref as LayoutVerified};
556
557/// Indicates that zerocopy can reason about certain aspects of a type's layout.
558///
559/// This trait is required by many of zerocopy's APIs. It supports sized types,
560/// slices, and [slice DSTs](#dynamically-sized-types).
561///
562/// # Implementation
563///
564/// **Do not implement this trait yourself!** Instead, use
565/// [`#[derive(KnownLayout)]`][derive]; e.g.:
566///
567/// ```
568/// # use zerocopy_derive::KnownLayout;
569/// #[derive(KnownLayout)]
570/// struct MyStruct {
571/// # /*
572///     ...
573/// # */
574/// }
575///
576/// #[derive(KnownLayout)]
577/// enum MyEnum {
578/// # /*
579///     ...
580/// # */
581/// }
582///
583/// #[derive(KnownLayout)]
584/// union MyUnion {
585/// #   variant: u8,
586/// # /*
587///     ...
588/// # */
589/// }
590/// ```
591///
592/// This derive performs a sophisticated analysis to deduce the layout
593/// characteristics of types. You **must** implement this trait via the derive.
594///
595/// # Dynamically-sized types
596///
597/// `KnownLayout` supports slice-based dynamically sized types ("slice DSTs").
598///
599/// A slice DST is a type whose trailing field is either a slice or another
600/// slice DST, rather than a type with fixed size. For example:
601///
602/// ```
603/// #[repr(C)]
604/// struct PacketHeader {
605/// # /*
606///     ...
607/// # */
608/// }
609///
610/// #[repr(C)]
611/// struct Packet {
612///     header: PacketHeader,
613///     body: [u8],
614/// }
615/// ```
616///
617/// It can be useful to think of slice DSTs as a generalization of slices - in
618/// other words, a normal slice is just the special case of a slice DST with
619/// zero leading fields. In particular:
620/// - Like slices, slice DSTs can have different lengths at runtime
621/// - Like slices, slice DSTs cannot be passed by-value, but only by reference
622///   or via other indirection such as `Box`
623/// - Like slices, a reference (or `Box`, or other pointer type) to a slice DST
624///   encodes the number of elements in the trailing slice field
625///
626/// ## Slice DST layout
627///
628/// Just like other composite Rust types, the layout of a slice DST is not
629/// well-defined unless it is specified using an explicit `#[repr(...)]`
630/// attribute such as `#[repr(C)]`. [Other representations are
631/// supported][reprs], but in this section, we'll use `#[repr(C)]` as our
632/// example.
633///
634/// A `#[repr(C)]` slice DST is laid out [just like sized `#[repr(C)]`
635/// types][repr-c-structs], but the presence of a variable-length field
636/// introduces the possibility of *dynamic padding*. In particular, it may be
637/// necessary to add trailing padding *after* the trailing slice field in order
638/// to satisfy the outer type's alignment, and the amount of padding required
639/// may be a function of the length of the trailing slice field. This is just a
640/// natural consequence of the normal `#[repr(C)]` rules applied to slice DSTs,
641/// but it can result in surprising behavior. For example, consider the
642/// following type:
643///
644/// ```
645/// #[repr(C)]
646/// struct Foo {
647///     a: u32,
648///     b: u8,
649///     z: [u16],
650/// }
651/// ```
652///
653/// Assuming that `u32` has alignment 4 (this is not true on all platforms),
654/// then `Foo` has alignment 4 as well. Here is the smallest possible value for
655/// `Foo`:
656///
657/// ```text
658/// byte offset | 01234567
659///       field | aaaab---
660///                    ><
661/// ```
662///
663/// In this value, `z` has length 0. Abiding by `#[repr(C)]`, the lowest offset
664/// that we can place `z` at is 5, but since `z` has alignment 2, we need to
665/// round up to offset 6. This means that there is one byte of padding between
666/// `b` and `z`, then 0 bytes of `z` itself (denoted `><` in this diagram), and
667/// then two bytes of padding after `z` in order to satisfy the overall
668/// alignment of `Foo`. The size of this instance is 8 bytes.
669///
670/// What about if `z` has length 1?
671///
672/// ```text
673/// byte offset | 01234567
674///       field | aaaab-zz
675/// ```
676///
677/// In this instance, `z` has length 1, and thus takes up 2 bytes. That means
678/// that we no longer need padding after `z` in order to satisfy `Foo`'s
679/// alignment. We've now seen two different values of `Foo` with two different
680/// lengths of `z`, but they both have the same size - 8 bytes.
681///
682/// What about if `z` has length 2?
683///
684/// ```text
685/// byte offset | 012345678901
686///       field | aaaab-zzzz--
687/// ```
688///
689/// Now `z` has length 2, and thus takes up 4 bytes. This brings our un-padded
690/// size to 10, and so we now need another 2 bytes of padding after `z` to
691/// satisfy `Foo`'s alignment.
692///
693/// Again, all of this is just a logical consequence of the `#[repr(C)]` rules
694/// applied to slice DSTs, but it can be surprising that the amount of trailing
695/// padding becomes a function of the trailing slice field's length, and thus
696/// can only be computed at runtime.
697///
698/// [reprs]: https://doc.rust-lang.org/reference/type-layout.html#representations
699/// [repr-c-structs]: https://doc.rust-lang.org/reference/type-layout.html#reprc-structs
700///
701/// ## What is a valid size?
702///
703/// There are two places in zerocopy's API that we refer to "a valid size" of a
704/// type. In normal casts or conversions, where the source is a byte slice, we
705/// need to know whether the source byte slice is a valid size of the
706/// destination type. In prefix or suffix casts, we need to know whether *there
707/// exists* a valid size of the destination type which fits in the source byte
708/// slice and, if so, what the largest such size is.
709///
710/// As outlined above, a slice DST's size is defined by the number of elements
711/// in its trailing slice field. However, there is not necessarily a 1-to-1
712/// mapping between trailing slice field length and overall size. As we saw in
713/// the previous section with the type `Foo`, instances with both 0 and 1
714/// elements in the trailing `z` field result in a `Foo` whose size is 8 bytes.
715///
716/// When we say "x is a valid size of `T`", we mean one of two things:
717/// - If `T: Sized`, then we mean that `x == size_of::<T>()`
718/// - If `T` is a slice DST, then we mean that there exists a `len` such that the instance of
719///   `T` with `len` trailing slice elements has size `x`
720///
721/// When we say "largest possible size of `T` that fits in a byte slice", we
722/// mean one of two things:
723/// - If `T: Sized`, then we mean `size_of::<T>()` if the byte slice is at least
724///   `size_of::<T>()` bytes long
725/// - If `T` is a slice DST, then we mean to consider all values, `len`, such
726///   that the instance of `T` with `len` trailing slice elements fits in the
727///   byte slice, and to choose the largest such `len`, if any
728///
729///
730/// # Safety
731///
732/// This trait does not convey any safety guarantees to code outside this crate.
733///
734/// You must not rely on the `#[doc(hidden)]` internals of `KnownLayout`. Future
735/// releases of zerocopy may make backwards-breaking changes to these items,
736/// including changes that only affect soundness, which may cause code which
737/// uses those items to silently become unsound.
738///
739#[cfg_attr(feature = "derive", doc = "[derive]: zerocopy_derive::KnownLayout")]
740#[cfg_attr(
741    not(feature = "derive"),
742    doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.KnownLayout.html"),
743)]
744#[cfg_attr(
745    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
746    diagnostic::on_unimplemented(note = "Consider adding `#[derive(KnownLayout)]` to `{Self}`")
747)]
748pub unsafe trait KnownLayout {
749    // The `Self: Sized` bound makes it so that `KnownLayout` can still be
750    // object safe. It's not currently object safe thanks to `const LAYOUT`, and
751    // it likely won't be in the future, but there's no reason not to be
752    // forwards-compatible with object safety.
753    #[doc(hidden)]
754    fn only_derive_is_allowed_to_implement_this_trait()
755    where
756        Self: Sized;
757
758    /// The type of metadata stored in a pointer to `Self`.
759    ///
760    /// This is `()` for sized types and [`usize`] for slice DSTs.
761    type PointerMetadata: PointerMetadata;
762
763    /// A maybe-uninitialized analog of `Self`
764    ///
765    /// # Safety
766    ///
767    /// `Self::LAYOUT` and `Self::MaybeUninit::LAYOUT` are identical.
768    /// `Self::MaybeUninit` admits uninitialized bytes in all positions.
769    #[doc(hidden)]
770    type MaybeUninit: ?Sized + KnownLayout<PointerMetadata = Self::PointerMetadata>;
771
772    /// The layout of `Self`.
773    ///
774    /// # Safety
775    ///
776    /// Callers may assume that `LAYOUT` accurately reflects the layout of
777    /// `Self`. In particular:
778    /// - `LAYOUT.align` is equal to `Self`'s alignment
779    /// - If `Self: Sized`, then `LAYOUT.size_info == SizeInfo::Sized { size }`
780    ///   where `size == size_of::<Self>()`
781    /// - If `Self` is a slice DST, then `LAYOUT.size_info ==
782    ///   SizeInfo::SliceDst(slice_layout)` where:
783    ///   - `slice_layout.size_rounding_align_and_phase` decodes to an alignment
784    ///     that is a power of two and a phase which is less than that alignment
785    ///   - The size, `size`, of an instance of `Self` with `elems` trailing
786    ///     slice elements is equal to `slice_layout.size_base +
787    ///     round_up(size_phase + slice_layout.elem_size * elems, size_align)`,
788    ///     where `(size_align, size_phase)` is decoded from
789    ///     `slice_layout.size_rounding_align_and_phase`
790    ///   - The trailing slice begins at byte offset `slice_layout.offset`
791    ///   - `slice_layout.offset + slice_layout.elem_size * elems` does not
792    ///     overflow and is no greater than `size`
793    ///   - For such an instance, any bytes in the range `[slice_layout.offset +
794    ///     slice_layout.elem_size * elems, size)` are padding and must not be
795    ///     assumed to be initialized
796    #[doc(hidden)]
797    const LAYOUT: DstLayout;
798
799    /// SAFETY: The returned pointer has the same address and provenance as
800    /// `bytes`. If `Self` is a DST, the returned pointer's referent has `elems`
801    /// elements in its trailing slice.
802    #[doc(hidden)]
803    fn raw_from_ptr_len(bytes: NonNull<u8>, meta: Self::PointerMetadata) -> NonNull<Self>;
804
805    /// Extracts the metadata from a pointer to `Self`.
806    ///
807    /// # Safety
808    ///
809    /// `pointer_to_metadata` always returns the correct metadata stored in
810    /// `ptr`.
811    #[doc(hidden)]
812    fn pointer_to_metadata(ptr: *mut Self) -> Self::PointerMetadata;
813
814    /// Computes the length of the byte range addressed by `ptr`.
815    ///
816    /// Returns `None` if the resulting length would not fit in an `usize`.
817    ///
818    /// # Safety
819    ///
820    /// Callers may assume that `size_of_val_raw` always returns the correct
821    /// size.
822    ///
823    /// Callers may assume that, if `ptr` addresses a byte range whose length
824    /// fits in an `usize`, this will return `Some`.
825    #[doc(hidden)]
826    #[must_use]
827    #[inline(always)]
828    fn size_of_val_raw(ptr: NonNull<Self>) -> Option<usize> {
829        let meta = Self::pointer_to_metadata(ptr.as_ptr());
830        // SAFETY: `size_for_metadata` promises to only return `None` if the
831        // resulting size would not fit in a `usize`.
832        Self::size_for_metadata(meta)
833    }
834
835    #[doc(hidden)]
836    #[must_use]
837    #[inline(always)]
838    fn raw_dangling() -> NonNull<Self> {
839        let meta = Self::PointerMetadata::from_elem_count(0);
840        Self::raw_from_ptr_len(NonNull::dangling(), meta)
841    }
842
843    /// Computes the size of an object of type `Self` with the given pointer
844    /// metadata.
845    ///
846    /// # Safety
847    ///
848    /// `size_for_metadata` promises to return `None` if and only if the
849    /// resulting size would not fit in a [`usize`]. Note that the returned size
850    /// could exceed the actual maximum valid size of an allocated object,
851    /// [`isize::MAX`].
852    ///
853    /// # Examples
854    ///
855    /// ```
856    /// use zerocopy::KnownLayout;
857    ///
858    /// assert_eq!(u8::size_for_metadata(()), Some(1));
859    /// assert_eq!(u16::size_for_metadata(()), Some(2));
860    /// assert_eq!(<[u8]>::size_for_metadata(42), Some(42));
861    /// assert_eq!(<[u16]>::size_for_metadata(42), Some(84));
862    ///
863    /// // This size exceeds the maximum valid object size (`isize::MAX`):
864    /// assert_eq!(<[u8]>::size_for_metadata(usize::MAX), Some(usize::MAX));
865    ///
866    /// // This size, if computed, would exceed `usize::MAX`:
867    /// assert_eq!(<[u16]>::size_for_metadata(usize::MAX), None);
868    /// ```
869    #[inline(always)]
870    fn size_for_metadata(meta: Self::PointerMetadata) -> Option<usize> {
871        meta.size_for_metadata(Self::LAYOUT)
872    }
873
874    /// Computes the size of an object of type `Self` with the given pointer
875    /// metadata without overflow checks.
876    ///
877    /// # Safety
878    ///
879    /// The resulting size must fit in a [`usize`].
880    #[doc(hidden)]
881    #[must_use]
882    #[inline(always)]
883    #[cfg_attr(
884        all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
885        coverage(off)
886    )]
887    unsafe fn size_for_metadata_unchecked(meta: Self::PointerMetadata) -> usize {
888        // SAFETY: The caller promises that the resulting size fits in a `usize`.
889        // By invariant on `Self::LAYOUT`, if `Self` is a slice DST,
890        // `offset + elems * elem_size` does not overflow and is no greater than
891        // the complete object size.
892        unsafe { meta.size_for_metadata_unchecked(Self::LAYOUT) }
893    }
894
895    /// Computes whether `meta` can describe a valid allocation of `Self`.
896    ///
897    /// # Safety
898    ///
899    /// `is_valid_metadata` promises to return `true` if and only if the size of
900    /// an allocation of `Self` with `meta` would not overflow an
901    /// [`isize::MAX`].
902    #[doc(hidden)]
903    #[inline(always)]
904    fn is_valid_metadata(meta: Self::PointerMetadata) -> bool {
905        meta.to_elem_count() <= maximum_trailing_slice_len::<Self>().to_elem_count()
906    }
907}
908
909/// Efficiently produces the [`TrailingSliceLayout`] of `T`.
910#[inline(always)]
911pub(crate) fn trailing_slice_layout<T>() -> TrailingSliceLayout
912where
913    T: ?Sized + KnownLayout<PointerMetadata = usize>,
914{
915    trait LayoutFacts {
916        const SIZE_INFO: TrailingSliceLayout;
917    }
918
919    impl<T: ?Sized> LayoutFacts for T
920    where
921        T: KnownLayout<PointerMetadata = usize>,
922    {
923        const SIZE_INFO: TrailingSliceLayout = match T::LAYOUT.size_info {
924            crate::SizeInfo::Sized { .. } => const_panic!("unreachable"),
925            crate::SizeInfo::SliceDst(info) => info,
926        };
927    }
928
929    T::SIZE_INFO
930}
931
932/// Efficiently produces the maximum trailing slice length `T`.
933#[inline(always)]
934pub(crate) fn maximum_trailing_slice_len<T>() -> usize
935where
936    T: ?Sized + KnownLayout,
937{
938    trait LayoutFacts {
939        const MAX_LEN: usize;
940    }
941
942    impl<T: ?Sized> LayoutFacts for T
943    where
944        T: KnownLayout,
945    {
946        const MAX_LEN: usize = match T::LAYOUT.size_info {
947            SizeInfo::SliceDst(TrailingSliceLayout { elem_size: 0, .. }) => usize::MAX,
948            _ => match T::LAYOUT.validate_cast_and_convert_metadata(
949                T::LAYOUT.align.get(),
950                DstLayout::MAX_SIZE,
951                CastType::Prefix,
952            ) {
953                Ok((elems, _)) => elems,
954                Err(_) => const_panic!("unreachable"),
955            },
956        };
957    }
958
959    T::MAX_LEN
960}
961
962/// The metadata associated with a [`KnownLayout`] type.
963#[doc(hidden)]
964pub trait PointerMetadata: Copy + Eq + Debug + Ord {
965    /// Constructs a `Self` from an element count.
966    ///
967    /// If `Self = ()`, this returns `()`. If `Self = usize`, this returns
968    /// `elems`. No other types are currently supported.
969    fn from_elem_count(elems: usize) -> Self;
970
971    /// Converts `self` to an element count.
972    ///
973    /// If `Self = ()`, this returns `0`. If `Self = usize`, this returns
974    /// `self`. No other types are currently supported.
975    fn to_elem_count(self) -> usize;
976
977    /// Computes the size of the object with the given layout and pointer
978    /// metadata.
979    ///
980    /// # Panics
981    ///
982    /// If `Self = ()`, `layout` must describe a sized type. If `Self = usize`,
983    /// `layout` must describe a slice DST. Otherwise, `size_for_metadata` may
984    /// panic.
985    ///
986    /// # Safety
987    ///
988    /// `size_for_metadata` promises to only return `None` if the resulting size
989    /// would not fit in a `usize`.
990    fn size_for_metadata(self, layout: DstLayout) -> Option<usize>;
991
992    /// Computes the size of the object with the given layout and pointer
993    /// metadata without overflow checks.
994    ///
995    /// # Panics
996    ///
997    /// If `Self = ()`, `layout` must describe a sized type. If `Self = usize`,
998    /// `layout` must describe a slice DST. Otherwise, `size_for_metadata_unchecked`
999    /// may panic.
1000    ///
1001    /// # Safety
1002    ///
1003    /// The resulting size must fit in a `usize`. If `Self = usize`, the trailing
1004    /// slice's byte range (`offset..offset + elems * elem_size`) must be
1005    /// representable in `usize` and contained within the complete object size.
1006    unsafe fn size_for_metadata_unchecked(self, layout: DstLayout) -> usize;
1007}
1008
1009impl PointerMetadata for () {
1010    #[inline]
1011    #[allow(clippy::unused_unit)]
1012    fn from_elem_count(_elems: usize) -> () {}
1013
1014    #[inline]
1015    fn to_elem_count(self) -> usize {
1016        0
1017    }
1018
1019    #[inline]
1020    fn size_for_metadata(self, layout: DstLayout) -> Option<usize> {
1021        match layout.size_info {
1022            SizeInfo::Sized { size } => Some(size),
1023            // NOTE: This branch is unreachable, but we return `None` rather
1024            // than `unreachable!()` to avoid generating panic paths.
1025            SizeInfo::SliceDst(_) => None,
1026        }
1027    }
1028
1029    #[inline(always)]
1030    #[cfg_attr(
1031        all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
1032        coverage(off)
1033    )]
1034    unsafe fn size_for_metadata_unchecked(self, layout: DstLayout) -> usize {
1035        match layout.size_info {
1036            SizeInfo::Sized { size } => size,
1037            // SAFETY: The caller promises that `layout` describes a sized type for `Self = ()`.
1038            SizeInfo::SliceDst(_) => unsafe { core::hint::unreachable_unchecked() },
1039        }
1040    }
1041}
1042
1043impl PointerMetadata for usize {
1044    #[inline]
1045    fn from_elem_count(elems: usize) -> usize {
1046        elems
1047    }
1048
1049    #[inline]
1050    fn to_elem_count(self) -> usize {
1051        self
1052    }
1053
1054    #[inline]
1055    fn size_for_metadata(self, layout: DstLayout) -> Option<usize> {
1056        match layout.size_info {
1057            SizeInfo::SliceDst(trailing) => trailing.size_for_elems(self),
1058            // NOTE: This branch is unreachable, but we return `None` rather
1059            // than `unreachable!()` to avoid generating panic paths.
1060            SizeInfo::Sized { .. } => None,
1061        }
1062    }
1063
1064    #[inline(always)]
1065    #[cfg_attr(
1066        all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
1067        coverage(off)
1068    )]
1069    unsafe fn size_for_metadata_unchecked(self, layout: DstLayout) -> usize {
1070        match layout.size_info {
1071            // SAFETY: The caller promises that the resulting size fits in a
1072            // `usize` and that the trailing slice's byte range is representable
1073            // and contained in the complete object size.
1074            SizeInfo::SliceDst(trailing) => unsafe { trailing.size_for_elems_unchecked(self) },
1075            // SAFETY: The caller promises that `layout` describes a slice DST for `Self = usize`.
1076            SizeInfo::Sized { .. } => unsafe { core::hint::unreachable_unchecked() },
1077        }
1078    }
1079}
1080
1081// SAFETY: Delegates safety to `DstLayout::for_slice`.
1082unsafe impl<T> KnownLayout for [T] {
1083    #[allow(clippy::missing_inline_in_public_items, dead_code)]
1084    #[cfg_attr(
1085        all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
1086        coverage(off)
1087    )]
1088    fn only_derive_is_allowed_to_implement_this_trait()
1089    where
1090        Self: Sized,
1091    {
1092    }
1093
1094    type PointerMetadata = usize;
1095
1096    // SAFETY: `CoreMaybeUninit<T>::LAYOUT` and `T::LAYOUT` are identical
1097    // because `CoreMaybeUninit<T>` has the same size and alignment as `T` [1].
1098    // Consequently, `[CoreMaybeUninit<T>]::LAYOUT` and `[T]::LAYOUT` are
1099    // identical, because they both lack a fixed-sized prefix and because they
1100    // inherit the alignments of their inner element type (which are identical)
1101    // [2][3].
1102    //
1103    // `[CoreMaybeUninit<T>]` admits uninitialized bytes at all positions
1104    // because `CoreMaybeUninit<T>` admits uninitialized bytes at all positions
1105    // and because the inner elements of `[CoreMaybeUninit<T>]` are laid out
1106    // back-to-back [2][3].
1107    //
1108    // [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
1109    //
1110    //   `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as
1111    //   `T`
1112    //
1113    // [2] Per https://doc.rust-lang.org/1.82.0/reference/type-layout.html#slice-layout:
1114    //
1115    //   Slices have the same layout as the section of the array they slice.
1116    //
1117    // [3] Per https://doc.rust-lang.org/1.82.0/reference/type-layout.html#array-layout:
1118    //
1119    //   An array of `[T; N]` has a size of `size_of::<T>() * N` and the same
1120    //   alignment of `T`. Arrays are laid out so that the zero-based `nth`
1121    //   element of the array is offset from the start of the array by `n *
1122    //   size_of::<T>()` bytes.
1123    type MaybeUninit = [CoreMaybeUninit<T>];
1124
1125    const LAYOUT: DstLayout = DstLayout::for_slice::<T>();
1126
1127    // SAFETY: `.cast` preserves address and provenance. The returned pointer
1128    // refers to an object with `elems` elements by construction.
1129    #[inline(always)]
1130    fn raw_from_ptr_len(data: NonNull<u8>, elems: usize) -> NonNull<Self> {
1131        // FIXME(#67): Remove this allow. See NonNullExt for more details.
1132        #[allow(unstable_name_collisions)]
1133        NonNull::slice_from_raw_parts(data.cast::<T>(), elems)
1134    }
1135
1136    #[inline(always)]
1137    fn pointer_to_metadata(ptr: *mut [T]) -> usize {
1138        #[cfg(not(no_zerocopy_slice_ptr_len_1_79_0))]
1139        {
1140            ptr.len()
1141        }
1142
1143        #[cfg(no_zerocopy_slice_ptr_len_1_79_0)]
1144        {
1145            // `*mut [T]::len` was not stable before Rust 1.79. In every Rust
1146            // version from our 1.56 MSRV through 1.78, `Hash for *mut T`
1147            // decomposes a raw pointer and passes its address and metadata to
1148            // the hasher in that order [1]. `Hash for usize` passes its value
1149            // to `Hasher::write_usize` [2]. Capture those two values to obtain
1150            // a candidate for the slice length without dereferencing `ptr` or
1151            // constructing a reference.
1152            //
1153            // This historical `Hash` implementation is only used to produce a
1154            // candidate. Before returning it, we reconstruct a raw slice and
1155            // authenticate the candidate with `ptr::eq`, which compares slice
1156            // lengths as well as addresses [3]. Thus, an unexpected `Hash`
1157            // implementation cannot cause us to return incorrect metadata; it
1158            // can only fail to produce an authenticated candidate.
1159            //
1160            // [1] Per https://doc.rust-lang.org/1.56.0/src/core/hash/mod.rs.html#776-782:
1161            //
1162            //   let (address, metadata) = self.to_raw_parts();
1163            //   state.write_usize(address as usize);
1164            //   metadata.hash(state);
1165            //
1166            // [2] Per https://doc.rust-lang.org/1.56.0/src/core/hash/mod.rs.html#628-656:
1167            //
1168            //   fn hash<H: Hasher>(&self, state: &mut H) {
1169            //       state.$meth(*self)
1170            //   }
1171            //   ...
1172            //   (usize, write_usize),
1173            //
1174            // [3] Per https://doc.rust-lang.org/1.56.0/std/ptr/fn.eq.html:
1175            //
1176            //   Slices are also compared by their length (fat pointers).
1177            struct MetadataHasher {
1178                values: [usize; 2],
1179                writes: usize,
1180                valid: bool,
1181            }
1182
1183            impl Hasher for MetadataHasher {
1184                #[inline(always)]
1185                fn finish(&self) -> u64 {
1186                    0
1187                }
1188
1189                #[inline(always)]
1190                fn write(&mut self, _bytes: &[u8]) {
1191                    self.valid = false;
1192                }
1193
1194                #[inline(always)]
1195                fn write_usize(&mut self, value: usize) {
1196                    match self.values.get_mut(self.writes) {
1197                        Some(slot) => *slot = value,
1198                        None => self.valid = false,
1199                    }
1200                    self.writes = self.writes.saturating_add(1);
1201                }
1202            }
1203
1204            let mut hasher = MetadataHasher { values: [0; 2], writes: 0, valid: true };
1205            core::hash::Hash::hash(&ptr, &mut hasher);
1206            assert!(
1207                hasher.valid && hasher.writes == 2,
1208                "unexpected raw-pointer Hash implementation"
1209            );
1210
1211            let elems = hasher.values[1];
1212            #[allow(clippy::as_conversions)]
1213            let reconstructed = ptr::slice_from_raw_parts_mut(ptr as *mut T, elems);
1214            assert!(ptr::eq(ptr, reconstructed), "captured value is not raw-slice metadata");
1215            elems
1216        }
1217    }
1218}
1219
1220#[rustfmt::skip]
1221impl_known_layout!(
1222    (),
1223    u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, f32, f64,
1224    bool, char,
1225    NonZeroU8, NonZeroI8, NonZeroU16, NonZeroI16, NonZeroU32, NonZeroI32,
1226    NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128, NonZeroUsize, NonZeroIsize
1227);
1228#[rustfmt::skip]
1229#[cfg(feature = "float-nightly")]
1230impl_known_layout!(
1231    #[cfg_attr(doc_cfg, doc(cfg(feature = "float-nightly")))]
1232    f16,
1233    #[cfg_attr(doc_cfg, doc(cfg(feature = "float-nightly")))]
1234    f128
1235);
1236#[rustfmt::skip]
1237impl_known_layout!(
1238    T         => Option<T>,
1239    T: ?Sized => PhantomData<T>,
1240    T         => Wrapping<T>,
1241    T         => CoreMaybeUninit<T>,
1242    T: ?Sized => *const T,
1243    T: ?Sized => *mut T,
1244    T: ?Sized => &'_ T,
1245    T: ?Sized => &'_ mut T,
1246);
1247impl_known_layout!(const N: usize, T => [T; N]);
1248
1249// SAFETY: `str` has the same representation as `[u8]`. `ManuallyDrop<T>` [1],
1250// `UnsafeCell<T>` [2], and `Cell<T>` [3] have the same representation as `T`.
1251//
1252// [1] Per https://doc.rust-lang.org/1.85.0/std/mem/struct.ManuallyDrop.html:
1253//
1254//   `ManuallyDrop<T>` is guaranteed to have the same layout and bit validity as
1255//   `T`
1256//
1257// [2] Per https://doc.rust-lang.org/1.85.0/core/cell/struct.UnsafeCell.html#memory-layout:
1258//
1259//   `UnsafeCell<T>` has the same in-memory representation as its inner type
1260//   `T`.
1261//
1262// [3] Per https://doc.rust-lang.org/1.85.0/core/cell/struct.Cell.html#memory-layout:
1263//
1264//   `Cell<T>` has the same in-memory representation as `T`.
1265#[allow(clippy::multiple_unsafe_ops_per_block)]
1266const _: () = unsafe {
1267    unsafe_impl_known_layout!(
1268        #[repr([u8])]
1269        str
1270    );
1271    unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] ManuallyDrop<T>);
1272    unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] UnsafeCell<T>);
1273    unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] Cell<T>);
1274};
1275
1276// SAFETY:
1277// - By consequence of the invariant on `T::MaybeUninit` that `T::LAYOUT` and
1278//   `T::MaybeUninit::LAYOUT` are equal, `T` and `T::MaybeUninit` have the same:
1279//   - Fixed prefix size
1280//   - Alignment
1281//   - (For DSTs) trailing slice element size
1282// - By consequence of the above, referents `T::MaybeUninit` and `T` have the
1283//   require the same kind of pointer metadata, and thus it is valid to perform
1284//   an `as` cast from `*mut T` and `*mut T::MaybeUninit`, and this operation
1285//   preserves referent size (ie, `size_of_val_raw`).
1286const _: () = unsafe {
1287    unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T::MaybeUninit)] MaybeUninit<T>)
1288};
1289
1290// FIXME(#196, #2856): Eventually, we'll want to support enums variants and
1291// union fields being treated uniformly since they behave similarly to each
1292// other in terms of projecting validity – specifically, for a type `T` with
1293// validity `V`, if `T` is a struct type, then its fields straightforwardly also
1294// have validity `V`. By contrast, if `T` is an enum or union type, then
1295// validity is not straightforwardly recursive in this way.
1296#[doc(hidden)]
1297pub const STRUCT_VARIANT_ID: i128 = -1;
1298#[doc(hidden)]
1299pub const UNION_VARIANT_ID: i128 = -2;
1300#[doc(hidden)]
1301pub const REPR_C_UNION_VARIANT_ID: i128 = -3;
1302
1303/// Marker types used to disambiguate implementations of projection traits that
1304/// would otherwise conflict.
1305#[doc(hidden)]
1306#[allow(missing_copy_implementations, missing_debug_implementations)]
1307pub mod project_clients {
1308    pub enum TryFromBytesDerive {}
1309
1310    pub enum ProjectDerive {}
1311}
1312
1313#[cfg(any(feature = "derive", test))]
1314#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
1315#[doc(hidden)]
1316pub use zerocopy_derive::Project;
1317
1318/// # Safety
1319///
1320/// `<Self as HasTag<Client>>::ProjectToTag` must satisfy its safety invariant.
1321///
1322/// The `Client` parameter exists solely to disambiguate between implementations
1323/// of `HasTag` that would otherwise conflict.
1324#[doc(hidden)]
1325pub unsafe trait HasTag<Client = project_clients::TryFromBytesDerive> {
1326    fn only_derive_is_allowed_to_implement_this_trait()
1327    where
1328        Self: Sized;
1329
1330    /// The type's enum tag, or `()` for non-enum types.
1331    type Tag: Immutable;
1332
1333    /// A pointer projection from `Self` to its tag.
1334    ///
1335    /// # Safety
1336    ///
1337    /// It must be the case that, for all `slf: Ptr<'_, Self, I>` where
1338    /// `I::Aliasing` is `Shared`, it is sound to project it using this
1339    /// projection to a `Ptr<'_, Self::Tag, (Shared, I::Alignment,
1340    /// I::Validity)>`.
1341    type ProjectToTag: pointer::cast::Project<Self, Self::Tag>;
1342}
1343
1344/// Projects a given field from `Self`.
1345///
1346/// All implementations of `HasField` for a particular `Client` and field `f`
1347/// in `Self` should use the same `Field` type; this ensures that `Field` is
1348/// inferable given an explicit `Client`, `VARIANT_ID`, and `FIELD_ID`.
1349///
1350/// The `Client` parameter exists solely to disambiguate between implementations
1351/// of `HasField` that would otherwise conflict.
1352///
1353/// # Safety
1354///
1355/// A field `f` is `HasField` for `Self` if and only if:
1356///
1357/// - If `Self` has the layout of a struct type, `VARIANT_ID` is
1358///   `STRUCT_VARIANT_ID`. If `Self` has the layout of a `repr(C)` union type,
1359///   `VARIANT_ID` is `REPR_C_UNION_VARIANT_ID`; for other union layouts, it is
1360///   `UNION_VARIANT_ID`. Otherwise, if `Self` has the layout of an enum type and
1361///   `f` appears in a variant named `v`, `VARIANT_ID` is
1362///   `zerocopy::ident_id!(v)`. Note that `Self` does not need to actually *be*
1363///   such a type – it just needs to have the same layout as such a type. For
1364///   example, a `#[repr(transparent)]` wrapper around an enum has the same
1365///   layout as that enum.
1366/// - If `f` has name `n`, `FIELD_ID` is `zerocopy::ident_id!(n)`; otherwise,
1367///   if `f` is at index `i`, `FIELD_ID` is `zerocopy::ident_id!(i)`.
1368/// - `Field` is a type with the same visibility as `f`.
1369/// - `Type` has the same type as `f`.
1370///
1371/// The caller must **not** assume that a pointer's referent being aligned
1372/// implies that calling `project` on that pointer will result in a pointer to
1373/// an aligned referent. For example, `HasField` may be implemented for
1374/// `#[repr(packed)]` structs.
1375///
1376/// The implementation of `project` must satisfy its safety post-condition.
1377#[doc(hidden)]
1378pub unsafe trait HasField<Client, Field, const VARIANT_ID: i128, const FIELD_ID: i128>:
1379    HasTag<Client>
1380{
1381    fn only_derive_is_allowed_to_implement_this_trait()
1382    where
1383        Self: Sized;
1384
1385    /// The type of the field.
1386    type Type: ?Sized;
1387
1388    /// Projects from `slf` to the field.
1389    ///
1390    /// Users should generally not call `project` directly, and instead should
1391    /// use high-level APIs like [`PtrInner::project`] or [`Ptr::project`].
1392    ///
1393    /// # Safety
1394    ///
1395    /// The returned pointer refers to a non-strict subset of the bytes of
1396    /// `slf`'s referent, and has the same provenance as `slf`.
1397    #[must_use]
1398    fn project(slf: PtrInner<'_, Self>) -> *mut Self::Type;
1399}
1400
1401/// Projects a given field from `Self`.
1402///
1403/// Implementations of this trait encode the conditions under which a field can
1404/// be projected from a `Ptr<'_, Self, I>`, and how the invariants of that
1405/// [`Ptr`] (`I`) determine the invariants of pointers projected from it. In
1406/// other words, it is a type-level function over invariants; `I` goes in,
1407/// `Self::Invariants` comes out.
1408///
1409/// The `Client` parameter exists solely to disambiguate between implementations
1410/// of `ProjectField` (and their corresponding `HasField` implementations) that
1411/// would otherwise conflict.
1412///
1413/// # Safety
1414///
1415/// `T: ProjectField<Client, Field, I, VARIANT_ID, FIELD_ID>` if, for a
1416/// `ptr: Ptr<'_, T, I>` such that `T::is_projectable` returns `Ok(())`
1417/// when passed the tag pointer projected from `ptr`,
1418/// `<T as HasField<Client, Field, VARIANT_ID, FIELD_ID>>::project(ptr.as_inner())`
1419/// conforms to `T::Invariants`.
1420#[doc(hidden)]
1421pub unsafe trait ProjectField<Client, Field, I, const VARIANT_ID: i128, const FIELD_ID: i128>:
1422    HasField<Client, Field, VARIANT_ID, FIELD_ID>
1423where
1424    I: invariant::Invariants,
1425{
1426    fn only_derive_is_allowed_to_implement_this_trait()
1427    where
1428        Self: Sized;
1429
1430    /// The invariants of the projected field pointer, with respect to the
1431    /// invariants, `I`, of the containing pointer. The aliasing dimension of
1432    /// the invariants is guaranteed to remain unchanged.
1433    type Invariants: invariant::Invariants<Aliasing = I::Aliasing>;
1434
1435    /// The failure mode of projection. `()` if the projection is fallible,
1436    /// otherwise [`core::convert::Infallible`].
1437    type Error;
1438
1439    /// Is the given field projectable from `ptr`?
1440    ///
1441    /// If a field with [`Self::Invariants`] is projectable from the containing
1442    /// value whose projected tag is `ptr`, this function produces `Ok(())`;
1443    /// otherwise it produces `Err`.
1444    ///
1445    /// This method must be overriden if the field's projectability depends on
1446    /// the value of the bytes in `ptr`.
1447    #[inline(always)]
1448    fn is_projectable<'a>(
1449        _ptr: Ptr<
1450            'a,
1451            <Self as HasTag<Client>>::Tag,
1452            (invariant::Shared, I::Alignment, I::Validity),
1453        >,
1454    ) -> Result<(), Self::Error> {
1455        trait IsInfallible {
1456            const IS_INFALLIBLE: bool;
1457        }
1458
1459        struct Projection<T, Client, Field, I, const VARIANT_ID: i128, const FIELD_ID: i128>(
1460            PhantomData<(Client, Field, I, T)>,
1461        )
1462        where
1463            T: ?Sized + HasField<Client, Field, VARIANT_ID, FIELD_ID>,
1464            I: invariant::Invariants;
1465
1466        impl<T, Client, Field, I, const VARIANT_ID: i128, const FIELD_ID: i128> IsInfallible
1467            for Projection<T, Client, Field, I, VARIANT_ID, FIELD_ID>
1468        where
1469            T: ?Sized + HasField<Client, Field, VARIANT_ID, FIELD_ID>,
1470            I: invariant::Invariants,
1471        {
1472            const IS_INFALLIBLE: bool = {
1473                let is_infallible = match VARIANT_ID {
1474                    // For nondestructive projections of struct and union
1475                    // fields, the projected field's satisfaction of
1476                    // `Invariants` does not depend on the value of the
1477                    // referent. This default implementation of `is_projectable`
1478                    // is non-destructive, as it does not overwrite any part of
1479                    // the referent.
1480                    crate::STRUCT_VARIANT_ID
1481                    | crate::UNION_VARIANT_ID
1482                    | crate::REPR_C_UNION_VARIANT_ID => true,
1483                    _enum_variant => {
1484                        use crate::invariant::{Validity, ValidityKind};
1485                        match I::Validity::KIND {
1486                            // The `Uninit` and `Initialized` validity
1487                            // invariants do not depend on the enum's tag. In
1488                            // particular, we don't actually care about what
1489                            // variant is present – we can treat *any* range of
1490                            // uninitialized or initialized memory as containing
1491                            // an uninitialized or initialized instance of *any*
1492                            // type – the type itself is irrelevant.
1493                            ValidityKind::Uninit | ValidityKind::Initialized => true,
1494                            // The projectability of an enum field from an
1495                            // `AsInitialized` or `Safe` state is a dynamic
1496                            // property of its tag.
1497                            ValidityKind::AsInitialized | ValidityKind::Safe => false,
1498                        }
1499                    }
1500                };
1501                const_assert!(is_infallible);
1502                is_infallible
1503            };
1504        }
1505
1506        const_assert!(
1507            <Projection<Self, Client, Field, I, VARIANT_ID, FIELD_ID> as IsInfallible>::IS_INFALLIBLE
1508        );
1509
1510        Ok(())
1511    }
1512}
1513
1514/// Analyzes whether a type is [`FromZeros`].
1515///
1516/// This derive analyzes, at compile time, whether the annotated type satisfies
1517/// the [safety conditions] of `FromZeros` and implements `FromZeros` and its
1518/// supertraits if it is sound to do so. This derive can be applied to structs,
1519/// enums, and unions; e.g.:
1520///
1521/// ```
1522/// # use zerocopy_derive::{FromZeros, Immutable};
1523/// #[derive(FromZeros)]
1524/// struct MyStruct {
1525/// # /*
1526///     ...
1527/// # */
1528/// }
1529///
1530/// #[derive(FromZeros)]
1531/// #[repr(u8)]
1532/// enum MyEnum {
1533/// #   Variant0,
1534/// # /*
1535///     ...
1536/// # */
1537/// }
1538///
1539/// #[derive(FromZeros, Immutable)]
1540/// union MyUnion {
1541/// #   variant: u8,
1542/// # /*
1543///     ...
1544/// # */
1545/// }
1546/// ```
1547///
1548/// [safety conditions]: trait@FromZeros#safety
1549///
1550/// # Analysis
1551///
1552/// *This section describes, roughly, the analysis performed by this derive to
1553/// determine whether it is sound to implement `FromZeros` for a given type.
1554/// Unless you are modifying the implementation of this derive, or attempting to
1555/// manually implement `FromZeros` for a type yourself, you don't need to read
1556/// this section.*
1557///
1558/// If a type has the following properties, then this derive can implement
1559/// `FromZeros` for that type:
1560///
1561/// - If the type is a struct, all of its fields must be `FromZeros`.
1562/// - If the type is an enum:
1563///   - It must have a defined representation (`repr`s `C`, `u8`, `u16`, `u32`,
1564///     `u64`, `usize`, `i8`, `i16`, `i32`, `i64`, or `isize`).
1565///   - It must have a variant with a discriminant/tag of `0`, and its fields
1566///     must be `FromZeros`. See [the reference] for a description of
1567///     discriminant values are specified.
1568///   - The fields of that variant must be `FromZeros`.
1569///
1570/// This analysis is subject to change. Unsafe code may *only* rely on the
1571/// documented [safety conditions] of `FromZeros`, and must *not* rely on the
1572/// implementation details of this derive.
1573///
1574/// [the reference]: https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
1575///
1576/// ## Why isn't an explicit representation required for structs?
1577///
1578/// Neither this derive, nor the [safety conditions] of `FromZeros`, requires
1579/// that structs are marked with `#[repr(C)]`.
1580///
1581/// Per the [Rust reference][the Rust reference],
1582///
1583/// > The representation of a type can change the padding between fields, but
1584/// > does not change the layout of the fields themselves.
1585///
1586/// [the Rust reference]: https://doc.rust-lang.org/reference/type-layout.html#representations
1587///
1588/// Since the layout of structs only consists of padding bytes and field bytes,
1589/// a struct is soundly `FromZeros` if:
1590/// 1. its padding is soundly `FromZeros`, and
1591/// 2. its fields are soundly `FromZeros`.
1592///
1593/// The answer to the first question is always yes: padding bytes do not have
1594/// any validity constraints. A [discussion] of this question in the Unsafe Code
1595/// Guidelines Working Group concluded that it would be virtually unimaginable
1596/// for future versions of rustc to add validity constraints to padding bytes.
1597///
1598/// [discussion]: https://github.com/rust-lang/unsafe-code-guidelines/issues/174
1599///
1600/// Whether a struct is soundly `FromZeros` therefore solely depends on whether
1601/// its fields are `FromZeros`.
1602// FIXME(#146): Document why we don't require an enum to have an explicit `repr`
1603// attribute.
1604#[cfg(any(feature = "derive", test))]
1605#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
1606pub use zerocopy_derive::FromZeros;
1607/// Analyzes whether a type is [`Immutable`].
1608///
1609/// This derive analyzes, at compile time, whether the annotated type satisfies
1610/// the [safety conditions] of `Immutable` and implements `Immutable` if it is
1611/// sound to do so. This derive can be applied to structs, enums, and unions;
1612/// e.g.:
1613///
1614/// ```
1615/// # use zerocopy_derive::Immutable;
1616/// #[derive(Immutable)]
1617/// struct MyStruct {
1618/// # /*
1619///     ...
1620/// # */
1621/// }
1622///
1623/// #[derive(Immutable)]
1624/// enum MyEnum {
1625/// #   Variant0,
1626/// # /*
1627///     ...
1628/// # */
1629/// }
1630///
1631/// #[derive(Immutable)]
1632/// union MyUnion {
1633/// #   variant: u8,
1634/// # /*
1635///     ...
1636/// # */
1637/// }
1638/// ```
1639///
1640/// # Analysis
1641///
1642/// *This section describes, roughly, the analysis performed by this derive to
1643/// determine whether it is sound to implement `Immutable` for a given type.
1644/// Unless you are modifying the implementation of this derive, you don't need
1645/// to read this section.*
1646///
1647/// If a type has the following properties, then this derive can implement
1648/// `Immutable` for that type:
1649///
1650/// - All fields must be `Immutable`.
1651///
1652/// This analysis is subject to change. Unsafe code may *only* rely on the
1653/// documented [safety conditions] of `Immutable`, and must *not* rely on the
1654/// implementation details of this derive.
1655///
1656/// [safety conditions]: trait@Immutable#safety
1657#[cfg(any(feature = "derive", test))]
1658#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
1659pub use zerocopy_derive::Immutable;
1660
1661/// Types which are free from interior mutability.
1662///
1663/// `T: Immutable` indicates that `T` does not permit interior mutation, except
1664/// by ownership or an exclusive (`&mut`) borrow.
1665///
1666/// # Implementation
1667///
1668/// **Do not implement this trait yourself!** Instead, use
1669/// [`#[derive(Immutable)]`][derive] (requires the `derive` Cargo feature);
1670/// e.g.:
1671///
1672/// ```
1673/// # use zerocopy_derive::Immutable;
1674/// #[derive(Immutable)]
1675/// struct MyStruct {
1676/// # /*
1677///     ...
1678/// # */
1679/// }
1680///
1681/// #[derive(Immutable)]
1682/// enum MyEnum {
1683/// # /*
1684///     ...
1685/// # */
1686/// }
1687///
1688/// #[derive(Immutable)]
1689/// union MyUnion {
1690/// #   variant: u8,
1691/// # /*
1692///     ...
1693/// # */
1694/// }
1695/// ```
1696///
1697/// This derive performs a sophisticated, compile-time safety analysis to
1698/// determine whether a type is `Immutable`.
1699///
1700/// # Safety
1701///
1702/// Unsafe code outside of this crate must not make any assumptions about `T`
1703/// based on `T: Immutable`. We reserve the right to relax the requirements for
1704/// `Immutable` in the future, and if unsafe code outside of this crate makes
1705/// assumptions based on `T: Immutable`, future relaxations may cause that code
1706/// to become unsound.
1707///
1708// # Safety (Internal)
1709//
1710// If `T: Immutable`, unsafe code *inside of this crate* may assume that, given
1711// `t: &T`, `t` does not permit interior mutation of its referent. Because
1712// [`UnsafeCell`] is the only type which permits interior mutation, it is
1713// sufficient (though not necessary) to guarantee that `T` contains no
1714// `UnsafeCell`s.
1715//
1716// [`UnsafeCell`]: core::cell::UnsafeCell
1717#[cfg_attr(
1718    feature = "derive",
1719    doc = "[derive]: zerocopy_derive::Immutable",
1720    doc = "[derive-analysis]: zerocopy_derive::Immutable#analysis"
1721)]
1722#[cfg_attr(
1723    not(feature = "derive"),
1724    doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Immutable.html"),
1725    doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Immutable.html#analysis"),
1726)]
1727#[cfg_attr(
1728    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
1729    diagnostic::on_unimplemented(note = "Consider adding `#[derive(Immutable)]` to `{Self}`")
1730)]
1731pub unsafe trait Immutable {
1732    // The `Self: Sized` bound makes it so that `Immutable` is still object
1733    // safe.
1734    #[doc(hidden)]
1735    fn only_derive_is_allowed_to_implement_this_trait()
1736    where
1737        Self: Sized;
1738}
1739
1740/// Implements [`TryFromBytes`].
1741///
1742/// This derive synthesizes the runtime checks required to check whether a
1743/// sequence of initialized bytes corresponds to a valid instance of a type.
1744/// This derive can be applied to structs, enums, and unions; e.g.:
1745///
1746/// ```
1747/// # use zerocopy_derive::{TryFromBytes, Immutable};
1748/// #[derive(TryFromBytes)]
1749/// struct MyStruct {
1750/// # /*
1751///     ...
1752/// # */
1753/// }
1754///
1755/// #[derive(TryFromBytes)]
1756/// #[repr(u8)]
1757/// enum MyEnum {
1758/// #   V00,
1759/// # /*
1760///     ...
1761/// # */
1762/// }
1763///
1764/// #[derive(TryFromBytes, Immutable)]
1765/// union MyUnion {
1766/// #   variant: u8,
1767/// # /*
1768///     ...
1769/// # */
1770/// }
1771/// ```
1772///
1773#[cfg_attr(
1774    zerocopy_unstable_ptr,
1775    doc = r#"
1776# Field invariants
1777
1778This experimental feature requires `--cfg zerocopy_unstable_ptr`.
1779
1780Named fields of structs, enum variants, and unions can specify additional
1781runtime checks using `#[zerocopy(invariant(expression))]`:
1782
1783```
1784# use zerocopy_derive::TryFromBytes;
1785#[derive(TryFromBytes)]
1786struct Foo {
1787    a: u8,
1788    #[zerocopy(invariant((*a.read() % 2) == (*b.read() as u8)))]
1789    b: bool,
1790    #[zerocopy(invariant(*c.read() > 0))]
1791    c: i16,
1792}
1793```
1794
1795Each expression must return a `bool`. It has access to validated, read-only
1796[`Ptr`]s to the current field and all preceding fields of the struct or
1797variant, using their field names. A union's invariants have access only to
1798the current field. The expression can use the existing [`Ptr`] APIs to
1799inspect those fields. In this example, `read()` copies each field without
1800requiring alignment, and dereferencing the resulting [`ReadOnly`] accesses
1801the copied value.
1802
1803Rust's usual restrictions on local bindings apply; for example, a field name
1804cannot shadow an in-scope constant.
1805
1806Fields are checked in declaration order. Each field's bit validity is
1807checked before its invariants run. Multiple invariants on a field run in
1808attribute order. For structs and enums, validation stops at the first invalid
1809field or invariant that returns `false`. For unions, a failed bit-validity
1810check or invariant causes validation to try the next field; validation
1811succeeds as soon as one field and all its invariants pass. Each expression
1812runs in its own closure; `return` returns from that expression, and panics
1813propagate to the caller. Only the selected enum variant's fields and
1814invariants are checked. Expressions may have arbitrary side effects, even
1815when the conversion fails or its result is discarded.
1816
1817These predicates are additional acceptance checks beyond Rust's bit validity;
1818bit-valid bytes may still be rejected. See [What is a "valid instance"?] for
1819the distinction.
1820
1821[What is a "valid instance"?]: trait@TryFromBytes#what-is-a-valid-instance
1822
1823Invariants are not supported on tuple fields. Types with invariants cannot
1824derive [`FromZeros`] or [`FromBytes`], whose conversions do not perform runtime
1825validation. These checks apply to conversions through [`TryFromBytes`]; they
1826do not restrict ordinary construction or mutation of Rust values.
1827
1828"#
1829)]
1830///
1831/// # Portability
1832///
1833/// To ensure consistent endianness for enums with multi-byte representations,
1834/// explicitly specify and convert each discriminant using `.to_le()` or
1835/// `.to_be()`; e.g.:
1836///
1837/// ```
1838/// # use zerocopy_derive::TryFromBytes;
1839/// // `DataStoreVersion` is encoded in little-endian.
1840/// #[derive(TryFromBytes)]
1841/// #[repr(u32)]
1842/// pub enum DataStoreVersion {
1843///     /// Version 1 of the data store.
1844///     V1 = 9u32.to_le(),
1845///
1846///     /// Version 2 of the data store.
1847///     V2 = 10u32.to_le(),
1848/// }
1849/// ```
1850///
1851/// [safety conditions]: trait@TryFromBytes#safety
1852#[cfg(any(feature = "derive", test))]
1853#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
1854pub use zerocopy_derive::TryFromBytes;
1855
1856/// Types for which some bit patterns are valid.
1857///
1858/// A memory region of the appropriate length which contains initialized bytes
1859/// can be viewed as a `TryFromBytes` type so long as the runtime value of those
1860/// bytes corresponds to a [*valid instance*] of that type. For example,
1861/// [`bool`] is `TryFromBytes`, so zerocopy can transmute a [`u8`] into a
1862/// [`bool`] so long as it first checks that the value of the [`u8`] is `0` or
1863/// `1`.
1864///
1865/// # Implementation
1866///
1867/// **Do not implement this trait yourself!** Instead, use
1868/// [`#[derive(TryFromBytes)]`][derive]; e.g.:
1869///
1870/// ```
1871/// # use zerocopy_derive::{TryFromBytes, Immutable};
1872/// #[derive(TryFromBytes)]
1873/// struct MyStruct {
1874/// # /*
1875///     ...
1876/// # */
1877/// }
1878///
1879/// #[derive(TryFromBytes)]
1880/// #[repr(u8)]
1881/// enum MyEnum {
1882/// #   V00,
1883/// # /*
1884///     ...
1885/// # */
1886/// }
1887///
1888/// #[derive(TryFromBytes, Immutable)]
1889/// union MyUnion {
1890/// #   variant: u8,
1891/// # /*
1892///     ...
1893/// # */
1894/// }
1895/// ```
1896///
1897/// This derive ensures that the runtime check of whether bytes correspond to a
1898/// valid instance is sound. You **must** implement this trait via the derive.
1899///
1900/// # What is a "valid instance"?
1901///
1902/// In Rust, each type has *bit validity*, which refers to the set of bit
1903/// patterns which may appear in an instance of that type. It is impossible for
1904/// safe Rust code to produce values which violate bit validity (ie, values
1905/// outside of the "valid" set of bit patterns). If `unsafe` code produces an
1906/// invalid value, this is considered [undefined behavior].
1907///
1908/// Rust's bit validity rules are currently being decided, which means that some
1909/// types have three classes of bit patterns: those which are definitely valid,
1910/// and whose validity is documented in the language; those which may or may not
1911/// be considered valid at some point in the future; and those which are
1912/// definitely invalid.
1913///
1914/// Zerocopy takes a conservative approach, and only considers a bit pattern to
1915/// be valid if its validity is a documented guarantee provided by the
1916/// language.
1917///
1918/// For most use cases, Rust's current guarantees align with programmers'
1919/// intuitions about what ought to be valid. As a result, zerocopy's
1920/// conservatism should not affect most users.
1921///
1922/// If you are negatively affected by lack of support for a particular type,
1923/// we encourage you to let us know by [filing an issue][github-repo].
1924///
1925/// In this trait's conversion methods, a "valid instance" must also pass any
1926/// configured field invariants, including those on nested fields. Rust bit
1927/// validity alone does not guarantee that a conversion succeeds: an invariant
1928/// may reject otherwise bit-valid bytes. Such predicates check acceptance at
1929/// conversion time; they do not constrain subsequent mutation or ordinary Rust
1930/// construction. See the [derive's field invariants][derive] documentation for
1931/// the experimental attribute's syntax, evaluation order, and side effects.
1932///
1933/// # `TryFromBytes` is not symmetrical with [`IntoBytes`]
1934///
1935/// There are some types which implement both `TryFromBytes` and [`IntoBytes`],
1936/// but for which `TryFromBytes` is not guaranteed to accept all byte sequences
1937/// produced by `IntoBytes`. In other words, for some `T: TryFromBytes +
1938/// IntoBytes`, there exist values of `t: T` such that
1939/// `TryFromBytes::try_ref_from_bytes(t.as_bytes()) == None`. Code should not
1940/// generally assume that values produced by `IntoBytes` will necessarily be
1941/// accepted as valid by `TryFromBytes`.
1942///
1943/// # Safety
1944///
1945/// On its own, `T: TryFromBytes` does not make any guarantees about the layout
1946/// or representation of `T`. It merely provides the ability to perform a
1947/// validity check at runtime via methods like [`try_ref_from_bytes`].
1948///
1949/// You must not rely on the `#[doc(hidden)]` internals of `TryFromBytes`.
1950/// Future releases of zerocopy may make backwards-breaking changes to these
1951/// items, including changes that only affect soundness, which may cause code
1952/// which uses those items to silently become unsound.
1953///
1954/// [undefined behavior]: https://raphlinus.github.io/programming/rust/2018/08/17/undefined-behavior.html
1955/// [github-repo]: https://github.com/google/zerocopy
1956/// [`try_ref_from_bytes`]: TryFromBytes::try_ref_from_bytes
1957/// [*valid instance*]: #what-is-a-valid-instance
1958#[cfg_attr(feature = "derive", doc = "[derive]: zerocopy_derive::TryFromBytes")]
1959#[cfg_attr(
1960    not(feature = "derive"),
1961    doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.TryFromBytes.html"),
1962)]
1963#[cfg_attr(
1964    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
1965    diagnostic::on_unimplemented(note = "Consider adding `#[derive(TryFromBytes)]` to `{Self}`")
1966)]
1967pub unsafe trait TryFromBytes {
1968    // The `Self: Sized` bound makes it so that `TryFromBytes` is still object
1969    // safe.
1970    #[doc(hidden)]
1971    fn only_derive_is_allowed_to_implement_this_trait()
1972    where
1973        Self: Sized;
1974
1975    /// Does a given memory range contain a valid instance of `Self`?
1976    ///
1977    /// # Safety
1978    ///
1979    /// Unsafe code may assume that, if `is_safe(candidate)` returns true,
1980    /// `*candidate` contains a valid `Self`.
1981    ///
1982    /// # Panics
1983    ///
1984    /// `is_safe` may panic. Callers are responsible for ensuring that any
1985    /// `unsafe` code remains sound even in the face of `is_safe` panicking. (We
1986    /// support user-defined validation routines; so long as these routines are
1987    /// not required to be `unsafe`, there is no way to ensure that these do not
1988    /// generate panics.)
1989    ///
1990    /// Besides user-defined validation routines panicking, `is_safe` will either
1991    /// panic or fail to compile if called on a pointer with [`Shared`] aliasing
1992    /// when `Self: !Immutable`.
1993    ///
1994    /// [`UnsafeCell`]: core::cell::UnsafeCell
1995    /// [`Shared`]: invariant::Shared
1996    #[doc(hidden)]
1997    fn is_safe<A>(candidate: Maybe<'_, Self, A>) -> bool
1998    where
1999        A: invariant::Alignment;
2000
2001    /// Attempts to interpret the given `source` as a `&Self`.
2002    ///
2003    /// If the bytes of `source` are a valid instance of `Self`, this method
2004    /// returns a reference to those bytes interpreted as a `Self`. If the
2005    /// length of `source` is not a [valid size of `Self`][valid-size], or if
2006    /// `source` is not appropriately aligned, or if `source` is not a valid
2007    /// instance of `Self`, this returns `Err`. If [`Self:
2008    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
2009    /// error][ConvertError::from].
2010    ///
2011    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
2012    ///
2013    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
2014    /// [self-unaligned]: Unaligned
2015    /// [slice-dst]: KnownLayout#dynamically-sized-types
2016    ///
2017    /// # Compile-Time Assertions
2018    ///
2019    /// This method cannot yet be used on unsized types whose dynamically-sized
2020    /// component is zero-sized. Attempting to use this method on such types
2021    /// results in a compile-time assertion error; e.g.:
2022    ///
2023    /// ```compile_fail,E0080
2024    /// use zerocopy::*;
2025    /// # use zerocopy_derive::*;
2026    ///
2027    /// #[derive(TryFromBytes, Immutable, KnownLayout)]
2028    /// #[repr(C)]
2029    /// struct ZSTy {
2030    ///     leading_sized: u16,
2031    ///     trailing_dst: [()],
2032    /// }
2033    ///
2034    /// let _ = ZSTy::try_ref_from_bytes(0u16.as_bytes()); // âš  Compile Error!
2035    /// ```
2036    ///
2037    /// # Examples
2038    ///
2039    /// ```
2040    /// use zerocopy::TryFromBytes;
2041    /// # use zerocopy_derive::*;
2042    ///
2043    /// // The only valid value of this type is the byte `0xC0`
2044    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2045    /// #[repr(u8)]
2046    /// enum C0 { xC0 = 0xC0 }
2047    ///
2048    /// // The only valid value of this type is the byte sequence `0xC0C0`.
2049    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2050    /// #[repr(C)]
2051    /// struct C0C0(C0, C0);
2052    ///
2053    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2054    /// #[repr(C)]
2055    /// struct Packet {
2056    ///     magic_number: C0C0,
2057    ///     mug_size: u8,
2058    ///     temperature: u8,
2059    ///     marshmallows: [[u8; 2]],
2060    /// }
2061    ///
2062    /// let bytes = &[0xC0, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5][..];
2063    ///
2064    /// let packet = Packet::try_ref_from_bytes(bytes).unwrap();
2065    ///
2066    /// assert_eq!(packet.mug_size, 240);
2067    /// assert_eq!(packet.temperature, 77);
2068    /// assert_eq!(packet.marshmallows, [[0, 1], [2, 3], [4, 5]]);
2069    ///
2070    /// // These bytes are not valid instance of `Packet`.
2071    /// let bytes = &[0x10, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5][..];
2072    /// assert!(Packet::try_ref_from_bytes(bytes).is_err());
2073    /// ```
2074    ///
2075    #[doc = codegen_section!(
2076        header = "h5",
2077        bench = "try_ref_from_bytes",
2078        format = "coco",
2079        arity = 3,
2080        [
2081            open
2082            @index 1
2083            @title "Sized"
2084            @variant "static_size"
2085        ],
2086        [
2087            @index 2
2088            @title "Unsized"
2089            @variant "dynamic_size"
2090        ],
2091        [
2092            @index 3
2093            @title "Dynamically Padded"
2094            @variant "dynamic_padding"
2095        ]
2096    )]
2097    #[must_use = "the conversion result must be checked"]
2098    #[cfg_attr(zerocopy_inline_always, inline(always))]
2099    #[cfg_attr(not(zerocopy_inline_always), inline)]
2100    fn try_ref_from_bytes(source: &[u8]) -> Result<&Self, TryCastError<&[u8], Self>>
2101    where
2102        Self: KnownLayout + Immutable,
2103    {
2104        static_assert_dst_is_not_zst!(Self);
2105        match Ptr::from_ref(source).try_cast_into_no_leftover::<Self, BecauseImmutable>(None) {
2106            Ok(source) => {
2107                // This call may panic. If that happens, it doesn't cause any soundness
2108                // issues, as we have not generated any invalid state which we need to
2109                // fix before returning.
2110                match source.try_into_safe() {
2111                    Ok(valid) => Ok(valid.as_ref()),
2112                    Err(e) => {
2113                        Err(e.map_src(|src| src.as_bytes::<BecauseImmutable>().as_ref()).into())
2114                    }
2115                }
2116            }
2117            Err(e) => Err(e.map_src(Ptr::as_ref).into()),
2118        }
2119    }
2120
2121    /// Attempts to interpret the prefix of the given `source` as a `&Self`.
2122    ///
2123    /// This method computes the [largest possible size of `Self`][valid-size]
2124    /// that can fit in the leading bytes of `source`. If that prefix is a valid
2125    /// instance of `Self`, this method returns a reference to those bytes
2126    /// interpreted as `Self`, and a reference to the remaining bytes. If there
2127    /// are insufficient bytes, or if `source` is not appropriately aligned, or
2128    /// if those bytes are not a valid instance of `Self`, this returns `Err`.
2129    /// If [`Self: Unaligned`][self-unaligned], you can [infallibly discard the
2130    /// alignment error][ConvertError::from].
2131    ///
2132    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
2133    ///
2134    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
2135    /// [self-unaligned]: Unaligned
2136    /// [slice-dst]: KnownLayout#dynamically-sized-types
2137    ///
2138    /// # Compile-Time Assertions
2139    ///
2140    /// This method cannot yet be used on unsized types whose dynamically-sized
2141    /// component is zero-sized. Attempting to use this method on such types
2142    /// results in a compile-time assertion error; e.g.:
2143    ///
2144    /// ```compile_fail,E0080
2145    /// use zerocopy::*;
2146    /// # use zerocopy_derive::*;
2147    ///
2148    /// #[derive(TryFromBytes, Immutable, KnownLayout)]
2149    /// #[repr(C)]
2150    /// struct ZSTy {
2151    ///     leading_sized: u16,
2152    ///     trailing_dst: [()],
2153    /// }
2154    ///
2155    /// let _ = ZSTy::try_ref_from_prefix(0u16.as_bytes()); // âš  Compile Error!
2156    /// ```
2157    ///
2158    /// # Examples
2159    ///
2160    /// ```
2161    /// use zerocopy::TryFromBytes;
2162    /// # use zerocopy_derive::*;
2163    ///
2164    /// // The only valid value of this type is the byte `0xC0`
2165    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2166    /// #[repr(u8)]
2167    /// enum C0 { xC0 = 0xC0 }
2168    ///
2169    /// // The only valid value of this type is the bytes `0xC0C0`.
2170    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2171    /// #[repr(C)]
2172    /// struct C0C0(C0, C0);
2173    ///
2174    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2175    /// #[repr(C)]
2176    /// struct Packet {
2177    ///     magic_number: C0C0,
2178    ///     mug_size: u8,
2179    ///     temperature: u8,
2180    ///     marshmallows: [[u8; 2]],
2181    /// }
2182    ///
2183    /// // These are more bytes than are needed to encode a `Packet`.
2184    /// let bytes = &[0xC0, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5, 6][..];
2185    ///
2186    /// let (packet, suffix) = Packet::try_ref_from_prefix(bytes).unwrap();
2187    ///
2188    /// assert_eq!(packet.mug_size, 240);
2189    /// assert_eq!(packet.temperature, 77);
2190    /// assert_eq!(packet.marshmallows, [[0, 1], [2, 3], [4, 5]]);
2191    /// assert_eq!(suffix, &[6u8][..]);
2192    ///
2193    /// // These bytes are not valid instance of `Packet`.
2194    /// let bytes = &[0x10, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5, 6][..];
2195    /// assert!(Packet::try_ref_from_prefix(bytes).is_err());
2196    /// ```
2197    ///
2198    #[doc = codegen_section!(
2199        header = "h5",
2200        bench = "try_ref_from_prefix",
2201        format = "coco",
2202        arity = 3,
2203        [
2204            open
2205            @index 1
2206            @title "Sized"
2207            @variant "static_size"
2208        ],
2209        [
2210            @index 2
2211            @title "Unsized"
2212            @variant "dynamic_size"
2213        ],
2214        [
2215            @index 3
2216            @title "Dynamically Padded"
2217            @variant "dynamic_padding"
2218        ]
2219    )]
2220    #[must_use = "the conversion result must be checked"]
2221    #[cfg_attr(zerocopy_inline_always, inline(always))]
2222    #[cfg_attr(not(zerocopy_inline_always), inline)]
2223    fn try_ref_from_prefix(source: &[u8]) -> Result<(&Self, &[u8]), TryCastError<&[u8], Self>>
2224    where
2225        Self: KnownLayout + Immutable,
2226    {
2227        static_assert_dst_is_not_zst!(Self);
2228        try_ref_from_prefix_suffix(source, CastType::Prefix, None)
2229    }
2230
2231    /// Attempts to interpret the suffix of the given `source` as a `&Self`.
2232    ///
2233    /// This method computes the [largest possible size of `Self`][valid-size]
2234    /// that can fit in the trailing bytes of `source`. If that suffix is a
2235    /// valid instance of `Self`, this method returns a reference to those bytes
2236    /// interpreted as `Self`, and a reference to the preceding bytes. If there
2237    /// are insufficient bytes, or if the suffix of `source` would not be
2238    /// appropriately aligned, or if the suffix is not a valid instance of
2239    /// `Self`, this returns `Err`. If [`Self: Unaligned`][self-unaligned], you
2240    /// can [infallibly discard the alignment error][ConvertError::from].
2241    ///
2242    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
2243    ///
2244    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
2245    /// [self-unaligned]: Unaligned
2246    /// [slice-dst]: KnownLayout#dynamically-sized-types
2247    ///
2248    /// # Compile-Time Assertions
2249    ///
2250    /// This method cannot yet be used on unsized types whose dynamically-sized
2251    /// component is zero-sized. Attempting to use this method on such types
2252    /// results in a compile-time assertion error; e.g.:
2253    ///
2254    /// ```compile_fail,E0080
2255    /// use zerocopy::*;
2256    /// # use zerocopy_derive::*;
2257    ///
2258    /// #[derive(TryFromBytes, Immutable, KnownLayout)]
2259    /// #[repr(C)]
2260    /// struct ZSTy {
2261    ///     leading_sized: u16,
2262    ///     trailing_dst: [()],
2263    /// }
2264    ///
2265    /// let _ = ZSTy::try_ref_from_suffix(0u16.as_bytes()); // âš  Compile Error!
2266    /// ```
2267    ///
2268    /// # Examples
2269    ///
2270    /// ```
2271    /// use zerocopy::TryFromBytes;
2272    /// # use zerocopy_derive::*;
2273    ///
2274    /// // The only valid value of this type is the byte `0xC0`
2275    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2276    /// #[repr(u8)]
2277    /// enum C0 { xC0 = 0xC0 }
2278    ///
2279    /// // The only valid value of this type is the bytes `0xC0C0`.
2280    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2281    /// #[repr(C)]
2282    /// struct C0C0(C0, C0);
2283    ///
2284    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2285    /// #[repr(C)]
2286    /// struct Packet {
2287    ///     magic_number: C0C0,
2288    ///     mug_size: u8,
2289    ///     temperature: u8,
2290    ///     marshmallows: [[u8; 2]],
2291    /// }
2292    ///
2293    /// // These are more bytes than are needed to encode a `Packet`.
2294    /// let bytes = &[0, 0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7][..];
2295    ///
2296    /// let (prefix, packet) = Packet::try_ref_from_suffix(bytes).unwrap();
2297    ///
2298    /// assert_eq!(packet.mug_size, 240);
2299    /// assert_eq!(packet.temperature, 77);
2300    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
2301    /// assert_eq!(prefix, &[0u8][..]);
2302    ///
2303    /// // These bytes are not valid instance of `Packet`.
2304    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 77, 240, 0xC0, 0x10][..];
2305    /// assert!(Packet::try_ref_from_suffix(bytes).is_err());
2306    /// ```
2307    ///
2308    #[doc = codegen_section!(
2309        header = "h5",
2310        bench = "try_ref_from_suffix",
2311        format = "coco",
2312        arity = 3,
2313        [
2314            open
2315            @index 1
2316            @title "Sized"
2317            @variant "static_size"
2318        ],
2319        [
2320            @index 2
2321            @title "Unsized"
2322            @variant "dynamic_size"
2323        ],
2324        [
2325            @index 3
2326            @title "Dynamically Padded"
2327            @variant "dynamic_padding"
2328        ]
2329    )]
2330    #[must_use = "the conversion result must be checked"]
2331    #[cfg_attr(zerocopy_inline_always, inline(always))]
2332    #[cfg_attr(not(zerocopy_inline_always), inline)]
2333    fn try_ref_from_suffix(source: &[u8]) -> Result<(&[u8], &Self), TryCastError<&[u8], Self>>
2334    where
2335        Self: KnownLayout + Immutable,
2336    {
2337        static_assert_dst_is_not_zst!(Self);
2338        try_ref_from_prefix_suffix(source, CastType::Suffix, None).map(swap)
2339    }
2340
2341    /// Attempts to interpret the given `source` as a `&mut Self` without
2342    /// copying.
2343    ///
2344    /// If the bytes of `source` are a valid instance of `Self`, this method
2345    /// returns a reference to those bytes interpreted as a `Self`. If the
2346    /// length of `source` is not a [valid size of `Self`][valid-size], or if
2347    /// `source` is not appropriately aligned, or if `source` is not a valid
2348    /// instance of `Self`, this returns `Err`. If [`Self:
2349    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
2350    /// error][ConvertError::from].
2351    ///
2352    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
2353    ///
2354    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
2355    /// [self-unaligned]: Unaligned
2356    /// [slice-dst]: KnownLayout#dynamically-sized-types
2357    ///
2358    /// # Compile-Time Assertions
2359    ///
2360    /// This method cannot yet be used on unsized types whose dynamically-sized
2361    /// component is zero-sized. Attempting to use this method on such types
2362    /// results in a compile-time assertion error; e.g.:
2363    ///
2364    /// ```compile_fail,E0080
2365    /// use zerocopy::*;
2366    /// # use zerocopy_derive::*;
2367    ///
2368    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2369    /// #[repr(C, packed)]
2370    /// struct ZSTy {
2371    ///     leading_sized: [u8; 2],
2372    ///     trailing_dst: [()],
2373    /// }
2374    ///
2375    /// let mut source = [85, 85];
2376    /// let _ = ZSTy::try_mut_from_bytes(&mut source[..]); // âš  Compile Error!
2377    /// ```
2378    ///
2379    /// # Examples
2380    ///
2381    /// ```
2382    /// use zerocopy::TryFromBytes;
2383    /// # use zerocopy_derive::*;
2384    ///
2385    /// // The only valid value of this type is the byte `0xC0`
2386    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2387    /// #[repr(u8)]
2388    /// enum C0 { xC0 = 0xC0 }
2389    ///
2390    /// // The only valid value of this type is the bytes `0xC0C0`.
2391    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2392    /// #[repr(C)]
2393    /// struct C0C0(C0, C0);
2394    ///
2395    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2396    /// #[repr(C, packed)]
2397    /// struct Packet {
2398    ///     magic_number: C0C0,
2399    ///     mug_size: u8,
2400    ///     temperature: u8,
2401    ///     marshmallows: [[u8; 2]],
2402    /// }
2403    ///
2404    /// let bytes = &mut [0xC0, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5][..];
2405    ///
2406    /// let packet = Packet::try_mut_from_bytes(bytes).unwrap();
2407    ///
2408    /// assert_eq!(packet.mug_size, 240);
2409    /// assert_eq!(packet.temperature, 77);
2410    /// assert_eq!(packet.marshmallows, [[0, 1], [2, 3], [4, 5]]);
2411    ///
2412    /// packet.temperature = 111;
2413    ///
2414    /// assert_eq!(bytes, [0xC0, 0xC0, 240, 111, 0, 1, 2, 3, 4, 5]);
2415    ///
2416    /// // These bytes are not valid instance of `Packet`.
2417    /// let bytes = &mut [0x10, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5, 6][..];
2418    /// assert!(Packet::try_mut_from_bytes(bytes).is_err());
2419    /// ```
2420    ///
2421    #[doc = codegen_section!(
2422        header = "h5",
2423        name = "try_mut_from_bytes",
2424        /// See [`TryFromBytes::try_ref_from_bytes`](#method.try_ref_from_bytes.codegen).
2425    )]
2426    #[must_use = "the conversion result must be checked"]
2427    #[cfg_attr(zerocopy_inline_always, inline(always))]
2428    #[cfg_attr(not(zerocopy_inline_always), inline)]
2429    fn try_mut_from_bytes(bytes: &mut [u8]) -> Result<&mut Self, TryCastError<&mut [u8], Self>>
2430    where
2431        Self: KnownLayout + IntoBytes,
2432    {
2433        static_assert_dst_is_not_zst!(Self);
2434        match Ptr::from_mut(bytes).try_cast_into_no_leftover::<Self, BecauseExclusive>(None) {
2435            Ok(source) => {
2436                // This call may panic. If that happens, it doesn't cause any soundness
2437                // issues, as we have not generated any invalid state which we need to
2438                // fix before returning.
2439                match source.try_into_safe() {
2440                    Ok(source) => Ok(source.as_mut()),
2441                    Err(e) => Err(e.map_src(|src| src.as_bytes().as_mut()).into()),
2442                }
2443            }
2444            Err(e) => Err(e.map_src(Ptr::as_mut).into()),
2445        }
2446    }
2447
2448    /// Attempts to interpret the prefix of the given `source` as a `&mut
2449    /// Self`.
2450    ///
2451    /// This method computes the [largest possible size of `Self`][valid-size]
2452    /// that can fit in the leading bytes of `source`. If that prefix is a valid
2453    /// instance of `Self`, this method returns a reference to those bytes
2454    /// interpreted as `Self`, and a reference to the remaining bytes. If there
2455    /// are insufficient bytes, or if `source` is not appropriately aligned, or
2456    /// if the bytes are not a valid instance of `Self`, this returns `Err`. If
2457    /// [`Self: Unaligned`][self-unaligned], you can [infallibly discard the
2458    /// alignment error][ConvertError::from].
2459    ///
2460    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
2461    ///
2462    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
2463    /// [self-unaligned]: Unaligned
2464    /// [slice-dst]: KnownLayout#dynamically-sized-types
2465    ///
2466    /// # Compile-Time Assertions
2467    ///
2468    /// This method cannot yet be used on unsized types whose dynamically-sized
2469    /// component is zero-sized. Attempting to use this method on such types
2470    /// results in a compile-time assertion error; e.g.:
2471    ///
2472    /// ```compile_fail,E0080
2473    /// use zerocopy::*;
2474    /// # use zerocopy_derive::*;
2475    ///
2476    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2477    /// #[repr(C, packed)]
2478    /// struct ZSTy {
2479    ///     leading_sized: [u8; 2],
2480    ///     trailing_dst: [()],
2481    /// }
2482    ///
2483    /// let mut source = [85, 85];
2484    /// let _ = ZSTy::try_mut_from_prefix(&mut source[..]); // âš  Compile Error!
2485    /// ```
2486    ///
2487    /// # Examples
2488    ///
2489    /// ```
2490    /// use zerocopy::TryFromBytes;
2491    /// # use zerocopy_derive::*;
2492    ///
2493    /// // The only valid value of this type is the byte `0xC0`
2494    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2495    /// #[repr(u8)]
2496    /// enum C0 { xC0 = 0xC0 }
2497    ///
2498    /// // The only valid value of this type is the bytes `0xC0C0`.
2499    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2500    /// #[repr(C)]
2501    /// struct C0C0(C0, C0);
2502    ///
2503    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2504    /// #[repr(C, packed)]
2505    /// struct Packet {
2506    ///     magic_number: C0C0,
2507    ///     mug_size: u8,
2508    ///     temperature: u8,
2509    ///     marshmallows: [[u8; 2]],
2510    /// }
2511    ///
2512    /// // These are more bytes than are needed to encode a `Packet`.
2513    /// let bytes = &mut [0xC0, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5, 6][..];
2514    ///
2515    /// let (packet, suffix) = Packet::try_mut_from_prefix(bytes).unwrap();
2516    ///
2517    /// assert_eq!(packet.mug_size, 240);
2518    /// assert_eq!(packet.temperature, 77);
2519    /// assert_eq!(packet.marshmallows, [[0, 1], [2, 3], [4, 5]]);
2520    /// assert_eq!(suffix, &[6u8][..]);
2521    ///
2522    /// packet.temperature = 111;
2523    /// suffix[0] = 222;
2524    ///
2525    /// assert_eq!(bytes, [0xC0, 0xC0, 240, 111, 0, 1, 2, 3, 4, 5, 222]);
2526    ///
2527    /// // These bytes are not valid instance of `Packet`.
2528    /// let bytes = &mut [0x10, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5, 6][..];
2529    /// assert!(Packet::try_mut_from_prefix(bytes).is_err());
2530    /// ```
2531    ///
2532    #[doc = codegen_section!(
2533        header = "h5",
2534        name = "try_mut_from_prefix",
2535        /// See [`TryFromBytes::try_ref_from_prefix`](#method.try_ref_from_prefix.codegen).
2536    )]
2537    #[must_use = "the conversion result must be checked"]
2538    #[cfg_attr(zerocopy_inline_always, inline(always))]
2539    #[cfg_attr(not(zerocopy_inline_always), inline)]
2540    fn try_mut_from_prefix(
2541        source: &mut [u8],
2542    ) -> Result<(&mut Self, &mut [u8]), TryCastError<&mut [u8], Self>>
2543    where
2544        Self: KnownLayout + IntoBytes,
2545    {
2546        static_assert_dst_is_not_zst!(Self);
2547        try_mut_from_prefix_suffix(source, CastType::Prefix, None)
2548    }
2549
2550    /// Attempts to interpret the suffix of the given `source` as a `&mut
2551    /// Self`.
2552    ///
2553    /// This method computes the [largest possible size of `Self`][valid-size]
2554    /// that can fit in the trailing bytes of `source`. If that suffix is a
2555    /// valid instance of `Self`, this method returns a reference to those bytes
2556    /// interpreted as `Self`, and a reference to the preceding bytes. If there
2557    /// are insufficient bytes, or if the suffix of `source` would not be
2558    /// appropriately aligned, or if the suffix is not a valid instance of
2559    /// `Self`, this returns `Err`. If [`Self: Unaligned`][self-unaligned], you
2560    /// can [infallibly discard the alignment error][ConvertError::from].
2561    ///
2562    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
2563    ///
2564    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
2565    /// [self-unaligned]: Unaligned
2566    /// [slice-dst]: KnownLayout#dynamically-sized-types
2567    ///
2568    /// # Compile-Time Assertions
2569    ///
2570    /// This method cannot yet be used on unsized types whose dynamically-sized
2571    /// component is zero-sized. Attempting to use this method on such types
2572    /// results in a compile-time assertion error; e.g.:
2573    ///
2574    /// ```compile_fail,E0080
2575    /// use zerocopy::*;
2576    /// # use zerocopy_derive::*;
2577    ///
2578    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2579    /// #[repr(C, packed)]
2580    /// struct ZSTy {
2581    ///     leading_sized: u16,
2582    ///     trailing_dst: [()],
2583    /// }
2584    ///
2585    /// let mut source = [85, 85];
2586    /// let _ = ZSTy::try_mut_from_suffix(&mut source[..]); // âš  Compile Error!
2587    /// ```
2588    ///
2589    /// # Examples
2590    ///
2591    /// ```
2592    /// use zerocopy::TryFromBytes;
2593    /// # use zerocopy_derive::*;
2594    ///
2595    /// // The only valid value of this type is the byte `0xC0`
2596    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2597    /// #[repr(u8)]
2598    /// enum C0 { xC0 = 0xC0 }
2599    ///
2600    /// // The only valid value of this type is the bytes `0xC0C0`.
2601    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2602    /// #[repr(C)]
2603    /// struct C0C0(C0, C0);
2604    ///
2605    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
2606    /// #[repr(C, packed)]
2607    /// struct Packet {
2608    ///     magic_number: C0C0,
2609    ///     mug_size: u8,
2610    ///     temperature: u8,
2611    ///     marshmallows: [[u8; 2]],
2612    /// }
2613    ///
2614    /// // These are more bytes than are needed to encode a `Packet`.
2615    /// let bytes = &mut [0, 0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7][..];
2616    ///
2617    /// let (prefix, packet) = Packet::try_mut_from_suffix(bytes).unwrap();
2618    ///
2619    /// assert_eq!(packet.mug_size, 240);
2620    /// assert_eq!(packet.temperature, 77);
2621    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
2622    /// assert_eq!(prefix, &[0u8][..]);
2623    ///
2624    /// prefix[0] = 111;
2625    /// packet.temperature = 222;
2626    ///
2627    /// assert_eq!(bytes, [111, 0xC0, 0xC0, 240, 222, 2, 3, 4, 5, 6, 7]);
2628    ///
2629    /// // These bytes are not valid instance of `Packet`.
2630    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 77, 240, 0xC0, 0x10][..];
2631    /// assert!(Packet::try_mut_from_suffix(bytes).is_err());
2632    /// ```
2633    ///
2634    #[doc = codegen_section!(
2635        header = "h5",
2636        name = "try_mut_from_suffix",
2637        /// See [`TryFromBytes::try_ref_from_suffix`](#method.try_ref_from_suffix.codegen).
2638    )]
2639    #[must_use = "the conversion result must be checked"]
2640    #[cfg_attr(zerocopy_inline_always, inline(always))]
2641    #[cfg_attr(not(zerocopy_inline_always), inline)]
2642    fn try_mut_from_suffix(
2643        source: &mut [u8],
2644    ) -> Result<(&mut [u8], &mut Self), TryCastError<&mut [u8], Self>>
2645    where
2646        Self: KnownLayout + IntoBytes,
2647    {
2648        static_assert_dst_is_not_zst!(Self);
2649        try_mut_from_prefix_suffix(source, CastType::Suffix, None).map(swap)
2650    }
2651
2652    /// Attempts to interpret the given `source` as a `&Self` with a DST length
2653    /// equal to `count`.
2654    ///
2655    /// This method attempts to return a reference to `source` interpreted as a
2656    /// `Self` with `count` trailing elements. If the length of `source` is not
2657    /// equal to the size of `Self` with `count` elements, if `source` is not
2658    /// appropriately aligned, or if `source` does not contain a valid instance
2659    /// of `Self`, this returns `Err`. If [`Self: Unaligned`][self-unaligned],
2660    /// you can [infallibly discard the alignment error][ConvertError::from].
2661    ///
2662    /// [self-unaligned]: Unaligned
2663    /// [slice-dst]: KnownLayout#dynamically-sized-types
2664    ///
2665    /// # Examples
2666    ///
2667    /// ```
2668    /// # #![allow(non_camel_case_types)] // For C0::xC0
2669    /// use zerocopy::TryFromBytes;
2670    /// # use zerocopy_derive::*;
2671    ///
2672    /// // The only valid value of this type is the byte `0xC0`
2673    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2674    /// #[repr(u8)]
2675    /// enum C0 { xC0 = 0xC0 }
2676    ///
2677    /// // The only valid value of this type is the bytes `0xC0C0`.
2678    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2679    /// #[repr(C)]
2680    /// struct C0C0(C0, C0);
2681    ///
2682    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2683    /// #[repr(C)]
2684    /// struct Packet {
2685    ///     magic_number: C0C0,
2686    ///     mug_size: u8,
2687    ///     temperature: u8,
2688    ///     marshmallows: [[u8; 2]],
2689    /// }
2690    ///
2691    /// let bytes = &[0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7][..];
2692    ///
2693    /// let packet = Packet::try_ref_from_bytes_with_elems(bytes, 3).unwrap();
2694    ///
2695    /// assert_eq!(packet.mug_size, 240);
2696    /// assert_eq!(packet.temperature, 77);
2697    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
2698    ///
2699    /// // These bytes are not valid instance of `Packet`.
2700    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 77, 240, 0xC0, 0xC0][..];
2701    /// assert!(Packet::try_ref_from_bytes_with_elems(bytes, 3).is_err());
2702    /// ```
2703    ///
2704    /// Since an explicit `count` is provided, this method supports types with
2705    /// zero-sized trailing slice elements. Methods such as [`try_ref_from_bytes`]
2706    /// which do not take an explicit count do not support such types.
2707    ///
2708    /// ```
2709    /// use core::num::NonZeroU16;
2710    /// use zerocopy::*;
2711    /// # use zerocopy_derive::*;
2712    ///
2713    /// #[derive(TryFromBytes, Immutable, KnownLayout)]
2714    /// #[repr(C)]
2715    /// struct ZSTy {
2716    ///     leading_sized: NonZeroU16,
2717    ///     trailing_dst: [()],
2718    /// }
2719    ///
2720    /// let src = 0xCAFEu16.as_bytes();
2721    /// let zsty = ZSTy::try_ref_from_bytes_with_elems(src, 42).unwrap();
2722    /// assert_eq!(zsty.trailing_dst.len(), 42);
2723    /// ```
2724    ///
2725    /// [`try_ref_from_bytes`]: TryFromBytes::try_ref_from_bytes
2726    ///
2727    #[doc = codegen_section!(
2728        header = "h5",
2729        bench = "try_ref_from_bytes_with_elems",
2730        format = "coco",
2731        arity = 2,
2732        [
2733            open
2734            @index 1
2735            @title "Unsized"
2736            @variant "dynamic_size"
2737        ],
2738        [
2739            @index 2
2740            @title "Dynamically Padded"
2741            @variant "dynamic_padding"
2742        ]
2743    )]
2744    #[must_use = "the conversion result must be checked"]
2745    #[cfg_attr(zerocopy_inline_always, inline(always))]
2746    #[cfg_attr(not(zerocopy_inline_always), inline)]
2747    fn try_ref_from_bytes_with_elems(
2748        source: &[u8],
2749        count: usize,
2750    ) -> Result<&Self, TryCastError<&[u8], Self>>
2751    where
2752        Self: KnownLayout<PointerMetadata = usize> + Immutable,
2753    {
2754        match Ptr::from_ref(source).try_cast_into_no_leftover::<Self, BecauseImmutable>(Some(count))
2755        {
2756            Ok(source) => {
2757                // This call may panic. If that happens, it doesn't cause any soundness
2758                // issues, as we have not generated any invalid state which we need to
2759                // fix before returning.
2760                match source.try_into_safe() {
2761                    Ok(source) => Ok(source.as_ref()),
2762                    Err(e) => {
2763                        Err(e.map_src(|src| src.as_bytes::<BecauseImmutable>().as_ref()).into())
2764                    }
2765                }
2766            }
2767            Err(e) => Err(e.map_src(Ptr::as_ref).into()),
2768        }
2769    }
2770
2771    /// Attempts to interpret the prefix of the given `source` as a `&Self` with
2772    /// a DST length equal to `count`.
2773    ///
2774    /// This method attempts to return a reference to the prefix of `source`
2775    /// interpreted as a `Self` with `count` trailing elements, and a reference
2776    /// to the remaining bytes. If the length of `source` is less than the size
2777    /// of `Self` with `count` elements, if `source` is not appropriately
2778    /// aligned, or if the prefix of `source` does not contain a valid instance
2779    /// of `Self`, this returns `Err`. If [`Self: Unaligned`][self-unaligned],
2780    /// you can [infallibly discard the alignment error][ConvertError::from].
2781    ///
2782    /// [self-unaligned]: Unaligned
2783    /// [slice-dst]: KnownLayout#dynamically-sized-types
2784    ///
2785    /// # Examples
2786    ///
2787    /// ```
2788    /// # #![allow(non_camel_case_types)] // For C0::xC0
2789    /// use zerocopy::TryFromBytes;
2790    /// # use zerocopy_derive::*;
2791    ///
2792    /// // The only valid value of this type is the byte `0xC0`
2793    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2794    /// #[repr(u8)]
2795    /// enum C0 { xC0 = 0xC0 }
2796    ///
2797    /// // The only valid value of this type is the bytes `0xC0C0`.
2798    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2799    /// #[repr(C)]
2800    /// struct C0C0(C0, C0);
2801    ///
2802    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2803    /// #[repr(C)]
2804    /// struct Packet {
2805    ///     magic_number: C0C0,
2806    ///     mug_size: u8,
2807    ///     temperature: u8,
2808    ///     marshmallows: [[u8; 2]],
2809    /// }
2810    ///
2811    /// let bytes = &[0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7, 8][..];
2812    ///
2813    /// let (packet, suffix) = Packet::try_ref_from_prefix_with_elems(bytes, 3).unwrap();
2814    ///
2815    /// assert_eq!(packet.mug_size, 240);
2816    /// assert_eq!(packet.temperature, 77);
2817    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
2818    /// assert_eq!(suffix, &[8u8][..]);
2819    ///
2820    /// // These bytes are not valid instance of `Packet`.
2821    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 77, 240, 0xC0, 0xC0][..];
2822    /// assert!(Packet::try_ref_from_prefix_with_elems(bytes, 3).is_err());
2823    /// ```
2824    ///
2825    /// Since an explicit `count` is provided, this method supports types with
2826    /// zero-sized trailing slice elements. Methods such as [`try_ref_from_prefix`]
2827    /// which do not take an explicit count do not support such types.
2828    ///
2829    /// ```
2830    /// use core::num::NonZeroU16;
2831    /// use zerocopy::*;
2832    /// # use zerocopy_derive::*;
2833    ///
2834    /// #[derive(TryFromBytes, Immutable, KnownLayout)]
2835    /// #[repr(C)]
2836    /// struct ZSTy {
2837    ///     leading_sized: NonZeroU16,
2838    ///     trailing_dst: [()],
2839    /// }
2840    ///
2841    /// let src = 0xCAFEu16.as_bytes();
2842    /// let (zsty, _) = ZSTy::try_ref_from_prefix_with_elems(src, 42).unwrap();
2843    /// assert_eq!(zsty.trailing_dst.len(), 42);
2844    /// ```
2845    ///
2846    /// [`try_ref_from_prefix`]: TryFromBytes::try_ref_from_prefix
2847    ///
2848    #[doc = codegen_section!(
2849        header = "h5",
2850        bench = "try_ref_from_prefix_with_elems",
2851        format = "coco",
2852        arity = 2,
2853        [
2854            open
2855            @index 1
2856            @title "Unsized"
2857            @variant "dynamic_size"
2858        ],
2859        [
2860            @index 2
2861            @title "Dynamically Padded"
2862            @variant "dynamic_padding"
2863        ]
2864    )]
2865    #[must_use = "the conversion result must be checked"]
2866    #[cfg_attr(zerocopy_inline_always, inline(always))]
2867    #[cfg_attr(not(zerocopy_inline_always), inline)]
2868    fn try_ref_from_prefix_with_elems(
2869        source: &[u8],
2870        count: usize,
2871    ) -> Result<(&Self, &[u8]), TryCastError<&[u8], Self>>
2872    where
2873        Self: KnownLayout<PointerMetadata = usize> + Immutable,
2874    {
2875        try_ref_from_prefix_suffix(source, CastType::Prefix, Some(count))
2876    }
2877
2878    /// Attempts to interpret the suffix of the given `source` as a `&Self` with
2879    /// a DST length equal to `count`.
2880    ///
2881    /// This method attempts to return a reference to the suffix of `source`
2882    /// interpreted as a `Self` with `count` trailing elements, and a reference
2883    /// to the preceding bytes. If the length of `source` is less than the size
2884    /// of `Self` with `count` elements, if the suffix of `source` is not
2885    /// appropriately aligned, or if the suffix of `source` does not contain a
2886    /// valid instance of `Self`, this returns `Err`. If [`Self:
2887    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
2888    /// error][ConvertError::from].
2889    ///
2890    /// [self-unaligned]: Unaligned
2891    /// [slice-dst]: KnownLayout#dynamically-sized-types
2892    ///
2893    /// # Examples
2894    ///
2895    /// ```
2896    /// # #![allow(non_camel_case_types)] // For C0::xC0
2897    /// use zerocopy::TryFromBytes;
2898    /// # use zerocopy_derive::*;
2899    ///
2900    /// // The only valid value of this type is the byte `0xC0`
2901    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2902    /// #[repr(u8)]
2903    /// enum C0 { xC0 = 0xC0 }
2904    ///
2905    /// // The only valid value of this type is the bytes `0xC0C0`.
2906    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2907    /// #[repr(C)]
2908    /// struct C0C0(C0, C0);
2909    ///
2910    /// #[derive(TryFromBytes, KnownLayout, Immutable)]
2911    /// #[repr(C)]
2912    /// struct Packet {
2913    ///     magic_number: C0C0,
2914    ///     mug_size: u8,
2915    ///     temperature: u8,
2916    ///     marshmallows: [[u8; 2]],
2917    /// }
2918    ///
2919    /// let bytes = &[123, 0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7][..];
2920    ///
2921    /// let (prefix, packet) = Packet::try_ref_from_suffix_with_elems(bytes, 3).unwrap();
2922    ///
2923    /// assert_eq!(packet.mug_size, 240);
2924    /// assert_eq!(packet.temperature, 77);
2925    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
2926    /// assert_eq!(prefix, &[123u8][..]);
2927    ///
2928    /// // These bytes are not valid instance of `Packet`.
2929    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 77, 240, 0xC0, 0xC0][..];
2930    /// assert!(Packet::try_ref_from_suffix_with_elems(bytes, 3).is_err());
2931    /// ```
2932    ///
2933    /// Since an explicit `count` is provided, this method supports types with
2934    /// zero-sized trailing slice elements. Methods such as [`try_ref_from_prefix`]
2935    /// which do not take an explicit count do not support such types.
2936    ///
2937    /// ```
2938    /// use core::num::NonZeroU16;
2939    /// use zerocopy::*;
2940    /// # use zerocopy_derive::*;
2941    ///
2942    /// #[derive(TryFromBytes, Immutable, KnownLayout)]
2943    /// #[repr(C)]
2944    /// struct ZSTy {
2945    ///     leading_sized: NonZeroU16,
2946    ///     trailing_dst: [()],
2947    /// }
2948    ///
2949    /// let src = 0xCAFEu16.as_bytes();
2950    /// let (_, zsty) = ZSTy::try_ref_from_suffix_with_elems(src, 42).unwrap();
2951    /// assert_eq!(zsty.trailing_dst.len(), 42);
2952    /// ```
2953    ///
2954    /// [`try_ref_from_prefix`]: TryFromBytes::try_ref_from_prefix
2955    ///
2956    #[doc = codegen_section!(
2957        header = "h5",
2958        bench = "try_ref_from_suffix_with_elems",
2959        format = "coco",
2960        arity = 2,
2961        [
2962            open
2963            @index 1
2964            @title "Unsized"
2965            @variant "dynamic_size"
2966        ],
2967        [
2968            @index 2
2969            @title "Dynamically Padded"
2970            @variant "dynamic_padding"
2971        ]
2972    )]
2973    #[must_use = "the conversion result must be checked"]
2974    #[cfg_attr(zerocopy_inline_always, inline(always))]
2975    #[cfg_attr(not(zerocopy_inline_always), inline)]
2976    fn try_ref_from_suffix_with_elems(
2977        source: &[u8],
2978        count: usize,
2979    ) -> Result<(&[u8], &Self), TryCastError<&[u8], Self>>
2980    where
2981        Self: KnownLayout<PointerMetadata = usize> + Immutable,
2982    {
2983        try_ref_from_prefix_suffix(source, CastType::Suffix, Some(count)).map(swap)
2984    }
2985
2986    /// Attempts to interpret the given `source` as a `&mut Self` with a DST
2987    /// length equal to `count`.
2988    ///
2989    /// This method attempts to return a reference to `source` interpreted as a
2990    /// `Self` with `count` trailing elements. If the length of `source` is not
2991    /// equal to the size of `Self` with `count` elements, if `source` is not
2992    /// appropriately aligned, or if `source` does not contain a valid instance
2993    /// of `Self`, this returns `Err`. If [`Self: Unaligned`][self-unaligned],
2994    /// you can [infallibly discard the alignment error][ConvertError::from].
2995    ///
2996    /// [self-unaligned]: Unaligned
2997    /// [slice-dst]: KnownLayout#dynamically-sized-types
2998    ///
2999    /// # Examples
3000    ///
3001    /// ```
3002    /// # #![allow(non_camel_case_types)] // For C0::xC0
3003    /// use zerocopy::TryFromBytes;
3004    /// # use zerocopy_derive::*;
3005    ///
3006    /// // The only valid value of this type is the byte `0xC0`
3007    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3008    /// #[repr(u8)]
3009    /// enum C0 { xC0 = 0xC0 }
3010    ///
3011    /// // The only valid value of this type is the bytes `0xC0C0`.
3012    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3013    /// #[repr(C)]
3014    /// struct C0C0(C0, C0);
3015    ///
3016    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3017    /// #[repr(C, packed)]
3018    /// struct Packet {
3019    ///     magic_number: C0C0,
3020    ///     mug_size: u8,
3021    ///     temperature: u8,
3022    ///     marshmallows: [[u8; 2]],
3023    /// }
3024    ///
3025    /// let bytes = &mut [0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7][..];
3026    ///
3027    /// let packet = Packet::try_mut_from_bytes_with_elems(bytes, 3).unwrap();
3028    ///
3029    /// assert_eq!(packet.mug_size, 240);
3030    /// assert_eq!(packet.temperature, 77);
3031    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
3032    ///
3033    /// packet.temperature = 111;
3034    ///
3035    /// assert_eq!(bytes, [0xC0, 0xC0, 240, 111, 2, 3, 4, 5, 6, 7]);
3036    ///
3037    /// // These bytes are not valid instance of `Packet`.
3038    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 77, 240, 0xC0, 0xC0][..];
3039    /// assert!(Packet::try_mut_from_bytes_with_elems(bytes, 3).is_err());
3040    /// ```
3041    ///
3042    /// Since an explicit `count` is provided, this method supports types with
3043    /// zero-sized trailing slice elements. Methods such as [`try_mut_from_bytes`]
3044    /// which do not take an explicit count do not support such types.
3045    ///
3046    /// ```
3047    /// use core::num::NonZeroU16;
3048    /// use zerocopy::*;
3049    /// # use zerocopy_derive::*;
3050    ///
3051    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3052    /// #[repr(C, packed)]
3053    /// struct ZSTy {
3054    ///     leading_sized: NonZeroU16,
3055    ///     trailing_dst: [()],
3056    /// }
3057    ///
3058    /// let mut src = 0xCAFEu16;
3059    /// let src = src.as_mut_bytes();
3060    /// let zsty = ZSTy::try_mut_from_bytes_with_elems(src, 42).unwrap();
3061    /// assert_eq!(zsty.trailing_dst.len(), 42);
3062    /// ```
3063    ///
3064    /// [`try_mut_from_bytes`]: TryFromBytes::try_mut_from_bytes
3065    ///
3066    #[doc = codegen_section!(
3067        header = "h5",
3068        name = "try_mut_from_bytes_with_elems",
3069        /// See [`TryFromBytes::try_ref_from_bytes_with_elems`](#method.try_ref_from_bytes_with_elems.codegen).
3070    )]
3071    #[must_use = "the conversion result must be checked"]
3072    #[cfg_attr(zerocopy_inline_always, inline(always))]
3073    #[cfg_attr(not(zerocopy_inline_always), inline)]
3074    fn try_mut_from_bytes_with_elems(
3075        source: &mut [u8],
3076        count: usize,
3077    ) -> Result<&mut Self, TryCastError<&mut [u8], Self>>
3078    where
3079        Self: KnownLayout<PointerMetadata = usize> + IntoBytes,
3080    {
3081        match Ptr::from_mut(source).try_cast_into_no_leftover::<Self, BecauseExclusive>(Some(count))
3082        {
3083            Ok(source) => {
3084                // This call may panic. If that happens, it doesn't cause any soundness
3085                // issues, as we have not generated any invalid state which we need to
3086                // fix before returning.
3087                match source.try_into_safe() {
3088                    Ok(source) => Ok(source.as_mut()),
3089                    Err(e) => Err(e.map_src(|src| src.as_bytes().as_mut()).into()),
3090                }
3091            }
3092            Err(e) => Err(e.map_src(Ptr::as_mut).into()),
3093        }
3094    }
3095
3096    /// Attempts to interpret the prefix of the given `source` as a `&mut Self`
3097    /// with a DST length equal to `count`.
3098    ///
3099    /// This method attempts to return a reference to the prefix of `source`
3100    /// interpreted as a `Self` with `count` trailing elements, and a reference
3101    /// to the remaining bytes. If the length of `source` is less than the size
3102    /// of `Self` with `count` elements, if `source` is not appropriately
3103    /// aligned, or if the prefix of `source` does not contain a valid instance
3104    /// of `Self`, this returns `Err`. If [`Self: Unaligned`][self-unaligned],
3105    /// you can [infallibly discard the alignment error][ConvertError::from].
3106    ///
3107    /// [self-unaligned]: Unaligned
3108    /// [slice-dst]: KnownLayout#dynamically-sized-types
3109    ///
3110    /// # Examples
3111    ///
3112    /// ```
3113    /// # #![allow(non_camel_case_types)] // For C0::xC0
3114    /// use zerocopy::TryFromBytes;
3115    /// # use zerocopy_derive::*;
3116    ///
3117    /// // The only valid value of this type is the byte `0xC0`
3118    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3119    /// #[repr(u8)]
3120    /// enum C0 { xC0 = 0xC0 }
3121    ///
3122    /// // The only valid value of this type is the bytes `0xC0C0`.
3123    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3124    /// #[repr(C)]
3125    /// struct C0C0(C0, C0);
3126    ///
3127    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3128    /// #[repr(C, packed)]
3129    /// struct Packet {
3130    ///     magic_number: C0C0,
3131    ///     mug_size: u8,
3132    ///     temperature: u8,
3133    ///     marshmallows: [[u8; 2]],
3134    /// }
3135    ///
3136    /// let bytes = &mut [0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7, 8][..];
3137    ///
3138    /// let (packet, suffix) = Packet::try_mut_from_prefix_with_elems(bytes, 3).unwrap();
3139    ///
3140    /// assert_eq!(packet.mug_size, 240);
3141    /// assert_eq!(packet.temperature, 77);
3142    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
3143    /// assert_eq!(suffix, &[8u8][..]);
3144    ///
3145    /// packet.temperature = 111;
3146    /// suffix[0] = 222;
3147    ///
3148    /// assert_eq!(bytes, [0xC0, 0xC0, 240, 111, 2, 3, 4, 5, 6, 7, 222]);
3149    ///
3150    /// // These bytes are not valid instance of `Packet`.
3151    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 77, 240, 0xC0, 0xC0][..];
3152    /// assert!(Packet::try_mut_from_prefix_with_elems(bytes, 3).is_err());
3153    /// ```
3154    ///
3155    /// Since an explicit `count` is provided, this method supports types with
3156    /// zero-sized trailing slice elements. Methods such as [`try_mut_from_prefix`]
3157    /// which do not take an explicit count do not support such types.
3158    ///
3159    /// ```
3160    /// use core::num::NonZeroU16;
3161    /// use zerocopy::*;
3162    /// # use zerocopy_derive::*;
3163    ///
3164    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3165    /// #[repr(C, packed)]
3166    /// struct ZSTy {
3167    ///     leading_sized: NonZeroU16,
3168    ///     trailing_dst: [()],
3169    /// }
3170    ///
3171    /// let mut src = 0xCAFEu16;
3172    /// let src = src.as_mut_bytes();
3173    /// let (zsty, _) = ZSTy::try_mut_from_prefix_with_elems(src, 42).unwrap();
3174    /// assert_eq!(zsty.trailing_dst.len(), 42);
3175    /// ```
3176    ///
3177    /// [`try_mut_from_prefix`]: TryFromBytes::try_mut_from_prefix
3178    ///
3179    #[doc = codegen_section!(
3180        header = "h5",
3181        name = "try_mut_from_prefix_with_elems",
3182        /// See [`TryFromBytes::try_ref_from_prefix_with_elems`](#method.try_ref_from_prefix_with_elems.codegen).
3183    )]
3184    #[must_use = "the conversion result must be checked"]
3185    #[cfg_attr(zerocopy_inline_always, inline(always))]
3186    #[cfg_attr(not(zerocopy_inline_always), inline)]
3187    fn try_mut_from_prefix_with_elems(
3188        source: &mut [u8],
3189        count: usize,
3190    ) -> Result<(&mut Self, &mut [u8]), TryCastError<&mut [u8], Self>>
3191    where
3192        Self: KnownLayout<PointerMetadata = usize> + IntoBytes,
3193    {
3194        try_mut_from_prefix_suffix(source, CastType::Prefix, Some(count))
3195    }
3196
3197    /// Attempts to interpret the suffix of the given `source` as a `&mut Self`
3198    /// with a DST length equal to `count`.
3199    ///
3200    /// This method attempts to return a reference to the suffix of `source`
3201    /// interpreted as a `Self` with `count` trailing elements, and a reference
3202    /// to the preceding bytes. If the length of `source` is less than the size
3203    /// of `Self` with `count` elements, if the suffix of `source` is not
3204    /// appropriately aligned, or if the suffix of `source` does not contain a
3205    /// valid instance of `Self`, this returns `Err`. If [`Self:
3206    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
3207    /// error][ConvertError::from].
3208    ///
3209    /// [self-unaligned]: Unaligned
3210    /// [slice-dst]: KnownLayout#dynamically-sized-types
3211    ///
3212    /// # Examples
3213    ///
3214    /// ```
3215    /// # #![allow(non_camel_case_types)] // For C0::xC0
3216    /// use zerocopy::TryFromBytes;
3217    /// # use zerocopy_derive::*;
3218    ///
3219    /// // The only valid value of this type is the byte `0xC0`
3220    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3221    /// #[repr(u8)]
3222    /// enum C0 { xC0 = 0xC0 }
3223    ///
3224    /// // The only valid value of this type is the bytes `0xC0C0`.
3225    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3226    /// #[repr(C)]
3227    /// struct C0C0(C0, C0);
3228    ///
3229    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3230    /// #[repr(C, packed)]
3231    /// struct Packet {
3232    ///     magic_number: C0C0,
3233    ///     mug_size: u8,
3234    ///     temperature: u8,
3235    ///     marshmallows: [[u8; 2]],
3236    /// }
3237    ///
3238    /// let bytes = &mut [123, 0xC0, 0xC0, 240, 77, 2, 3, 4, 5, 6, 7][..];
3239    ///
3240    /// let (prefix, packet) = Packet::try_mut_from_suffix_with_elems(bytes, 3).unwrap();
3241    ///
3242    /// assert_eq!(packet.mug_size, 240);
3243    /// assert_eq!(packet.temperature, 77);
3244    /// assert_eq!(packet.marshmallows, [[2, 3], [4, 5], [6, 7]]);
3245    /// assert_eq!(prefix, &[123u8][..]);
3246    ///
3247    /// prefix[0] = 111;
3248    /// packet.temperature = 222;
3249    ///
3250    /// assert_eq!(bytes, [111, 0xC0, 0xC0, 240, 222, 2, 3, 4, 5, 6, 7]);
3251    ///
3252    /// // These bytes are not valid instance of `Packet`.
3253    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 77, 240, 0xC0, 0xC0][..];
3254    /// assert!(Packet::try_mut_from_suffix_with_elems(bytes, 3).is_err());
3255    /// ```
3256    ///
3257    /// Since an explicit `count` is provided, this method supports types with
3258    /// zero-sized trailing slice elements. Methods such as [`try_mut_from_prefix`]
3259    /// which do not take an explicit count do not support such types.
3260    ///
3261    /// ```
3262    /// use core::num::NonZeroU16;
3263    /// use zerocopy::*;
3264    /// # use zerocopy_derive::*;
3265    ///
3266    /// #[derive(TryFromBytes, IntoBytes, KnownLayout)]
3267    /// #[repr(C, packed)]
3268    /// struct ZSTy {
3269    ///     leading_sized: NonZeroU16,
3270    ///     trailing_dst: [()],
3271    /// }
3272    ///
3273    /// let mut src = 0xCAFEu16;
3274    /// let src = src.as_mut_bytes();
3275    /// let (_, zsty) = ZSTy::try_mut_from_suffix_with_elems(src, 42).unwrap();
3276    /// assert_eq!(zsty.trailing_dst.len(), 42);
3277    /// ```
3278    ///
3279    /// [`try_mut_from_prefix`]: TryFromBytes::try_mut_from_prefix
3280    ///
3281    #[doc = codegen_section!(
3282        header = "h5",
3283        name = "try_mut_from_suffix_with_elems",
3284        /// See [`TryFromBytes::try_ref_from_suffix_with_elems`](#method.try_ref_from_suffix_with_elems.codegen).
3285    )]
3286    #[must_use = "the conversion result must be checked"]
3287    #[cfg_attr(zerocopy_inline_always, inline(always))]
3288    #[cfg_attr(not(zerocopy_inline_always), inline)]
3289    fn try_mut_from_suffix_with_elems(
3290        source: &mut [u8],
3291        count: usize,
3292    ) -> Result<(&mut [u8], &mut Self), TryCastError<&mut [u8], Self>>
3293    where
3294        Self: KnownLayout<PointerMetadata = usize> + IntoBytes,
3295    {
3296        try_mut_from_prefix_suffix(source, CastType::Suffix, Some(count)).map(swap)
3297    }
3298
3299    /// Attempts to read the given `source` as a `Self`.
3300    ///
3301    /// If `source.len() != size_of::<Self>()` or the bytes are not a valid
3302    /// instance of `Self`, this returns `Err`.
3303    ///
3304    /// # Examples
3305    ///
3306    /// ```
3307    /// use zerocopy::TryFromBytes;
3308    /// # use zerocopy_derive::*;
3309    ///
3310    /// // The only valid value of this type is the byte `0xC0`
3311    /// #[derive(TryFromBytes)]
3312    /// #[repr(u8)]
3313    /// enum C0 { xC0 = 0xC0 }
3314    ///
3315    /// // The only valid value of this type is the bytes `0xC0C0`.
3316    /// #[derive(TryFromBytes)]
3317    /// #[repr(C)]
3318    /// struct C0C0(C0, C0);
3319    ///
3320    /// #[derive(TryFromBytes)]
3321    /// #[repr(C)]
3322    /// struct Packet {
3323    ///     magic_number: C0C0,
3324    ///     mug_size: u8,
3325    ///     temperature: u8,
3326    /// }
3327    ///
3328    /// let bytes = &[0xC0, 0xC0, 240, 77][..];
3329    ///
3330    /// let packet = Packet::try_read_from_bytes(bytes).unwrap();
3331    ///
3332    /// assert_eq!(packet.mug_size, 240);
3333    /// assert_eq!(packet.temperature, 77);
3334    ///
3335    /// // These bytes are not valid instance of `Packet`.
3336    /// let bytes = &mut [0x10, 0xC0, 240, 77][..];
3337    /// assert!(Packet::try_read_from_bytes(bytes).is_err());
3338    /// ```
3339    ///
3340    /// # Performance Considerations
3341    ///
3342    /// In this version of zerocopy, this method reads the `source` into a
3343    /// well-aligned stack allocation and *then* validates that the allocation
3344    /// is a valid `Self`. This ensures that validation can be performed using
3345    /// aligned reads (which carry a performance advantage over unaligned reads
3346    /// on many platforms) at the cost of an unconditional copy.
3347    ///
3348    #[doc = codegen_section!(
3349        header = "h5",
3350        bench = "try_read_from_bytes",
3351        format = "coco_static_size",
3352    )]
3353    #[must_use = "the conversion result must be checked"]
3354    #[cfg_attr(zerocopy_inline_always, inline(always))]
3355    #[cfg_attr(not(zerocopy_inline_always), inline)]
3356    fn try_read_from_bytes(source: &[u8]) -> Result<Self, TryReadError<&[u8], Self>>
3357    where
3358        Self: Sized,
3359    {
3360        try_read_from(source)
3361    }
3362
3363    /// Attempts to read a `Self` from the prefix of the given `source`.
3364    ///
3365    /// This attempts to read a `Self` from the first `size_of::<Self>()` bytes
3366    /// of `source`, returning that `Self` and any remaining bytes. If
3367    /// `source.len() < size_of::<Self>()` or the bytes are not a valid instance
3368    /// of `Self`, it returns `Err`.
3369    ///
3370    /// # Examples
3371    ///
3372    /// ```
3373    /// use zerocopy::TryFromBytes;
3374    /// # use zerocopy_derive::*;
3375    ///
3376    /// // The only valid value of this type is the byte `0xC0`
3377    /// #[derive(TryFromBytes)]
3378    /// #[repr(u8)]
3379    /// enum C0 { xC0 = 0xC0 }
3380    ///
3381    /// // The only valid value of this type is the bytes `0xC0C0`.
3382    /// #[derive(TryFromBytes)]
3383    /// #[repr(C)]
3384    /// struct C0C0(C0, C0);
3385    ///
3386    /// #[derive(TryFromBytes)]
3387    /// #[repr(C)]
3388    /// struct Packet {
3389    ///     magic_number: C0C0,
3390    ///     mug_size: u8,
3391    ///     temperature: u8,
3392    /// }
3393    ///
3394    /// // These are more bytes than are needed to encode a `Packet`.
3395    /// let bytes = &[0xC0, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5, 6][..];
3396    ///
3397    /// let (packet, suffix) = Packet::try_read_from_prefix(bytes).unwrap();
3398    ///
3399    /// assert_eq!(packet.mug_size, 240);
3400    /// assert_eq!(packet.temperature, 77);
3401    /// assert_eq!(suffix, &[0u8, 1, 2, 3, 4, 5, 6][..]);
3402    ///
3403    /// // These bytes are not valid instance of `Packet`.
3404    /// let bytes = &[0x10, 0xC0, 240, 77, 0, 1, 2, 3, 4, 5, 6][..];
3405    /// assert!(Packet::try_read_from_prefix(bytes).is_err());
3406    /// ```
3407    ///
3408    /// # Performance Considerations
3409    ///
3410    /// In this version of zerocopy, this method reads the `source` into a
3411    /// well-aligned stack allocation and *then* validates that the allocation
3412    /// is a valid `Self`. This ensures that validation can be performed using
3413    /// aligned reads (which carry a performance advantage over unaligned reads
3414    /// on many platforms) at the cost of an unconditional copy.
3415    ///
3416    #[doc = codegen_section!(
3417        header = "h5",
3418        bench = "try_read_from_prefix",
3419        format = "coco_static_size",
3420    )]
3421    #[must_use = "the conversion result must be checked"]
3422    #[cfg_attr(zerocopy_inline_always, inline(always))]
3423    #[cfg_attr(not(zerocopy_inline_always), inline)]
3424    fn try_read_from_prefix(source: &[u8]) -> Result<(Self, &[u8]), TryReadError<&[u8], Self>>
3425    where
3426        Self: Sized,
3427    {
3428        let (prefix, suffix) = match SplitAt::split_at(source, mem::size_of::<Self>()) {
3429            Some(split) => split.via_immutable(),
3430            None => return Err(SizeError::new(source).into()),
3431        };
3432        match try_read_from(prefix) {
3433            Ok(slf) => Ok((slf, suffix)),
3434            Err(e) => Err(e.map_src(
3435                #[inline(always)]
3436                |_| source,
3437            )),
3438        }
3439    }
3440
3441    /// Attempts to read a `Self` from the suffix of the given `source`.
3442    ///
3443    /// This attempts to read a `Self` from the last `size_of::<Self>()` bytes
3444    /// of `source`, returning that `Self` and any preceding bytes. If
3445    /// `source.len() < size_of::<Self>()` or the bytes are not a valid instance
3446    /// of `Self`, it returns `Err`.
3447    ///
3448    /// # Examples
3449    ///
3450    /// ```
3451    /// # #![allow(non_camel_case_types)] // For C0::xC0
3452    /// use zerocopy::TryFromBytes;
3453    /// # use zerocopy_derive::*;
3454    ///
3455    /// // The only valid value of this type is the byte `0xC0`
3456    /// #[derive(TryFromBytes)]
3457    /// #[repr(u8)]
3458    /// enum C0 { xC0 = 0xC0 }
3459    ///
3460    /// // The only valid value of this type is the bytes `0xC0C0`.
3461    /// #[derive(TryFromBytes)]
3462    /// #[repr(C)]
3463    /// struct C0C0(C0, C0);
3464    ///
3465    /// #[derive(TryFromBytes)]
3466    /// #[repr(C)]
3467    /// struct Packet {
3468    ///     magic_number: C0C0,
3469    ///     mug_size: u8,
3470    ///     temperature: u8,
3471    /// }
3472    ///
3473    /// // These are more bytes than are needed to encode a `Packet`.
3474    /// let bytes = &[0, 1, 2, 3, 4, 5, 0xC0, 0xC0, 240, 77][..];
3475    ///
3476    /// let (prefix, packet) = Packet::try_read_from_suffix(bytes).unwrap();
3477    ///
3478    /// assert_eq!(packet.mug_size, 240);
3479    /// assert_eq!(packet.temperature, 77);
3480    /// assert_eq!(prefix, &[0u8, 1, 2, 3, 4, 5][..]);
3481    ///
3482    /// // These bytes are not valid instance of `Packet`.
3483    /// let bytes = &[0, 1, 2, 3, 4, 5, 0x10, 0xC0, 240, 77][..];
3484    /// assert!(Packet::try_read_from_suffix(bytes).is_err());
3485    /// ```
3486    ///
3487    /// # Performance Considerations
3488    ///
3489    /// In this version of zerocopy, this method reads the `source` into a
3490    /// well-aligned stack allocation and *then* validates that the allocation
3491    /// is a valid `Self`. This ensures that validation can be performed using
3492    /// aligned reads (which carry a performance advantage over unaligned reads
3493    /// on many platforms) at the cost of an unconditional copy.
3494    ///
3495    #[doc = codegen_section!(
3496        header = "h5",
3497        bench = "try_read_from_suffix",
3498        format = "coco_static_size",
3499    )]
3500    #[must_use = "the conversion result must be checked"]
3501    #[cfg_attr(zerocopy_inline_always, inline(always))]
3502    #[cfg_attr(not(zerocopy_inline_always), inline)]
3503    fn try_read_from_suffix(source: &[u8]) -> Result<(&[u8], Self), TryReadError<&[u8], Self>>
3504    where
3505        Self: Sized,
3506    {
3507        let split_at = match source.len().checked_sub(mem::size_of::<Self>()) {
3508            Some(split_at) => split_at,
3509            None => return Err(SizeError::new(source).into()),
3510        };
3511        // SAFETY: `checked_sub` returned the difference without overflow [1],
3512        // so `split_at = source.len() - size_of::<Self>() <= source.len()`.
3513        // This satisfies `SplitAt::split_at_unchecked`'s precondition.
3514        //
3515        // [1] Per https://doc.rust-lang.org/1.56.0/std/primitive.usize.html#method.checked_sub:
3516        //
3517        //   Checked integer subtraction. Computes `self - rhs`, returning
3518        //   `None` if overflow occurred.
3519        let (prefix, suffix) =
3520            unsafe { SplitAt::split_at_unchecked(source, split_at) }.via_immutable();
3521        match try_read_from(suffix) {
3522            Ok(slf) => Ok((prefix, slf)),
3523            Err(e) => Err(e.map_src(
3524                #[inline(always)]
3525                |_| source,
3526            )),
3527        }
3528    }
3529}
3530
3531/// Validates and interprets the given affix of `source`'s bytes as a `&T`.
3532///
3533/// Returns the destination reference and excess bytes on success. All errors,
3534/// including validity errors, contain the original `&S`.
3535#[inline(always)]
3536fn try_ref_from_prefix_suffix<S, T>(
3537    source: &S,
3538    cast_type: CastType,
3539    meta: Option<T::PointerMetadata>,
3540) -> Result<(&T, &[u8]), TryCastError<&S, T>>
3541where
3542    S: IntoBytes + Immutable + ?Sized,
3543    T: TryFromBytes + KnownLayout + Immutable + ?Sized,
3544{
3545    match Ptr::from_ref(source.as_bytes()).try_cast_into::<T, BecauseImmutable>(cast_type, meta) {
3546        Ok((candidate, prefix_suffix)) => {
3547            // This call may panic. If that happens, it doesn't cause any soundness
3548            // issues, as we have not generated any invalid state which we need to
3549            // fix before returning.
3550            match candidate.try_into_safe() {
3551                Ok(valid) => Ok((valid.as_ref(), prefix_suffix.as_ref())),
3552                Err(e) => Err(e
3553                    .map_src(
3554                        #[inline(always)]
3555                        |_| source,
3556                    )
3557                    .into()),
3558            }
3559        }
3560        Err(e) => Err(e
3561            .map_src(
3562                #[inline(always)]
3563                |_| source,
3564            )
3565            .into()),
3566    }
3567}
3568
3569#[inline(always)]
3570fn try_mut_from_prefix_suffix<T: IntoBytes + TryFromBytes + KnownLayout + ?Sized>(
3571    candidate: &mut [u8],
3572    cast_type: CastType,
3573    meta: Option<T::PointerMetadata>,
3574) -> Result<(&mut T, &mut [u8]), TryCastError<&mut [u8], T>> {
3575    match Ptr::from_mut(candidate).try_cast_into::<T, BecauseExclusive>(cast_type, meta) {
3576        Ok((candidate, prefix_suffix)) => {
3577            // This call may panic. If that happens, it doesn't cause any soundness
3578            // issues, as we have not generated any invalid state which we need to
3579            // fix before returning.
3580            match candidate.try_into_safe() {
3581                Ok(valid) => Ok((valid.as_mut(), prefix_suffix.as_mut())),
3582                Err(e) => Err(e.map_src(|src| src.as_bytes().as_mut()).into()),
3583            }
3584        }
3585        Err(e) => Err(e.map_src(Ptr::as_mut).into()),
3586    }
3587}
3588
3589#[inline(always)]
3590fn swap<T, U>((t, u): (T, U)) -> (U, T) {
3591    (u, t)
3592}
3593
3594#[inline(always)]
3595fn try_read_from<S, T>(source: &S) -> Result<T, TryReadError<&S, T>>
3596where
3597    S: IntoBytes + Immutable + ?Sized,
3598    T: TryFromBytes,
3599{
3600    let bytes = source.as_bytes();
3601
3602    if bytes.len() != mem::size_of::<T>() {
3603        return Err(SizeError::new(source).into());
3604    }
3605
3606    // FIXME(#2981): Avoid the validation copy when validation can safely use
3607    // a pointer derived from `source`'s shared borrow.
3608
3609    // Initialize the candidate in its final location. A typed move of a
3610    // `MaybeUninit<T>` may discard initialized bytes at `T`'s padding offsets
3611    // [1], but validation requires every byte to be initialized. Do not move
3612    // `candidate` between this copy and validation.
3613    //
3614    // [1] Per https://doc.rust-lang.org/1.93.1/std/mem/union.MaybeUninit.html#validity:
3615    //
3616    //   Moving or copying a value of type `MaybeUninit<T>` (i.e., performing a
3617    //   "typed copy") will exactly preserve the contents, including the
3618    //   provenance, of all non-padding bytes of type `T` in the value's
3619    //   representation.
3620    let mut candidate = CoreMaybeUninit::<T>::uninit();
3621
3622    // SAFETY: The earlier `if bytes.len() != mem::size_of::<T>()` returns on a
3623    // size mismatch, so reaching this copy implies that `bytes.len()` equals
3624    // `mem::size_of::<T>()`. Copying that many `u8`s cannot overrun `bytes`.
3625    // `candidate.as_mut_ptr()` is writable for the same number of bytes because
3626    // `MaybeUninit<T>` has `T`'s size. Both pointers are non-null and aligned
3627    // for `u8`, including when `T` is zero-sized. The fresh local allocation
3628    // cannot overlap `source`, which is an argument. Thus the read, write,
3629    // alignment, and non-overlap requirements of [2] hold. Copying `u8`s
3630    // initializes every destination byte, including those at `T`'s padding
3631    // offsets.
3632    //
3633    // These writes cannot violate `candidate`'s bit validity because every bit
3634    // pattern is valid for `MaybeUninit<T>` [3], even if it is invalid for `T`.
3635    //
3636    // [2] Per https://doc.rust-lang.org/1.56.0/std/ptr/fn.copy_nonoverlapping.html:
3637    //
3638    //   Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
3639    //   and destination must *not* overlap.
3640    //
3641    // [3] Per https://doc.rust-lang.org/1.56.0/std/mem/union.MaybeUninit.html#layout:
3642    //
3643    //   ... any bit value is valid for a `MaybeUninit<T>` ...
3644    unsafe {
3645        ptr::copy_nonoverlapping(
3646            bytes.as_ptr(),
3647            candidate.as_mut_ptr().cast::<u8>(),
3648            mem::size_of::<T>(),
3649        );
3650    }
3651
3652    // We use `from_mut` despite not mutating via `c_ptr` so that we don't need
3653    // to add a `T: Immutable` bound.
3654    let c_ptr = Ptr::from_mut(&mut candidate);
3655
3656    // SAFETY: `c_ptr` has no uninitialized sub-ranges because it derived from
3657    // `candidate`, whose bytes were all initialized by the copy above and which
3658    // has not been moved since. Since `candidate` is a `MaybeUninit`, it has no
3659    // validity requirements, and so no values written to an `Initialized`
3660    // `c_ptr` can violate its validity. Since `c_ptr` has `Exclusive` aliasing,
3661    // no mutations may happen except via `c_ptr` so long as it is live, so we
3662    // don't need to worry about the fact that `c_ptr` may have more restricted
3663    // validity than `candidate`.
3664    let c_ptr = unsafe { c_ptr.assume_validity::<invariant::Initialized>() };
3665
3666    let c_ptr = c_ptr.cast::<_, crate::pointer::cast::CastSized, _>();
3667
3668    // SAFETY: `c_ptr` originated from a reference to `candidate`, so its
3669    // address is aligned for `MaybeUninit<T>`, which has `T`'s alignment [1].
3670    // `CastSized` preserves that address. `ReadOnly<T>` is `repr(transparent)`
3671    // with a single `T` field, so it also has `T`'s alignment [2], including
3672    // when `T` is zero-sized.
3673    //
3674    // [1] Per https://doc.rust-lang.org/1.56.0/std/mem/union.MaybeUninit.html#layout:
3675    //
3676    //   `MaybeUninit<T>` is guaranteed to have the same size, alignment, and
3677    //   ABI as `T`:
3678    //
3679    // [2] Per https://doc.rust-lang.org/1.93.1/reference/type-layout.html#the-transparent-representation:
3680    //
3681    //   ... same layout and ABI as the only non-size 0 non-alignment 1 field,
3682    //   if present, or unit otherwise.
3683    let mut c_ptr = unsafe { c_ptr.assume_alignment::<invariant::Aligned>() };
3684
3685    // This call may panic. If that happens, it doesn't cause any soundness
3686    // issues, as we have not generated any invalid state which we need to fix
3687    // before returning.
3688    if !T::is_safe(c_ptr.reborrow_shared()) {
3689        return Err(ValidityError::new(source).into());
3690    }
3691
3692    // SAFETY: `T::is_safe` returned true for `candidate`'s initialized bytes,
3693    // so it contains a valid `T`, as required by [1]. Validation used a shared
3694    // `ReadOnly<T>` pointer, and the bytes have not been modified since.
3695    //
3696    // [1] Per https://doc.rust-lang.org/1.56.0/std/mem/union.MaybeUninit.html#method.assume_init:
3697    //
3698    //   It is up to the caller to guarantee that the `MaybeUninit<T>` really is
3699    //   in an initialized state.
3700    Ok(unsafe { candidate.assume_init() })
3701}
3702
3703/// Types for which a sequence of `0` bytes is a valid instance.
3704///
3705/// Any memory region of the appropriate length which is guaranteed to contain
3706/// only zero bytes can be viewed as any `FromZeros` type with no runtime
3707/// overhead. This is useful whenever memory is known to be in a zeroed state,
3708/// such memory returned from some allocation routines.
3709///
3710/// # Warning: Padding bytes
3711///
3712/// Note that, when a value is moved or copied, only the non-padding bytes of
3713/// that value are guaranteed to be preserved. It is unsound to assume that
3714/// values written to padding bytes are preserved after a move or copy. For more
3715/// details, see the [`FromBytes` docs][frombytes-warning-padding-bytes].
3716///
3717/// [frombytes-warning-padding-bytes]: FromBytes#warning-padding-bytes
3718///
3719/// # Implementation
3720///
3721/// **Do not implement this trait yourself!** Instead, use
3722/// [`#[derive(FromZeros)]`][derive]; e.g.:
3723///
3724/// ```
3725/// # use zerocopy_derive::{FromZeros, Immutable};
3726/// #[derive(FromZeros)]
3727/// struct MyStruct {
3728/// # /*
3729///     ...
3730/// # */
3731/// }
3732///
3733/// #[derive(FromZeros)]
3734/// #[repr(u8)]
3735/// enum MyEnum {
3736/// #   Variant0,
3737/// # /*
3738///     ...
3739/// # */
3740/// }
3741///
3742/// #[derive(FromZeros, Immutable)]
3743/// union MyUnion {
3744/// #   variant: u8,
3745/// # /*
3746///     ...
3747/// # */
3748/// }
3749/// ```
3750///
3751/// This derive performs a sophisticated, compile-time safety analysis to
3752/// determine whether a type is `FromZeros`.
3753///
3754/// # Safety
3755///
3756/// *This section describes what is required in order for `T: FromZeros`, and
3757/// what unsafe code may assume of such types. If you don't plan on implementing
3758/// `FromZeros` manually, and you don't plan on writing unsafe code that
3759/// operates on `FromZeros` types, then you don't need to read this section.*
3760///
3761/// If `T: FromZeros`, then unsafe code may assume that it is sound to produce a
3762/// `T` whose bytes are all initialized to zero. If a type is marked as
3763/// `FromZeros` which violates this contract, it may cause undefined behavior.
3764///
3765/// `#[derive(FromZeros)]` only permits [types which satisfy these
3766/// requirements][derive-analysis].
3767///
3768#[cfg_attr(
3769    feature = "derive",
3770    doc = "[derive]: zerocopy_derive::FromZeros",
3771    doc = "[derive-analysis]: zerocopy_derive::FromZeros#analysis"
3772)]
3773#[cfg_attr(
3774    not(feature = "derive"),
3775    doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeros.html"),
3776    doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeros.html#analysis"),
3777)]
3778#[cfg_attr(
3779    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
3780    diagnostic::on_unimplemented(note = "Consider adding `#[derive(FromZeros)]` to `{Self}`")
3781)]
3782pub unsafe trait FromZeros: TryFromBytes {
3783    // The `Self: Sized` bound makes it so that `FromZeros` is still object
3784    // safe.
3785    #[doc(hidden)]
3786    fn only_derive_is_allowed_to_implement_this_trait()
3787    where
3788        Self: Sized;
3789
3790    /// Overwrites `self` with zeros.
3791    ///
3792    /// Sets every byte in `self` to 0. While this is similar to doing `*self =
3793    /// Self::new_zeroed()`, it differs in that `zero` does not semantically
3794    /// drop the current value and replace it with a new one — it simply
3795    /// modifies the bytes of the existing value.
3796    ///
3797    /// # Examples
3798    ///
3799    /// ```
3800    /// # use zerocopy::FromZeros;
3801    /// # use zerocopy_derive::*;
3802    /// #
3803    /// #[derive(FromZeros)]
3804    /// #[repr(C)]
3805    /// struct PacketHeader {
3806    ///     src_port: [u8; 2],
3807    ///     dst_port: [u8; 2],
3808    ///     length: [u8; 2],
3809    ///     checksum: [u8; 2],
3810    /// }
3811    ///
3812    /// let mut header = PacketHeader {
3813    ///     src_port: 100u16.to_be_bytes(),
3814    ///     dst_port: 200u16.to_be_bytes(),
3815    ///     length: 300u16.to_be_bytes(),
3816    ///     checksum: 400u16.to_be_bytes(),
3817    /// };
3818    ///
3819    /// header.zero();
3820    ///
3821    /// assert_eq!(header.src_port, [0, 0]);
3822    /// assert_eq!(header.dst_port, [0, 0]);
3823    /// assert_eq!(header.length, [0, 0]);
3824    /// assert_eq!(header.checksum, [0, 0]);
3825    /// ```
3826    ///
3827    #[doc = codegen_section!(
3828        header = "h5",
3829        bench = "zero",
3830        format = "coco",
3831        arity = 3,
3832        [
3833            open
3834            @index 1
3835            @title "Sized"
3836            @variant "static_size"
3837        ],
3838        [
3839            @index 2
3840            @title "Unsized"
3841            @variant "dynamic_size"
3842        ],
3843        [
3844            @index 3
3845            @title "Dynamically Padded"
3846            @variant "dynamic_padding"
3847        ]
3848    )]
3849    #[inline(always)]
3850    fn zero(&mut self) {
3851        let slf: *mut Self = self;
3852        let len = mem::size_of_val(self);
3853        // SAFETY:
3854        // - `self` is guaranteed by the type system to be valid for writes of
3855        //   size `size_of_val(self)`.
3856        // - `u8`'s alignment is 1, and thus `self` is guaranteed to be aligned
3857        //   as required by `u8`.
3858        // - Since `Self: FromZeros`, the all-zeros instance is a valid instance
3859        //   of `Self.`
3860        //
3861        // FIXME(#429): Add references to docs and quotes.
3862        unsafe { ptr::write_bytes(slf.cast::<u8>(), 0, len) };
3863    }
3864
3865    /// Creates an instance of `Self` from zeroed bytes.
3866    ///
3867    /// # Examples
3868    ///
3869    /// ```
3870    /// # use zerocopy::FromZeros;
3871    /// # use zerocopy_derive::*;
3872    /// #
3873    /// #[derive(FromZeros)]
3874    /// #[repr(C)]
3875    /// struct PacketHeader {
3876    ///     src_port: [u8; 2],
3877    ///     dst_port: [u8; 2],
3878    ///     length: [u8; 2],
3879    ///     checksum: [u8; 2],
3880    /// }
3881    ///
3882    /// let header: PacketHeader = FromZeros::new_zeroed();
3883    ///
3884    /// assert_eq!(header.src_port, [0, 0]);
3885    /// assert_eq!(header.dst_port, [0, 0]);
3886    /// assert_eq!(header.length, [0, 0]);
3887    /// assert_eq!(header.checksum, [0, 0]);
3888    /// ```
3889    ///
3890    #[doc = codegen_section!(
3891        header = "h5",
3892        bench = "new_zeroed",
3893        format = "coco_static_size",
3894    )]
3895    #[must_use = "has no side effects"]
3896    #[inline(always)]
3897    fn new_zeroed() -> Self
3898    where
3899        Self: Sized,
3900    {
3901        // SAFETY: `FromZeros` says that the all-zeros bit pattern is legal.
3902        unsafe { mem::zeroed() }
3903    }
3904
3905    /// Creates a `Box<Self>` from zeroed bytes.
3906    ///
3907    /// This function is useful for allocating large values on the heap and
3908    /// zero-initializing them, without ever creating a temporary instance of
3909    /// `Self` on the stack. For example, `<[u8; 1048576]>::new_box_zeroed()`
3910    /// will allocate `[u8; 1048576]` directly on the heap; it does not require
3911    /// storing `[u8; 1048576]` in a temporary variable on the stack.
3912    ///
3913    /// On systems that use a heap implementation that supports allocating from
3914    /// pre-zeroed memory, using `new_box_zeroed` (or related functions) may
3915    /// have performance benefits.
3916    ///
3917    /// # Errors
3918    ///
3919    /// Returns an error on allocation failure. Allocation failure is guaranteed
3920    /// never to cause a panic or an abort.
3921    ///
3922    #[doc = codegen_section!(
3923        header = "h5",
3924        bench = "new_box_zeroed",
3925        format = "coco_static_size",
3926    )]
3927    #[must_use = "has no side effects (other than allocation)"]
3928    #[cfg(any(feature = "alloc", test))]
3929    #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
3930    #[inline]
3931    fn new_box_zeroed() -> Result<Box<Self>, AllocError>
3932    where
3933        Self: Sized,
3934    {
3935        // SAFETY: `BoxAllocator::allocate_zeroed` is a valid argument of
3936        // `new_box`. The referent of the pointer returned by `allocate_zeroed`
3937        // (and, consequently, the `Box` derived from it) is a valid instance of
3938        // `Wrapping<Self>`, because `Self` (and thus `Wrapping<Self>`) is
3939        // `FromZeros`.
3940        unsafe {
3941            crate::util::new_box::<Wrapping<Self>, _>(
3942                (),
3943                crate::util::UnwrapWrapping(crate::util::GlobalAlloc),
3944                crate::util::BoxAllocator::<Wrapping<Self>>::allocate_zeroed,
3945            )
3946        }
3947    }
3948
3949    /// Creates a `Box<Self, A>` in `alloc` from zeroed bytes.
3950    ///
3951    /// This function is useful for allocating large values on the heap using a
3952    /// custom allocator and zero-initializing them, without ever creating a
3953    /// temporary instance of `Self` on the stack. For example,
3954    /// `<[u8; 1048576]>::new_box_zeroed_in(alloc)` will allocate
3955    /// `[u8; 1048576]` directly in `alloc`; it does not require storing
3956    /// `[u8; 1048576]` in a temporary variable on the stack.
3957    ///
3958    /// On systems that use a heap implementation that supports allocating from
3959    /// pre-zeroed memory, using `new_box_zeroed_in` (or related functions) may
3960    /// have performance benefits.
3961    ///
3962    /// # Errors
3963    ///
3964    /// Returns an error on allocation failure.
3965    #[must_use = "has no side effects (other than allocation)"]
3966    #[cfg(all(not(no_zerocopy_allocator_api_1_100_0), feature = "alloc"))]
3967    #[cfg_attr(doc_cfg, doc(cfg(all(rust = "1.100.0", feature = "alloc"))))]
3968    #[inline]
3969    fn new_box_zeroed_in<A: Allocator>(alloc: A) -> Result<Box<Self, A>, AllocError>
3970    where
3971        Self: Sized,
3972    {
3973        // SAFETY: `BoxAllocator::allocate_zeroed` is a valid argument of
3974        // `new_box`. The referent of the pointer returned by `allocate_zeroed`
3975        // (and, consequently, the `Box` derived from it) is a valid instance of
3976        // `Wrapping<Self>`, because `Self` (and thus `Wrapping<Self>`) is
3977        // `FromZeros`.
3978        unsafe {
3979            crate::util::new_box::<Wrapping<Self>, _>(
3980                (),
3981                crate::util::UnwrapWrapping(alloc),
3982                crate::util::BoxAllocator::<Wrapping<Self>>::allocate_zeroed,
3983            )
3984        }
3985    }
3986
3987    /// Creates a `Box<Self>` from zeroed bytes with `count` trailing elements.
3988    ///
3989    /// `Self` may be a slice or a [slice DST]. `count` specifies the number of
3990    /// elements in the trailing slice.
3991    ///
3992    /// This function is useful for allocating large values of `Self` on the
3993    /// heap and zero-initializing them, without ever creating a temporary
3994    /// instance on the stack. For example,
3995    /// `<[u8]>::new_box_zeroed_with_elems(1048576)` will allocate the slice
3996    /// directly on the heap; it does not require storing the slice on the
3997    /// stack.
3998    ///
3999    /// On systems that use a heap implementation that supports allocating from
4000    /// pre-zeroed memory, using `new_box_zeroed_with_elems` may have
4001    /// performance benefits.
4002    ///
4003    /// If the trailing slice element type is zero-sized, the returned box still
4004    /// has `count` trailing elements.
4005    ///
4006    /// [slice DST]: KnownLayout#dynamically-sized-types
4007    ///
4008    /// # Errors
4009    ///
4010    /// Returns an error on allocation failure. Allocation failure is
4011    /// guaranteed never to cause a panic or an abort.
4012    ///
4013    #[doc = codegen_section!(
4014        header = "h5",
4015        bench = "new_box_zeroed_with_elems",
4016        format = "coco",
4017        arity = 2,
4018        [
4019            open
4020            @index 1
4021            @title "Unsized"
4022            @variant "dynamic_size"
4023        ],
4024        [
4025            @index 2
4026            @title "Dynamically Padded"
4027            @variant "dynamic_padding"
4028        ]
4029    )]
4030    #[must_use = "has no side effects (other than allocation)"]
4031    #[cfg(feature = "alloc")]
4032    #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
4033    #[inline]
4034    fn new_box_zeroed_with_elems(count: usize) -> Result<Box<Self>, AllocError>
4035    where
4036        Self: KnownLayout<PointerMetadata = usize>,
4037    {
4038        // SAFETY: `BoxAllocator::allocate_zeroed` is a valid argument of
4039        // `new_box`. The referent of the pointer returned by `allocate_zeroed`
4040        // (and, consequently, the `Box` derived from it) is a valid instance of
4041        // `Self`, because `Self` is `FromZeros`.
4042        unsafe {
4043            crate::util::new_box(
4044                count,
4045                crate::util::GlobalAlloc,
4046                crate::util::BoxAllocator::<Self>::allocate_zeroed,
4047            )
4048        }
4049    }
4050
4051    #[deprecated(since = "0.8.0", note = "renamed to `FromZeros::new_box_zeroed_with_elems`")]
4052    #[doc(hidden)]
4053    #[cfg(feature = "alloc")]
4054    #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
4055    #[must_use = "has no side effects (other than allocation)"]
4056    #[inline(always)]
4057    fn new_box_slice_zeroed(len: usize) -> Result<Box<[Self]>, AllocError>
4058    where
4059        Self: Sized,
4060    {
4061        <[Self]>::new_box_zeroed_with_elems(len)
4062    }
4063
4064    /// Creates a `Vec<Self>` from zeroed bytes.
4065    ///
4066    /// This function is useful for allocating large values of `Vec`s and
4067    /// zero-initializing them, without ever creating a temporary instance of
4068    /// `[Self; _]` (or many temporary instances of `Self`) on the stack. For
4069    /// example, `u8::new_vec_zeroed(1048576)` will allocate directly on the
4070    /// heap; it does not require storing intermediate values on the stack.
4071    ///
4072    /// On systems that use a heap implementation that supports allocating from
4073    /// pre-zeroed memory, using `new_vec_zeroed` may have performance benefits.
4074    ///
4075    /// If `Self` is a zero-sized type, then this function will return a
4076    /// `Vec<Self>` that has the correct `len`. Such a `Vec` cannot contain any
4077    /// actual information, but its `len()` property will report the correct
4078    /// value.
4079    ///
4080    /// # Errors
4081    ///
4082    /// Returns an error on allocation failure. Allocation failure is
4083    /// guaranteed never to cause a panic or an abort.
4084    ///
4085    #[doc = codegen_section!(
4086        header = "h5",
4087        bench = "new_vec_zeroed",
4088        format = "coco_static_size",
4089    )]
4090    #[must_use = "has no side effects (other than allocation)"]
4091    #[cfg(feature = "alloc")]
4092    #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
4093    #[inline(always)]
4094    fn new_vec_zeroed(len: usize) -> Result<Vec<Self>, AllocError>
4095    where
4096        Self: Sized,
4097    {
4098        <[Self]>::new_box_zeroed_with_elems(len).map(Into::into)
4099    }
4100
4101    /// Extends a `Vec<Self>` by pushing `additional` new items onto the end of
4102    /// the vector. The new items are initialized with zeros.
4103    ///
4104    #[doc = codegen_section!(
4105        header = "h5",
4106        bench = "extend_vec_zeroed",
4107        format = "coco_static_size",
4108    )]
4109    #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
4110    #[cfg(feature = "alloc")]
4111    #[cfg_attr(doc_cfg, doc(cfg(all(rust = "1.57.0", feature = "alloc"))))]
4112    #[inline(always)]
4113    fn extend_vec_zeroed(v: &mut Vec<Self>, additional: usize) -> Result<(), AllocError>
4114    where
4115        Self: Sized,
4116    {
4117        // PANICS: We pass `v.len()` for `position`, so the `position > v.len()`
4118        // panic condition is not satisfied.
4119        <Self as FromZeros>::insert_vec_zeroed(v, v.len(), additional)
4120    }
4121
4122    /// Inserts `additional` new items into `Vec<Self>` at `position`. The new
4123    /// items are initialized with zeros.
4124    ///
4125    /// # Panics
4126    ///
4127    /// Panics if `position > v.len()`.
4128    ///
4129    #[doc = codegen_section!(
4130        header = "h5",
4131        bench = "insert_vec_zeroed",
4132        format = "coco_static_size",
4133    )]
4134    #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
4135    #[cfg(feature = "alloc")]
4136    #[cfg_attr(doc_cfg, doc(cfg(all(rust = "1.57.0", feature = "alloc"))))]
4137    #[inline]
4138    fn insert_vec_zeroed(
4139        v: &mut Vec<Self>,
4140        position: usize,
4141        additional: usize,
4142    ) -> Result<(), AllocError>
4143    where
4144        Self: Sized,
4145    {
4146        assert!(position <= v.len());
4147        // We only conditionally compile on versions on which `try_reserve` is
4148        // stable; the Clippy lint is a false positive.
4149        v.try_reserve(additional).map_err(|_| AllocError)?;
4150        // SAFETY: The `try_reserve` call guarantees that these cannot overflow:
4151        // * `ptr.add(position)`
4152        // * `position + additional`
4153        // * `v.len() + additional`
4154        //
4155        // `v.len() - position` cannot overflow because we asserted that
4156        // `position <= v.len()`.
4157        #[allow(clippy::multiple_unsafe_ops_per_block)]
4158        unsafe {
4159            // This is a potentially overlapping copy.
4160            let ptr = v.as_mut_ptr();
4161            #[allow(clippy::arithmetic_side_effects)]
4162            ptr.add(position).copy_to(ptr.add(position + additional), v.len() - position);
4163            ptr.add(position).write_bytes(0, additional);
4164            #[allow(clippy::arithmetic_side_effects)]
4165            v.set_len(v.len() + additional);
4166        }
4167
4168        Ok(())
4169    }
4170}
4171
4172/// Analyzes whether a type is [`FromBytes`].
4173///
4174/// This derive analyzes, at compile time, whether the annotated type satisfies
4175/// the [safety conditions] of `FromBytes` and implements `FromBytes` and its
4176/// supertraits if it is sound to do so. This derive can be applied to structs,
4177/// enums, and unions;
4178/// e.g.:
4179///
4180/// ```
4181/// # use zerocopy_derive::{FromBytes, FromZeros, Immutable};
4182/// #[derive(FromBytes)]
4183/// struct MyStruct {
4184/// # /*
4185///     ...
4186/// # */
4187/// }
4188///
4189/// #[derive(FromBytes)]
4190/// #[repr(u8)]
4191/// enum MyEnum {
4192/// #   V00, V01, V02, V03, V04, V05, V06, V07, V08, V09, V0A, V0B, V0C, V0D, V0E,
4193/// #   V0F, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V1A, V1B, V1C, V1D,
4194/// #   V1E, V1F, V20, V21, V22, V23, V24, V25, V26, V27, V28, V29, V2A, V2B, V2C,
4195/// #   V2D, V2E, V2F, V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, V3A, V3B,
4196/// #   V3C, V3D, V3E, V3F, V40, V41, V42, V43, V44, V45, V46, V47, V48, V49, V4A,
4197/// #   V4B, V4C, V4D, V4E, V4F, V50, V51, V52, V53, V54, V55, V56, V57, V58, V59,
4198/// #   V5A, V5B, V5C, V5D, V5E, V5F, V60, V61, V62, V63, V64, V65, V66, V67, V68,
4199/// #   V69, V6A, V6B, V6C, V6D, V6E, V6F, V70, V71, V72, V73, V74, V75, V76, V77,
4200/// #   V78, V79, V7A, V7B, V7C, V7D, V7E, V7F, V80, V81, V82, V83, V84, V85, V86,
4201/// #   V87, V88, V89, V8A, V8B, V8C, V8D, V8E, V8F, V90, V91, V92, V93, V94, V95,
4202/// #   V96, V97, V98, V99, V9A, V9B, V9C, V9D, V9E, V9F, VA0, VA1, VA2, VA3, VA4,
4203/// #   VA5, VA6, VA7, VA8, VA9, VAA, VAB, VAC, VAD, VAE, VAF, VB0, VB1, VB2, VB3,
4204/// #   VB4, VB5, VB6, VB7, VB8, VB9, VBA, VBB, VBC, VBD, VBE, VBF, VC0, VC1, VC2,
4205/// #   VC3, VC4, VC5, VC6, VC7, VC8, VC9, VCA, VCB, VCC, VCD, VCE, VCF, VD0, VD1,
4206/// #   VD2, VD3, VD4, VD5, VD6, VD7, VD8, VD9, VDA, VDB, VDC, VDD, VDE, VDF, VE0,
4207/// #   VE1, VE2, VE3, VE4, VE5, VE6, VE7, VE8, VE9, VEA, VEB, VEC, VED, VEE, VEF,
4208/// #   VF0, VF1, VF2, VF3, VF4, VF5, VF6, VF7, VF8, VF9, VFA, VFB, VFC, VFD, VFE,
4209/// #   VFF,
4210/// # /*
4211///     ...
4212/// # */
4213/// }
4214///
4215/// #[derive(FromBytes, Immutable)]
4216/// union MyUnion {
4217/// #   variant: u8,
4218/// # /*
4219///     ...
4220/// # */
4221/// }
4222/// ```
4223///
4224/// [safety conditions]: trait@FromBytes#safety
4225///
4226/// # Analysis
4227///
4228/// *This section describes, roughly, the analysis performed by this derive to
4229/// determine whether it is sound to implement `FromBytes` for a given type.
4230/// Unless you are modifying the implementation of this derive, or attempting to
4231/// manually implement `FromBytes` for a type yourself, you don't need to read
4232/// this section.*
4233///
4234/// If a type has the following properties, then this derive can implement
4235/// `FromBytes` for that type:
4236///
4237/// - If the type is a struct, all of its fields must be `FromBytes`.
4238/// - If the type is an enum:
4239///   - It must have a defined representation which is one of `u8`, `u16`, `i8`,
4240///     or `i16`.
4241///   - The maximum number of discriminants must be used (so that every possible
4242///     bit pattern is a valid one).
4243///   - Its fields must be `FromBytes`.
4244///
4245/// This analysis is subject to change. Unsafe code may *only* rely on the
4246/// documented [safety conditions] of `FromBytes`, and must *not* rely on the
4247/// implementation details of this derive.
4248///
4249/// ## Why isn't an explicit representation required for structs?
4250///
4251/// Neither this derive, nor the [safety conditions] of `FromBytes`, requires
4252/// that structs are marked with `#[repr(C)]`.
4253///
4254/// Per the [Rust reference][the Rust reference],
4255///
4256/// > The representation of a type can change the padding between fields, but
4257/// > does not change the layout of the fields themselves.
4258///
4259/// [the Rust reference]: https://doc.rust-lang.org/reference/type-layout.html#representations
4260///
4261/// Since the layout of structs only consists of padding bytes and field bytes,
4262/// a struct is soundly `FromBytes` if:
4263/// 1. its padding is soundly `FromBytes`, and
4264/// 2. its fields are soundly `FromBytes`.
4265///
4266/// The answer to the first question is always yes: padding bytes do not have
4267/// any validity constraints. A [discussion] of this question in the Unsafe Code
4268/// Guidelines Working Group concluded that it would be virtually unimaginable
4269/// for future versions of rustc to add validity constraints to padding bytes.
4270///
4271/// [discussion]: https://github.com/rust-lang/unsafe-code-guidelines/issues/174
4272///
4273/// Whether a struct is soundly `FromBytes` therefore solely depends on whether
4274/// its fields are `FromBytes`.
4275#[cfg(any(feature = "derive", test))]
4276#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
4277pub use zerocopy_derive::FromBytes;
4278
4279/// Types for which any bit pattern is valid.
4280///
4281/// Any memory region of the appropriate length which contains initialized bytes
4282/// can be viewed as any `FromBytes` type with no runtime overhead. This is
4283/// useful for efficiently parsing bytes as structured data.
4284///
4285/// # Warning: Padding bytes
4286///
4287/// Note that, when a value is moved or copied, only the non-padding bytes of
4288/// that value are guaranteed to be preserved. It is unsound to assume that
4289/// values written to padding bytes are preserved after a move or copy. For
4290/// example, the following is unsound:
4291///
4292/// ```rust,no_run
4293/// use core::mem::{size_of, transmute};
4294/// use zerocopy::FromZeros;
4295/// # use zerocopy_derive::*;
4296///
4297/// // Assume `Foo` is a type with padding bytes.
4298/// #[derive(FromZeros, Default)]
4299/// struct Foo {
4300/// # /*
4301///     ...
4302/// # */
4303/// }
4304///
4305/// let mut foo: Foo = Foo::default();
4306/// FromZeros::zero(&mut foo);
4307/// // UNSOUND: Although `FromZeros::zero` writes zeros to all bytes of `foo`,
4308/// // those writes are not guaranteed to be preserved in padding bytes when
4309/// // `foo` is moved, so this may expose padding bytes as `u8`s.
4310/// let foo_bytes: [u8; size_of::<Foo>()] = unsafe { transmute(foo) };
4311/// ```
4312///
4313/// # Implementation
4314///
4315/// **Do not implement this trait yourself!** Instead, use
4316/// [`#[derive(FromBytes)]`][derive]; e.g.:
4317///
4318/// ```
4319/// # use zerocopy_derive::{FromBytes, Immutable};
4320/// #[derive(FromBytes)]
4321/// struct MyStruct {
4322/// # /*
4323///     ...
4324/// # */
4325/// }
4326///
4327/// #[derive(FromBytes)]
4328/// #[repr(u8)]
4329/// enum MyEnum {
4330/// #   V00, V01, V02, V03, V04, V05, V06, V07, V08, V09, V0A, V0B, V0C, V0D, V0E,
4331/// #   V0F, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V1A, V1B, V1C, V1D,
4332/// #   V1E, V1F, V20, V21, V22, V23, V24, V25, V26, V27, V28, V29, V2A, V2B, V2C,
4333/// #   V2D, V2E, V2F, V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, V3A, V3B,
4334/// #   V3C, V3D, V3E, V3F, V40, V41, V42, V43, V44, V45, V46, V47, V48, V49, V4A,
4335/// #   V4B, V4C, V4D, V4E, V4F, V50, V51, V52, V53, V54, V55, V56, V57, V58, V59,
4336/// #   V5A, V5B, V5C, V5D, V5E, V5F, V60, V61, V62, V63, V64, V65, V66, V67, V68,
4337/// #   V69, V6A, V6B, V6C, V6D, V6E, V6F, V70, V71, V72, V73, V74, V75, V76, V77,
4338/// #   V78, V79, V7A, V7B, V7C, V7D, V7E, V7F, V80, V81, V82, V83, V84, V85, V86,
4339/// #   V87, V88, V89, V8A, V8B, V8C, V8D, V8E, V8F, V90, V91, V92, V93, V94, V95,
4340/// #   V96, V97, V98, V99, V9A, V9B, V9C, V9D, V9E, V9F, VA0, VA1, VA2, VA3, VA4,
4341/// #   VA5, VA6, VA7, VA8, VA9, VAA, VAB, VAC, VAD, VAE, VAF, VB0, VB1, VB2, VB3,
4342/// #   VB4, VB5, VB6, VB7, VB8, VB9, VBA, VBB, VBC, VBD, VBE, VBF, VC0, VC1, VC2,
4343/// #   VC3, VC4, VC5, VC6, VC7, VC8, VC9, VCA, VCB, VCC, VCD, VCE, VCF, VD0, VD1,
4344/// #   VD2, VD3, VD4, VD5, VD6, VD7, VD8, VD9, VDA, VDB, VDC, VDD, VDE, VDF, VE0,
4345/// #   VE1, VE2, VE3, VE4, VE5, VE6, VE7, VE8, VE9, VEA, VEB, VEC, VED, VEE, VEF,
4346/// #   VF0, VF1, VF2, VF3, VF4, VF5, VF6, VF7, VF8, VF9, VFA, VFB, VFC, VFD, VFE,
4347/// #   VFF,
4348/// # /*
4349///     ...
4350/// # */
4351/// }
4352///
4353/// #[derive(FromBytes, Immutable)]
4354/// union MyUnion {
4355/// #   variant: u8,
4356/// # /*
4357///     ...
4358/// # */
4359/// }
4360/// ```
4361///
4362/// This derive performs a sophisticated, compile-time safety analysis to
4363/// determine whether a type is `FromBytes`.
4364///
4365/// # Safety
4366///
4367/// *This section describes what is required in order for `T: FromBytes`, and
4368/// what unsafe code may assume of such types. If you don't plan on implementing
4369/// `FromBytes` manually, and you don't plan on writing unsafe code that
4370/// operates on `FromBytes` types, then you don't need to read this section.*
4371///
4372/// If `T: FromBytes`, then unsafe code may assume that it is sound to produce a
4373/// `T` whose bytes are initialized to any sequence of valid `u8`s (in other
4374/// words, any byte value which is not uninitialized). If a type is marked as
4375/// `FromBytes` which violates this contract, it may cause undefined behavior.
4376///
4377/// `#[derive(FromBytes)]` only permits [types which satisfy these
4378/// requirements][derive-analysis].
4379///
4380#[cfg_attr(
4381    feature = "derive",
4382    doc = "[derive]: zerocopy_derive::FromBytes",
4383    doc = "[derive-analysis]: zerocopy_derive::FromBytes#analysis"
4384)]
4385#[cfg_attr(
4386    not(feature = "derive"),
4387    doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromBytes.html"),
4388    doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromBytes.html#analysis"),
4389)]
4390#[cfg_attr(
4391    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
4392    diagnostic::on_unimplemented(note = "Consider adding `#[derive(FromBytes)]` to `{Self}`")
4393)]
4394pub unsafe trait FromBytes: FromZeros {
4395    // The `Self: Sized` bound makes it so that `FromBytes` is still object
4396    // safe.
4397    #[doc(hidden)]
4398    fn only_derive_is_allowed_to_implement_this_trait()
4399    where
4400        Self: Sized;
4401
4402    /// Interprets the given `source` as a `&Self`.
4403    ///
4404    /// This method attempts to return a reference to `source` interpreted as a
4405    /// `Self`. If the length of `source` is not a [valid size of
4406    /// `Self`][valid-size], or if `source` is not appropriately aligned, this
4407    /// returns `Err`. If [`Self: Unaligned`][self-unaligned], you can
4408    /// [infallibly discard the alignment error][size-error-from].
4409    ///
4410    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
4411    ///
4412    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
4413    /// [self-unaligned]: Unaligned
4414    /// [size-error-from]: error/struct.SizeError.html#method.from-1
4415    /// [slice-dst]: KnownLayout#dynamically-sized-types
4416    ///
4417    /// # Compile-Time Assertions
4418    ///
4419    /// This method cannot yet be used on unsized types whose dynamically-sized
4420    /// component is zero-sized. Attempting to use this method on such types
4421    /// results in a compile-time assertion error; e.g.:
4422    ///
4423    /// ```compile_fail,E0080
4424    /// use zerocopy::*;
4425    /// # use zerocopy_derive::*;
4426    ///
4427    /// #[derive(FromBytes, Immutable, KnownLayout)]
4428    /// #[repr(C)]
4429    /// struct ZSTy {
4430    ///     leading_sized: u16,
4431    ///     trailing_dst: [()],
4432    /// }
4433    ///
4434    /// let _ = ZSTy::ref_from_bytes(0u16.as_bytes()); // âš  Compile Error!
4435    /// ```
4436    ///
4437    /// # Examples
4438    ///
4439    /// ```
4440    /// use zerocopy::FromBytes;
4441    /// # use zerocopy_derive::*;
4442    ///
4443    /// #[derive(FromBytes, KnownLayout, Immutable)]
4444    /// #[repr(C)]
4445    /// struct PacketHeader {
4446    ///     src_port: [u8; 2],
4447    ///     dst_port: [u8; 2],
4448    ///     length: [u8; 2],
4449    ///     checksum: [u8; 2],
4450    /// }
4451    ///
4452    /// #[derive(FromBytes, KnownLayout, Immutable)]
4453    /// #[repr(C)]
4454    /// struct Packet {
4455    ///     header: PacketHeader,
4456    ///     body: [u8],
4457    /// }
4458    ///
4459    /// // These bytes encode a `Packet`.
4460    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11][..];
4461    ///
4462    /// let packet = Packet::ref_from_bytes(bytes).unwrap();
4463    ///
4464    /// assert_eq!(packet.header.src_port, [0, 1]);
4465    /// assert_eq!(packet.header.dst_port, [2, 3]);
4466    /// assert_eq!(packet.header.length, [4, 5]);
4467    /// assert_eq!(packet.header.checksum, [6, 7]);
4468    /// assert_eq!(packet.body, [8, 9, 10, 11]);
4469    /// ```
4470    ///
4471    #[doc = codegen_section!(
4472        header = "h5",
4473        bench = "ref_from_bytes",
4474        format = "coco",
4475        arity = 3,
4476        [
4477            open
4478            @index 1
4479            @title "Sized"
4480            @variant "static_size"
4481        ],
4482        [
4483            @index 2
4484            @title "Unsized"
4485            @variant "dynamic_size"
4486        ],
4487        [
4488            @index 3
4489            @title "Dynamically Padded"
4490            @variant "dynamic_padding"
4491        ]
4492    )]
4493    #[must_use = "has no side effects"]
4494    #[cfg_attr(zerocopy_inline_always, inline(always))]
4495    #[cfg_attr(not(zerocopy_inline_always), inline)]
4496    fn ref_from_bytes(source: &[u8]) -> Result<&Self, CastError<&[u8], Self>>
4497    where
4498        Self: KnownLayout + Immutable,
4499    {
4500        static_assert_dst_is_not_zst!(Self);
4501        match Ptr::from_ref(source).try_cast_into_no_leftover::<_, BecauseImmutable>(None) {
4502            Ok(ptr) => Ok(ptr.recall_validity().as_ref()),
4503            Err(err) => Err(err.map_src(|src| src.as_ref())),
4504        }
4505    }
4506
4507    /// Interprets the prefix of the given `source` as a `&Self` without
4508    /// copying.
4509    ///
4510    /// This method computes the [largest possible size of `Self`][valid-size]
4511    /// that can fit in the leading bytes of `source`, then attempts to return
4512    /// both a reference to those bytes interpreted as a `Self`, and a reference
4513    /// to the remaining bytes. If there are insufficient bytes, or if `source`
4514    /// is not appropriately aligned, this returns `Err`. If [`Self:
4515    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
4516    /// error][size-error-from].
4517    ///
4518    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
4519    ///
4520    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
4521    /// [self-unaligned]: Unaligned
4522    /// [size-error-from]: error/struct.SizeError.html#method.from-1
4523    /// [slice-dst]: KnownLayout#dynamically-sized-types
4524    ///
4525    /// # Compile-Time Assertions
4526    ///
4527    /// This method cannot yet be used on unsized types whose dynamically-sized
4528    /// component is zero-sized. See [`ref_from_prefix_with_elems`], which does
4529    /// support such types. Attempting to use this method on such types results
4530    /// in a compile-time assertion error; e.g.:
4531    ///
4532    /// ```compile_fail,E0080
4533    /// use zerocopy::*;
4534    /// # use zerocopy_derive::*;
4535    ///
4536    /// #[derive(FromBytes, Immutable, KnownLayout)]
4537    /// #[repr(C)]
4538    /// struct ZSTy {
4539    ///     leading_sized: u16,
4540    ///     trailing_dst: [()],
4541    /// }
4542    ///
4543    /// let _ = ZSTy::ref_from_prefix(0u16.as_bytes()); // âš  Compile Error!
4544    /// ```
4545    ///
4546    /// [`ref_from_prefix_with_elems`]: FromBytes::ref_from_prefix_with_elems
4547    ///
4548    /// # Examples
4549    ///
4550    /// ```
4551    /// use zerocopy::FromBytes;
4552    /// # use zerocopy_derive::*;
4553    ///
4554    /// #[derive(FromBytes, KnownLayout, Immutable)]
4555    /// #[repr(C)]
4556    /// struct PacketHeader {
4557    ///     src_port: [u8; 2],
4558    ///     dst_port: [u8; 2],
4559    ///     length: [u8; 2],
4560    ///     checksum: [u8; 2],
4561    /// }
4562    ///
4563    /// #[derive(FromBytes, KnownLayout, Immutable)]
4564    /// #[repr(C)]
4565    /// struct Packet {
4566    ///     header: PacketHeader,
4567    ///     body: [[u8; 2]],
4568    /// }
4569    ///
4570    /// // These are more bytes than are needed to encode a `Packet`.
4571    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14][..];
4572    ///
4573    /// let (packet, suffix) = Packet::ref_from_prefix(bytes).unwrap();
4574    ///
4575    /// assert_eq!(packet.header.src_port, [0, 1]);
4576    /// assert_eq!(packet.header.dst_port, [2, 3]);
4577    /// assert_eq!(packet.header.length, [4, 5]);
4578    /// assert_eq!(packet.header.checksum, [6, 7]);
4579    /// assert_eq!(packet.body, [[8, 9], [10, 11], [12, 13]]);
4580    /// assert_eq!(suffix, &[14u8][..]);
4581    /// ```
4582    ///
4583    #[doc = codegen_section!(
4584        header = "h5",
4585        bench = "ref_from_prefix",
4586        format = "coco",
4587        arity = 3,
4588        [
4589            open
4590            @index 1
4591            @title "Sized"
4592            @variant "static_size"
4593        ],
4594        [
4595            @index 2
4596            @title "Unsized"
4597            @variant "dynamic_size"
4598        ],
4599        [
4600            @index 3
4601            @title "Dynamically Padded"
4602            @variant "dynamic_padding"
4603        ]
4604    )]
4605    #[must_use = "has no side effects"]
4606    #[cfg_attr(zerocopy_inline_always, inline(always))]
4607    #[cfg_attr(not(zerocopy_inline_always), inline)]
4608    fn ref_from_prefix(source: &[u8]) -> Result<(&Self, &[u8]), CastError<&[u8], Self>>
4609    where
4610        Self: KnownLayout + Immutable,
4611    {
4612        static_assert_dst_is_not_zst!(Self);
4613        ref_from_prefix_suffix(source, None, CastType::Prefix)
4614    }
4615
4616    /// Interprets the suffix of the given bytes as a `&Self`.
4617    ///
4618    /// This method computes the [largest possible size of `Self`][valid-size]
4619    /// that can fit in the trailing bytes of `source`, then attempts to return
4620    /// both a reference to those bytes interpreted as a `Self`, and a reference
4621    /// to the preceding bytes. If there are insufficient bytes, or if that
4622    /// suffix of `source` is not appropriately aligned, this returns `Err`. If
4623    /// [`Self: Unaligned`][self-unaligned], you can [infallibly discard the
4624    /// alignment error][size-error-from].
4625    ///
4626    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
4627    ///
4628    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
4629    /// [self-unaligned]: Unaligned
4630    /// [size-error-from]: error/struct.SizeError.html#method.from-1
4631    /// [slice-dst]: KnownLayout#dynamically-sized-types
4632    ///
4633    /// # Compile-Time Assertions
4634    ///
4635    /// This method cannot yet be used on unsized types whose dynamically-sized
4636    /// component is zero-sized. See [`ref_from_suffix_with_elems`], which does
4637    /// support such types. Attempting to use this method on such types results
4638    /// in a compile-time assertion error; e.g.:
4639    ///
4640    /// ```compile_fail,E0080
4641    /// use zerocopy::*;
4642    /// # use zerocopy_derive::*;
4643    ///
4644    /// #[derive(FromBytes, Immutable, KnownLayout)]
4645    /// #[repr(C)]
4646    /// struct ZSTy {
4647    ///     leading_sized: u16,
4648    ///     trailing_dst: [()],
4649    /// }
4650    ///
4651    /// let _ = ZSTy::ref_from_suffix(0u16.as_bytes()); // âš  Compile Error!
4652    /// ```
4653    ///
4654    /// [`ref_from_suffix_with_elems`]: FromBytes::ref_from_suffix_with_elems
4655    ///
4656    /// # Examples
4657    ///
4658    /// ```
4659    /// use zerocopy::FromBytes;
4660    /// # use zerocopy_derive::*;
4661    ///
4662    /// #[derive(FromBytes, Immutable, KnownLayout)]
4663    /// #[repr(C)]
4664    /// struct PacketTrailer {
4665    ///     frame_check_sequence: [u8; 4],
4666    /// }
4667    ///
4668    /// // These are more bytes than are needed to encode a `PacketTrailer`.
4669    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
4670    ///
4671    /// let (prefix, trailer) = PacketTrailer::ref_from_suffix(bytes).unwrap();
4672    ///
4673    /// assert_eq!(prefix, &[0, 1, 2, 3, 4, 5][..]);
4674    /// assert_eq!(trailer.frame_check_sequence, [6, 7, 8, 9]);
4675    /// ```
4676    ///
4677    #[doc = codegen_section!(
4678        header = "h5",
4679        bench = "ref_from_suffix",
4680        format = "coco",
4681        arity = 3,
4682        [
4683            open
4684            @index 1
4685            @title "Sized"
4686            @variant "static_size"
4687        ],
4688        [
4689            @index 2
4690            @title "Unsized"
4691            @variant "dynamic_size"
4692        ],
4693        [
4694            @index 3
4695            @title "Dynamically Padded"
4696            @variant "dynamic_padding"
4697        ]
4698    )]
4699    #[must_use = "has no side effects"]
4700    #[cfg_attr(zerocopy_inline_always, inline(always))]
4701    #[cfg_attr(not(zerocopy_inline_always), inline)]
4702    fn ref_from_suffix(source: &[u8]) -> Result<(&[u8], &Self), CastError<&[u8], Self>>
4703    where
4704        Self: Immutable + KnownLayout,
4705    {
4706        static_assert_dst_is_not_zst!(Self);
4707        ref_from_prefix_suffix(source, None, CastType::Suffix).map(swap)
4708    }
4709
4710    /// Interprets the given `source` as a `&mut Self`.
4711    ///
4712    /// This method attempts to return a reference to `source` interpreted as a
4713    /// `Self`. If the length of `source` is not a [valid size of
4714    /// `Self`][valid-size], or if `source` is not appropriately aligned, this
4715    /// returns `Err`. If [`Self: Unaligned`][self-unaligned], you can
4716    /// [infallibly discard the alignment error][size-error-from].
4717    ///
4718    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
4719    ///
4720    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
4721    /// [self-unaligned]: Unaligned
4722    /// [size-error-from]: error/struct.SizeError.html#method.from-1
4723    /// [slice-dst]: KnownLayout#dynamically-sized-types
4724    ///
4725    /// # Compile-Time Assertions
4726    ///
4727    /// This method cannot yet be used on unsized types whose dynamically-sized
4728    /// component is zero-sized. See [`mut_from_prefix_with_elems`], which does
4729    /// support such types. Attempting to use this method on such types results
4730    /// in a compile-time assertion error; e.g.:
4731    ///
4732    /// ```compile_fail,E0080
4733    /// use zerocopy::*;
4734    /// # use zerocopy_derive::*;
4735    ///
4736    /// #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)]
4737    /// #[repr(C, packed)]
4738    /// struct ZSTy {
4739    ///     leading_sized: [u8; 2],
4740    ///     trailing_dst: [()],
4741    /// }
4742    ///
4743    /// let mut source = [85, 85];
4744    /// let _ = ZSTy::mut_from_bytes(&mut source[..]); // âš  Compile Error!
4745    /// ```
4746    ///
4747    /// [`mut_from_prefix_with_elems`]: FromBytes::mut_from_prefix_with_elems
4748    ///
4749    /// # Examples
4750    ///
4751    /// ```
4752    /// use zerocopy::FromBytes;
4753    /// # use zerocopy_derive::*;
4754    ///
4755    /// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
4756    /// #[repr(C)]
4757    /// struct PacketHeader {
4758    ///     src_port: [u8; 2],
4759    ///     dst_port: [u8; 2],
4760    ///     length: [u8; 2],
4761    ///     checksum: [u8; 2],
4762    /// }
4763    ///
4764    /// // These bytes encode a `PacketHeader`.
4765    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7][..];
4766    ///
4767    /// let header = PacketHeader::mut_from_bytes(bytes).unwrap();
4768    ///
4769    /// assert_eq!(header.src_port, [0, 1]);
4770    /// assert_eq!(header.dst_port, [2, 3]);
4771    /// assert_eq!(header.length, [4, 5]);
4772    /// assert_eq!(header.checksum, [6, 7]);
4773    ///
4774    /// header.checksum = [0, 0];
4775    ///
4776    /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 0, 0]);
4777    ///
4778    /// ```
4779    ///
4780    #[doc = codegen_section!(
4781        header = "h5",
4782        name = "mut_from_bytes",
4783        /// See [`FromBytes::ref_from_bytes`](#method.ref_from_bytes.codegen).
4784    )]
4785    #[must_use = "has no side effects"]
4786    #[cfg_attr(zerocopy_inline_always, inline(always))]
4787    #[cfg_attr(not(zerocopy_inline_always), inline)]
4788    fn mut_from_bytes(source: &mut [u8]) -> Result<&mut Self, CastError<&mut [u8], Self>>
4789    where
4790        Self: IntoBytes + KnownLayout,
4791    {
4792        static_assert_dst_is_not_zst!(Self);
4793        match Ptr::from_mut(source).try_cast_into_no_leftover::<_, BecauseExclusive>(None) {
4794            Ok(ptr) => Ok(ptr.recall_validity::<_, (_, (_, _))>().as_mut()),
4795            Err(err) => Err(err.map_src(|src| src.as_mut())),
4796        }
4797    }
4798
4799    /// Interprets the prefix of the given `source` as a `&mut Self` without
4800    /// copying.
4801    ///
4802    /// This method computes the [largest possible size of `Self`][valid-size]
4803    /// that can fit in the leading bytes of `source`, then attempts to return
4804    /// both a reference to those bytes interpreted as a `Self`, and a reference
4805    /// to the remaining bytes. If there are insufficient bytes, or if `source`
4806    /// is not appropriately aligned, this returns `Err`. If [`Self:
4807    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
4808    /// error][size-error-from].
4809    ///
4810    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
4811    ///
4812    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
4813    /// [self-unaligned]: Unaligned
4814    /// [size-error-from]: error/struct.SizeError.html#method.from-1
4815    /// [slice-dst]: KnownLayout#dynamically-sized-types
4816    ///
4817    /// # Compile-Time Assertions
4818    ///
4819    /// This method cannot yet be used on unsized types whose dynamically-sized
4820    /// component is zero-sized. See [`mut_from_suffix_with_elems`], which does
4821    /// support such types. Attempting to use this method on such types results
4822    /// in a compile-time assertion error; e.g.:
4823    ///
4824    /// ```compile_fail,E0080
4825    /// use zerocopy::*;
4826    /// # use zerocopy_derive::*;
4827    ///
4828    /// #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)]
4829    /// #[repr(C, packed)]
4830    /// struct ZSTy {
4831    ///     leading_sized: [u8; 2],
4832    ///     trailing_dst: [()],
4833    /// }
4834    ///
4835    /// let mut source = [85, 85];
4836    /// let _ = ZSTy::mut_from_prefix(&mut source[..]); // âš  Compile Error!
4837    /// ```
4838    ///
4839    /// [`mut_from_suffix_with_elems`]: FromBytes::mut_from_suffix_with_elems
4840    ///
4841    /// # Examples
4842    ///
4843    /// ```
4844    /// use zerocopy::FromBytes;
4845    /// # use zerocopy_derive::*;
4846    ///
4847    /// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
4848    /// #[repr(C)]
4849    /// struct PacketHeader {
4850    ///     src_port: [u8; 2],
4851    ///     dst_port: [u8; 2],
4852    ///     length: [u8; 2],
4853    ///     checksum: [u8; 2],
4854    /// }
4855    ///
4856    /// // These are more bytes than are needed to encode a `PacketHeader`.
4857    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
4858    ///
4859    /// let (header, body) = PacketHeader::mut_from_prefix(bytes).unwrap();
4860    ///
4861    /// assert_eq!(header.src_port, [0, 1]);
4862    /// assert_eq!(header.dst_port, [2, 3]);
4863    /// assert_eq!(header.length, [4, 5]);
4864    /// assert_eq!(header.checksum, [6, 7]);
4865    /// assert_eq!(body, &[8, 9][..]);
4866    ///
4867    /// header.checksum = [0, 0];
4868    /// body.fill(1);
4869    ///
4870    /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 0, 0, 1, 1]);
4871    /// ```
4872    ///
4873    #[doc = codegen_section!(
4874        header = "h5",
4875        name = "mut_from_prefix",
4876        /// See [`FromBytes::ref_from_prefix`](#method.ref_from_prefix.codegen).
4877    )]
4878    #[must_use = "has no side effects"]
4879    #[cfg_attr(zerocopy_inline_always, inline(always))]
4880    #[cfg_attr(not(zerocopy_inline_always), inline)]
4881    fn mut_from_prefix(
4882        source: &mut [u8],
4883    ) -> Result<(&mut Self, &mut [u8]), CastError<&mut [u8], Self>>
4884    where
4885        Self: IntoBytes + KnownLayout,
4886    {
4887        static_assert_dst_is_not_zst!(Self);
4888        mut_from_prefix_suffix(source, None, CastType::Prefix)
4889    }
4890
4891    /// Interprets the suffix of the given `source` as a `&mut Self` without
4892    /// copying.
4893    ///
4894    /// This method computes the [largest possible size of `Self`][valid-size]
4895    /// that can fit in the trailing bytes of `source`, then attempts to return
4896    /// both a reference to those bytes interpreted as a `Self`, and a reference
4897    /// to the preceding bytes. If there are insufficient bytes, or if that
4898    /// suffix of `source` is not appropriately aligned, this returns `Err`. If
4899    /// [`Self: Unaligned`][self-unaligned], you can [infallibly discard the
4900    /// alignment error][size-error-from].
4901    ///
4902    /// `Self` may be a sized type, a slice, or a [slice DST][slice-dst].
4903    ///
4904    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
4905    /// [self-unaligned]: Unaligned
4906    /// [size-error-from]: error/struct.SizeError.html#method.from-1
4907    /// [slice-dst]: KnownLayout#dynamically-sized-types
4908    ///
4909    /// # Compile-Time Assertions
4910    ///
4911    /// This method cannot yet be used on unsized types whose dynamically-sized
4912    /// component is zero-sized. Attempting to use this method on such types
4913    /// results in a compile-time assertion error; e.g.:
4914    ///
4915    /// ```compile_fail,E0080
4916    /// use zerocopy::*;
4917    /// # use zerocopy_derive::*;
4918    ///
4919    /// #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)]
4920    /// #[repr(C, packed)]
4921    /// struct ZSTy {
4922    ///     leading_sized: [u8; 2],
4923    ///     trailing_dst: [()],
4924    /// }
4925    ///
4926    /// let mut source = [85, 85];
4927    /// let _ = ZSTy::mut_from_suffix(&mut source[..]); // âš  Compile Error!
4928    /// ```
4929    ///
4930    /// # Examples
4931    ///
4932    /// ```
4933    /// use zerocopy::FromBytes;
4934    /// # use zerocopy_derive::*;
4935    ///
4936    /// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
4937    /// #[repr(C)]
4938    /// struct PacketTrailer {
4939    ///     frame_check_sequence: [u8; 4],
4940    /// }
4941    ///
4942    /// // These are more bytes than are needed to encode a `PacketTrailer`.
4943    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
4944    ///
4945    /// let (prefix, trailer) = PacketTrailer::mut_from_suffix(bytes).unwrap();
4946    ///
4947    /// assert_eq!(prefix, &[0u8, 1, 2, 3, 4, 5][..]);
4948    /// assert_eq!(trailer.frame_check_sequence, [6, 7, 8, 9]);
4949    ///
4950    /// prefix.fill(0);
4951    /// trailer.frame_check_sequence.fill(1);
4952    ///
4953    /// assert_eq!(bytes, [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
4954    /// ```
4955    ///
4956    #[doc = codegen_section!(
4957        header = "h5",
4958        name = "mut_from_suffix",
4959        /// See [`FromBytes::ref_from_suffix`](#method.ref_from_suffix.codegen).
4960    )]
4961    #[must_use = "has no side effects"]
4962    #[cfg_attr(zerocopy_inline_always, inline(always))]
4963    #[cfg_attr(not(zerocopy_inline_always), inline)]
4964    fn mut_from_suffix(
4965        source: &mut [u8],
4966    ) -> Result<(&mut [u8], &mut Self), CastError<&mut [u8], Self>>
4967    where
4968        Self: IntoBytes + KnownLayout,
4969    {
4970        static_assert_dst_is_not_zst!(Self);
4971        mut_from_prefix_suffix(source, None, CastType::Suffix).map(swap)
4972    }
4973
4974    /// Interprets the given `source` as a `&Self` with a DST length equal to
4975    /// `count`.
4976    ///
4977    /// This method attempts to return a reference to `source` interpreted as a
4978    /// `Self` with `count` trailing elements. If the length of `source` is not
4979    /// equal to the size of `Self` with `count` elements, or if `source` is not
4980    /// appropriately aligned, this returns `Err`. If [`Self:
4981    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
4982    /// error][size-error-from].
4983    ///
4984    /// [self-unaligned]: Unaligned
4985    /// [size-error-from]: error/struct.SizeError.html#method.from-1
4986    ///
4987    /// # Examples
4988    ///
4989    /// ```
4990    /// use zerocopy::FromBytes;
4991    /// # use zerocopy_derive::*;
4992    ///
4993    /// # #[derive(Debug, PartialEq, Eq)]
4994    /// #[derive(FromBytes, Immutable)]
4995    /// #[repr(C)]
4996    /// struct Pixel {
4997    ///     r: u8,
4998    ///     g: u8,
4999    ///     b: u8,
5000    ///     a: u8,
5001    /// }
5002    ///
5003    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7][..];
5004    ///
5005    /// let pixels = <[Pixel]>::ref_from_bytes_with_elems(bytes, 2).unwrap();
5006    ///
5007    /// assert_eq!(pixels, &[
5008    ///     Pixel { r: 0, g: 1, b: 2, a: 3 },
5009    ///     Pixel { r: 4, g: 5, b: 6, a: 7 },
5010    /// ]);
5011    ///
5012    /// ```
5013    ///
5014    /// Since an explicit `count` is provided, this method supports types with
5015    /// zero-sized trailing slice elements. Methods such as [`ref_from_bytes`]
5016    /// which do not take an explicit count do not support such types.
5017    ///
5018    /// ```
5019    /// use zerocopy::*;
5020    /// # use zerocopy_derive::*;
5021    ///
5022    /// #[derive(FromBytes, Immutable, KnownLayout)]
5023    /// #[repr(C)]
5024    /// struct ZSTy {
5025    ///     leading_sized: [u8; 2],
5026    ///     trailing_dst: [()],
5027    /// }
5028    ///
5029    /// let src = &[85, 85][..];
5030    /// let zsty = ZSTy::ref_from_bytes_with_elems(src, 42).unwrap();
5031    /// assert_eq!(zsty.trailing_dst.len(), 42);
5032    /// ```
5033    ///
5034    /// [`ref_from_bytes`]: FromBytes::ref_from_bytes
5035    ///
5036    #[doc = codegen_section!(
5037        header = "h5",
5038        bench = "ref_from_bytes_with_elems",
5039        format = "coco",
5040        arity = 2,
5041        [
5042            open
5043            @index 1
5044            @title "Unsized"
5045            @variant "dynamic_size"
5046        ],
5047        [
5048            @index 2
5049            @title "Dynamically Padded"
5050            @variant "dynamic_padding"
5051        ]
5052    )]
5053    #[must_use = "has no side effects"]
5054    #[cfg_attr(zerocopy_inline_always, inline(always))]
5055    #[cfg_attr(not(zerocopy_inline_always), inline)]
5056    fn ref_from_bytes_with_elems(
5057        source: &[u8],
5058        count: usize,
5059    ) -> Result<&Self, CastError<&[u8], Self>>
5060    where
5061        Self: KnownLayout<PointerMetadata = usize> + Immutable,
5062    {
5063        let source = Ptr::from_ref(source);
5064        let maybe_slf = source.try_cast_into_no_leftover::<_, BecauseImmutable>(Some(count));
5065        match maybe_slf {
5066            Ok(slf) => Ok(slf.recall_validity().as_ref()),
5067            Err(err) => Err(err.map_src(|s| s.as_ref())),
5068        }
5069    }
5070
5071    /// Interprets the prefix of the given `source` as a DST `&Self` with length
5072    /// equal to `count`.
5073    ///
5074    /// This method attempts to return a reference to the prefix of `source`
5075    /// interpreted as a `Self` with `count` trailing elements, and a reference
5076    /// to the remaining bytes. If there are insufficient bytes, or if `source`
5077    /// is not appropriately aligned, this returns `Err`. If [`Self:
5078    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
5079    /// error][size-error-from].
5080    ///
5081    /// [self-unaligned]: Unaligned
5082    /// [size-error-from]: error/struct.SizeError.html#method.from-1
5083    ///
5084    /// # Examples
5085    ///
5086    /// ```
5087    /// use zerocopy::FromBytes;
5088    /// # use zerocopy_derive::*;
5089    ///
5090    /// # #[derive(Debug, PartialEq, Eq)]
5091    /// #[derive(FromBytes, Immutable)]
5092    /// #[repr(C)]
5093    /// struct Pixel {
5094    ///     r: u8,
5095    ///     g: u8,
5096    ///     b: u8,
5097    ///     a: u8,
5098    /// }
5099    ///
5100    /// // These are more bytes than are needed to encode two `Pixel`s.
5101    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
5102    ///
5103    /// let (pixels, suffix) = <[Pixel]>::ref_from_prefix_with_elems(bytes, 2).unwrap();
5104    ///
5105    /// assert_eq!(pixels, &[
5106    ///     Pixel { r: 0, g: 1, b: 2, a: 3 },
5107    ///     Pixel { r: 4, g: 5, b: 6, a: 7 },
5108    /// ]);
5109    ///
5110    /// assert_eq!(suffix, &[8, 9]);
5111    /// ```
5112    ///
5113    /// Since an explicit `count` is provided, this method supports types with
5114    /// zero-sized trailing slice elements. Methods such as [`ref_from_prefix`]
5115    /// which do not take an explicit count do not support such types.
5116    ///
5117    /// ```
5118    /// use zerocopy::*;
5119    /// # use zerocopy_derive::*;
5120    ///
5121    /// #[derive(FromBytes, Immutable, KnownLayout)]
5122    /// #[repr(C)]
5123    /// struct ZSTy {
5124    ///     leading_sized: [u8; 2],
5125    ///     trailing_dst: [()],
5126    /// }
5127    ///
5128    /// let src = &[85, 85][..];
5129    /// let (zsty, _) = ZSTy::ref_from_prefix_with_elems(src, 42).unwrap();
5130    /// assert_eq!(zsty.trailing_dst.len(), 42);
5131    /// ```
5132    ///
5133    /// [`ref_from_prefix`]: FromBytes::ref_from_prefix
5134    ///
5135    #[doc = codegen_section!(
5136        header = "h5",
5137        bench = "ref_from_prefix_with_elems",
5138        format = "coco",
5139        arity = 2,
5140        [
5141            open
5142            @index 1
5143            @title "Unsized"
5144            @variant "dynamic_size"
5145        ],
5146        [
5147            @index 2
5148            @title "Dynamically Padded"
5149            @variant "dynamic_padding"
5150        ]
5151    )]
5152    #[must_use = "has no side effects"]
5153    #[cfg_attr(zerocopy_inline_always, inline(always))]
5154    #[cfg_attr(not(zerocopy_inline_always), inline)]
5155    fn ref_from_prefix_with_elems(
5156        source: &[u8],
5157        count: usize,
5158    ) -> Result<(&Self, &[u8]), CastError<&[u8], Self>>
5159    where
5160        Self: KnownLayout<PointerMetadata = usize> + Immutable,
5161    {
5162        ref_from_prefix_suffix(source, Some(count), CastType::Prefix)
5163    }
5164
5165    /// Interprets the suffix of the given `source` as a DST `&Self` with length
5166    /// equal to `count`.
5167    ///
5168    /// This method attempts to return a reference to the suffix of `source`
5169    /// interpreted as a `Self` with `count` trailing elements, and a reference
5170    /// to the preceding bytes. If there are insufficient bytes, or if that
5171    /// suffix of `source` is not appropriately aligned, this returns `Err`. If
5172    /// [`Self: Unaligned`][self-unaligned], you can [infallibly discard the
5173    /// alignment error][size-error-from].
5174    ///
5175    /// [self-unaligned]: Unaligned
5176    /// [size-error-from]: error/struct.SizeError.html#method.from-1
5177    ///
5178    /// # Examples
5179    ///
5180    /// ```
5181    /// use zerocopy::FromBytes;
5182    /// # use zerocopy_derive::*;
5183    ///
5184    /// # #[derive(Debug, PartialEq, Eq)]
5185    /// #[derive(FromBytes, Immutable)]
5186    /// #[repr(C)]
5187    /// struct Pixel {
5188    ///     r: u8,
5189    ///     g: u8,
5190    ///     b: u8,
5191    ///     a: u8,
5192    /// }
5193    ///
5194    /// // These are more bytes than are needed to encode two `Pixel`s.
5195    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
5196    ///
5197    /// let (prefix, pixels) = <[Pixel]>::ref_from_suffix_with_elems(bytes, 2).unwrap();
5198    ///
5199    /// assert_eq!(prefix, &[0, 1]);
5200    ///
5201    /// assert_eq!(pixels, &[
5202    ///     Pixel { r: 2, g: 3, b: 4, a: 5 },
5203    ///     Pixel { r: 6, g: 7, b: 8, a: 9 },
5204    /// ]);
5205    /// ```
5206    ///
5207    /// Since an explicit `count` is provided, this method supports types with
5208    /// zero-sized trailing slice elements. Methods such as [`ref_from_suffix`]
5209    /// which do not take an explicit count do not support such types.
5210    ///
5211    /// ```
5212    /// use zerocopy::*;
5213    /// # use zerocopy_derive::*;
5214    ///
5215    /// #[derive(FromBytes, Immutable, KnownLayout)]
5216    /// #[repr(C)]
5217    /// struct ZSTy {
5218    ///     leading_sized: [u8; 2],
5219    ///     trailing_dst: [()],
5220    /// }
5221    ///
5222    /// let src = &[85, 85][..];
5223    /// let (_, zsty) = ZSTy::ref_from_suffix_with_elems(src, 42).unwrap();
5224    /// assert_eq!(zsty.trailing_dst.len(), 42);
5225    /// ```
5226    ///
5227    /// [`ref_from_suffix`]: FromBytes::ref_from_suffix
5228    ///
5229    #[doc = codegen_section!(
5230        header = "h5",
5231        bench = "ref_from_suffix_with_elems",
5232        format = "coco",
5233        arity = 2,
5234        [
5235            open
5236            @index 1
5237            @title "Unsized"
5238            @variant "dynamic_size"
5239        ],
5240        [
5241            @index 2
5242            @title "Dynamically Padded"
5243            @variant "dynamic_padding"
5244        ]
5245    )]
5246    #[must_use = "has no side effects"]
5247    #[cfg_attr(zerocopy_inline_always, inline(always))]
5248    #[cfg_attr(not(zerocopy_inline_always), inline)]
5249    fn ref_from_suffix_with_elems(
5250        source: &[u8],
5251        count: usize,
5252    ) -> Result<(&[u8], &Self), CastError<&[u8], Self>>
5253    where
5254        Self: KnownLayout<PointerMetadata = usize> + Immutable,
5255    {
5256        ref_from_prefix_suffix(source, Some(count), CastType::Suffix).map(swap)
5257    }
5258
5259    /// Interprets the given `source` as a `&mut Self` with a DST length equal
5260    /// to `count`.
5261    ///
5262    /// This method attempts to return a reference to `source` interpreted as a
5263    /// `Self` with `count` trailing elements. If the length of `source` is not
5264    /// equal to the size of `Self` with `count` elements, or if `source` is not
5265    /// appropriately aligned, this returns `Err`. If [`Self:
5266    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
5267    /// error][size-error-from].
5268    ///
5269    /// [self-unaligned]: Unaligned
5270    /// [size-error-from]: error/struct.SizeError.html#method.from-1
5271    ///
5272    /// # Examples
5273    ///
5274    /// ```
5275    /// use zerocopy::FromBytes;
5276    /// # use zerocopy_derive::*;
5277    ///
5278    /// # #[derive(Debug, PartialEq, Eq)]
5279    /// #[derive(KnownLayout, FromBytes, IntoBytes, Immutable)]
5280    /// #[repr(C)]
5281    /// struct Pixel {
5282    ///     r: u8,
5283    ///     g: u8,
5284    ///     b: u8,
5285    ///     a: u8,
5286    /// }
5287    ///
5288    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7][..];
5289    ///
5290    /// let pixels = <[Pixel]>::mut_from_bytes_with_elems(bytes, 2).unwrap();
5291    ///
5292    /// assert_eq!(pixels, &[
5293    ///     Pixel { r: 0, g: 1, b: 2, a: 3 },
5294    ///     Pixel { r: 4, g: 5, b: 6, a: 7 },
5295    /// ]);
5296    ///
5297    /// pixels[1] = Pixel { r: 0, g: 0, b: 0, a: 0 };
5298    ///
5299    /// assert_eq!(bytes, [0, 1, 2, 3, 0, 0, 0, 0]);
5300    /// ```
5301    ///
5302    /// Since an explicit `count` is provided, this method supports types with
5303    /// zero-sized trailing slice elements. Methods such as [`mut_from_bytes`]
5304    /// which do not take an explicit count do not support such types.
5305    ///
5306    /// ```
5307    /// use zerocopy::*;
5308    /// # use zerocopy_derive::*;
5309    ///
5310    /// #[derive(FromBytes, IntoBytes, Immutable, KnownLayout)]
5311    /// #[repr(C, packed)]
5312    /// struct ZSTy {
5313    ///     leading_sized: [u8; 2],
5314    ///     trailing_dst: [()],
5315    /// }
5316    ///
5317    /// let src = &mut [85, 85][..];
5318    /// let zsty = ZSTy::mut_from_bytes_with_elems(src, 42).unwrap();
5319    /// assert_eq!(zsty.trailing_dst.len(), 42);
5320    /// ```
5321    ///
5322    /// [`mut_from_bytes`]: FromBytes::mut_from_bytes
5323    ///
5324    #[doc = codegen_section!(
5325        header = "h5",
5326        name = "mut_from_bytes_with_elems",
5327        /// See [`TryFromBytes::ref_from_bytes_with_elems`](#method.ref_from_bytes_with_elems.codegen).
5328    )]
5329    #[must_use = "has no side effects"]
5330    #[cfg_attr(zerocopy_inline_always, inline(always))]
5331    #[cfg_attr(not(zerocopy_inline_always), inline)]
5332    fn mut_from_bytes_with_elems(
5333        source: &mut [u8],
5334        count: usize,
5335    ) -> Result<&mut Self, CastError<&mut [u8], Self>>
5336    where
5337        Self: IntoBytes + KnownLayout<PointerMetadata = usize> + Immutable,
5338    {
5339        let source = Ptr::from_mut(source);
5340        let maybe_slf = source.try_cast_into_no_leftover::<_, BecauseImmutable>(Some(count));
5341        match maybe_slf {
5342            Ok(slf) => Ok(slf.recall_validity::<_, (_, (_, BecauseExclusive))>().as_mut()),
5343            Err(err) => Err(err.map_src(|s| s.as_mut())),
5344        }
5345    }
5346
5347    /// Interprets the prefix of the given `source` as a `&mut Self` with DST
5348    /// length equal to `count`.
5349    ///
5350    /// This method attempts to return a reference to the prefix of `source`
5351    /// interpreted as a `Self` with `count` trailing elements, and a reference
5352    /// to the preceding bytes. If there are insufficient bytes, or if `source`
5353    /// is not appropriately aligned, this returns `Err`. If [`Self:
5354    /// Unaligned`][self-unaligned], you can [infallibly discard the alignment
5355    /// error][size-error-from].
5356    ///
5357    /// [self-unaligned]: Unaligned
5358    /// [size-error-from]: error/struct.SizeError.html#method.from-1
5359    ///
5360    /// # Examples
5361    ///
5362    /// ```
5363    /// use zerocopy::FromBytes;
5364    /// # use zerocopy_derive::*;
5365    ///
5366    /// # #[derive(Debug, PartialEq, Eq)]
5367    /// #[derive(KnownLayout, FromBytes, IntoBytes, Immutable)]
5368    /// #[repr(C)]
5369    /// struct Pixel {
5370    ///     r: u8,
5371    ///     g: u8,
5372    ///     b: u8,
5373    ///     a: u8,
5374    /// }
5375    ///
5376    /// // These are more bytes than are needed to encode two `Pixel`s.
5377    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
5378    ///
5379    /// let (pixels, suffix) = <[Pixel]>::mut_from_prefix_with_elems(bytes, 2).unwrap();
5380    ///
5381    /// assert_eq!(pixels, &[
5382    ///     Pixel { r: 0, g: 1, b: 2, a: 3 },
5383    ///     Pixel { r: 4, g: 5, b: 6, a: 7 },
5384    /// ]);
5385    ///
5386    /// assert_eq!(suffix, &[8, 9]);
5387    ///
5388    /// pixels[1] = Pixel { r: 0, g: 0, b: 0, a: 0 };
5389    /// suffix.fill(1);
5390    ///
5391    /// assert_eq!(bytes, [0, 1, 2, 3, 0, 0, 0, 0, 1, 1]);
5392    /// ```
5393    ///
5394    /// Since an explicit `count` is provided, this method supports types with
5395    /// zero-sized trailing slice elements. Methods such as [`mut_from_prefix`]
5396    /// which do not take an explicit count do not support such types.
5397    ///
5398    /// ```
5399    /// use zerocopy::*;
5400    /// # use zerocopy_derive::*;
5401    ///
5402    /// #[derive(FromBytes, IntoBytes, Immutable, KnownLayout)]
5403    /// #[repr(C, packed)]
5404    /// struct ZSTy {
5405    ///     leading_sized: [u8; 2],
5406    ///     trailing_dst: [()],
5407    /// }
5408    ///
5409    /// let src = &mut [85, 85][..];
5410    /// let (zsty, _) = ZSTy::mut_from_prefix_with_elems(src, 42).unwrap();
5411    /// assert_eq!(zsty.trailing_dst.len(), 42);
5412    /// ```
5413    ///
5414    /// [`mut_from_prefix`]: FromBytes::mut_from_prefix
5415    ///
5416    #[doc = codegen_section!(
5417        header = "h5",
5418        name = "mut_from_prefix_with_elems",
5419        /// See [`TryFromBytes::ref_from_prefix_with_elems`](#method.ref_from_prefix_with_elems.codegen).
5420    )]
5421    #[must_use = "has no side effects"]
5422    #[cfg_attr(zerocopy_inline_always, inline(always))]
5423    #[cfg_attr(not(zerocopy_inline_always), inline)]
5424    fn mut_from_prefix_with_elems(
5425        source: &mut [u8],
5426        count: usize,
5427    ) -> Result<(&mut Self, &mut [u8]), CastError<&mut [u8], Self>>
5428    where
5429        Self: IntoBytes + KnownLayout<PointerMetadata = usize>,
5430    {
5431        mut_from_prefix_suffix(source, Some(count), CastType::Prefix)
5432    }
5433
5434    /// Interprets the suffix of the given `source` as a `&mut Self` with DST
5435    /// length equal to `count`.
5436    ///
5437    /// This method attempts to return a reference to the suffix of `source`
5438    /// interpreted as a `Self` with `count` trailing elements, and a reference
5439    /// to the remaining bytes. If there are insufficient bytes, or if that
5440    /// suffix of `source` is not appropriately aligned, this returns `Err`. If
5441    /// [`Self: Unaligned`][self-unaligned], you can [infallibly discard the
5442    /// alignment error][size-error-from].
5443    ///
5444    /// [self-unaligned]: Unaligned
5445    /// [size-error-from]: error/struct.SizeError.html#method.from-1
5446    ///
5447    /// # Examples
5448    ///
5449    /// ```
5450    /// use zerocopy::FromBytes;
5451    /// # use zerocopy_derive::*;
5452    ///
5453    /// # #[derive(Debug, PartialEq, Eq)]
5454    /// #[derive(FromBytes, IntoBytes, Immutable)]
5455    /// #[repr(C)]
5456    /// struct Pixel {
5457    ///     r: u8,
5458    ///     g: u8,
5459    ///     b: u8,
5460    ///     a: u8,
5461    /// }
5462    ///
5463    /// // These are more bytes than are needed to encode two `Pixel`s.
5464    /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
5465    ///
5466    /// let (prefix, pixels) = <[Pixel]>::mut_from_suffix_with_elems(bytes, 2).unwrap();
5467    ///
5468    /// assert_eq!(prefix, &[0, 1]);
5469    ///
5470    /// assert_eq!(pixels, &[
5471    ///     Pixel { r: 2, g: 3, b: 4, a: 5 },
5472    ///     Pixel { r: 6, g: 7, b: 8, a: 9 },
5473    /// ]);
5474    ///
5475    /// prefix.fill(9);
5476    /// pixels[1] = Pixel { r: 0, g: 0, b: 0, a: 0 };
5477    ///
5478    /// assert_eq!(bytes, [9, 9, 2, 3, 4, 5, 0, 0, 0, 0]);
5479    /// ```
5480    ///
5481    /// Since an explicit `count` is provided, this method supports types with
5482    /// zero-sized trailing slice elements. Methods such as [`mut_from_suffix`]
5483    /// which do not take an explicit count do not support such types.
5484    ///
5485    /// ```
5486    /// use zerocopy::*;
5487    /// # use zerocopy_derive::*;
5488    ///
5489    /// #[derive(FromBytes, IntoBytes, Immutable, KnownLayout)]
5490    /// #[repr(C, packed)]
5491    /// struct ZSTy {
5492    ///     leading_sized: [u8; 2],
5493    ///     trailing_dst: [()],
5494    /// }
5495    ///
5496    /// let src = &mut [85, 85][..];
5497    /// let (_, zsty) = ZSTy::mut_from_suffix_with_elems(src, 42).unwrap();
5498    /// assert_eq!(zsty.trailing_dst.len(), 42);
5499    /// ```
5500    ///
5501    /// [`mut_from_suffix`]: FromBytes::mut_from_suffix
5502    ///
5503    #[doc = codegen_section!(
5504        header = "h5",
5505        name = "mut_from_suffix_with_elems",
5506        /// See [`TryFromBytes::ref_from_suffix_with_elems`](#method.ref_from_suffix_with_elems.codegen).
5507    )]
5508    #[must_use = "has no side effects"]
5509    #[cfg_attr(zerocopy_inline_always, inline(always))]
5510    #[cfg_attr(not(zerocopy_inline_always), inline)]
5511    fn mut_from_suffix_with_elems(
5512        source: &mut [u8],
5513        count: usize,
5514    ) -> Result<(&mut [u8], &mut Self), CastError<&mut [u8], Self>>
5515    where
5516        Self: IntoBytes + KnownLayout<PointerMetadata = usize>,
5517    {
5518        mut_from_prefix_suffix(source, Some(count), CastType::Suffix).map(swap)
5519    }
5520
5521    /// Reads a copy of `Self` from the given `source`.
5522    ///
5523    /// If `source.len() != size_of::<Self>()`, `read_from_bytes` returns `Err`.
5524    ///
5525    /// # Examples
5526    ///
5527    /// ```
5528    /// use zerocopy::FromBytes;
5529    /// # use zerocopy_derive::*;
5530    ///
5531    /// #[derive(FromBytes)]
5532    /// #[repr(C)]
5533    /// struct PacketHeader {
5534    ///     src_port: [u8; 2],
5535    ///     dst_port: [u8; 2],
5536    ///     length: [u8; 2],
5537    ///     checksum: [u8; 2],
5538    /// }
5539    ///
5540    /// // These bytes encode a `PacketHeader`.
5541    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7][..];
5542    ///
5543    /// let header = PacketHeader::read_from_bytes(bytes).unwrap();
5544    ///
5545    /// assert_eq!(header.src_port, [0, 1]);
5546    /// assert_eq!(header.dst_port, [2, 3]);
5547    /// assert_eq!(header.length, [4, 5]);
5548    /// assert_eq!(header.checksum, [6, 7]);
5549    /// ```
5550    ///
5551    #[doc = codegen_section!(
5552        header = "h5",
5553        bench = "read_from_bytes",
5554        format = "coco_static_size",
5555    )]
5556    #[must_use = "has no side effects"]
5557    #[cfg_attr(zerocopy_inline_always, inline(always))]
5558    #[cfg_attr(not(zerocopy_inline_always), inline)]
5559    fn read_from_bytes(source: &[u8]) -> Result<Self, SizeError<&[u8], Self>>
5560    where
5561        Self: Sized,
5562    {
5563        match Ref::<_, Unalign<Self>>::sized_from(source) {
5564            Ok(r) => Ok(Ref::read(&r).into_inner()),
5565            Err(CastError::Size(e)) => Err(e.with_dst()),
5566            Err(CastError::Alignment(_)) => {
5567                // SAFETY: `Unalign<Self>` is trivially aligned, so
5568                // `Ref::sized_from` cannot fail due to unmet alignment
5569                // requirements.
5570                unsafe { core::hint::unreachable_unchecked() }
5571            }
5572            Err(CastError::Validity(i)) => match i {},
5573        }
5574    }
5575
5576    /// Reads a copy of `Self` from the prefix of the given `source`.
5577    ///
5578    /// This attempts to read a `Self` from the first `size_of::<Self>()` bytes
5579    /// of `source`, returning that `Self` and any remaining bytes. If
5580    /// `source.len() < size_of::<Self>()`, it returns `Err`.
5581    ///
5582    /// # Examples
5583    ///
5584    /// ```
5585    /// use zerocopy::FromBytes;
5586    /// # use zerocopy_derive::*;
5587    ///
5588    /// #[derive(FromBytes)]
5589    /// #[repr(C)]
5590    /// struct PacketHeader {
5591    ///     src_port: [u8; 2],
5592    ///     dst_port: [u8; 2],
5593    ///     length: [u8; 2],
5594    ///     checksum: [u8; 2],
5595    /// }
5596    ///
5597    /// // These are more bytes than are needed to encode a `PacketHeader`.
5598    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
5599    ///
5600    /// let (header, body) = PacketHeader::read_from_prefix(bytes).unwrap();
5601    ///
5602    /// assert_eq!(header.src_port, [0, 1]);
5603    /// assert_eq!(header.dst_port, [2, 3]);
5604    /// assert_eq!(header.length, [4, 5]);
5605    /// assert_eq!(header.checksum, [6, 7]);
5606    /// assert_eq!(body, [8, 9]);
5607    /// ```
5608    ///
5609    #[doc = codegen_section!(
5610        header = "h5",
5611        bench = "read_from_prefix",
5612        format = "coco_static_size",
5613    )]
5614    #[must_use = "has no side effects"]
5615    #[cfg_attr(zerocopy_inline_always, inline(always))]
5616    #[cfg_attr(not(zerocopy_inline_always), inline)]
5617    fn read_from_prefix(source: &[u8]) -> Result<(Self, &[u8]), SizeError<&[u8], Self>>
5618    where
5619        Self: Sized,
5620    {
5621        match Ref::<_, Unalign<Self>>::sized_from_prefix(source) {
5622            Ok((r, suffix)) => Ok((Ref::read(&r).into_inner(), suffix)),
5623            Err(CastError::Size(e)) => Err(e.with_dst()),
5624            Err(CastError::Alignment(_)) => {
5625                // SAFETY: `Unalign<Self>` is trivially aligned, so
5626                // `Ref::sized_from_prefix` cannot fail due to unmet alignment
5627                // requirements.
5628                unsafe { core::hint::unreachable_unchecked() }
5629            }
5630            Err(CastError::Validity(i)) => match i {},
5631        }
5632    }
5633
5634    /// Reads a copy of `Self` from the suffix of the given `source`.
5635    ///
5636    /// This attempts to read a `Self` from the last `size_of::<Self>()` bytes
5637    /// of `source`, returning that `Self` and any preceding bytes. If
5638    /// `source.len() < size_of::<Self>()`, it returns `Err`.
5639    ///
5640    /// # Examples
5641    ///
5642    /// ```
5643    /// use zerocopy::FromBytes;
5644    /// # use zerocopy_derive::*;
5645    ///
5646    /// #[derive(FromBytes)]
5647    /// #[repr(C)]
5648    /// struct PacketTrailer {
5649    ///     frame_check_sequence: [u8; 4],
5650    /// }
5651    ///
5652    /// // These are more bytes than are needed to encode a `PacketTrailer`.
5653    /// let bytes = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];
5654    ///
5655    /// let (prefix, trailer) = PacketTrailer::read_from_suffix(bytes).unwrap();
5656    ///
5657    /// assert_eq!(prefix, [0, 1, 2, 3, 4, 5]);
5658    /// assert_eq!(trailer.frame_check_sequence, [6, 7, 8, 9]);
5659    /// ```
5660    ///
5661    #[doc = codegen_section!(
5662        header = "h5",
5663        bench = "read_from_suffix",
5664        format = "coco_static_size",
5665    )]
5666    #[must_use = "has no side effects"]
5667    #[cfg_attr(zerocopy_inline_always, inline(always))]
5668    #[cfg_attr(not(zerocopy_inline_always), inline)]
5669    fn read_from_suffix(source: &[u8]) -> Result<(&[u8], Self), SizeError<&[u8], Self>>
5670    where
5671        Self: Sized,
5672    {
5673        match Ref::<_, Unalign<Self>>::sized_from_suffix(source) {
5674            Ok((prefix, r)) => Ok((prefix, Ref::read(&r).into_inner())),
5675            Err(CastError::Size(e)) => Err(e.with_dst()),
5676            Err(CastError::Alignment(_)) => {
5677                // SAFETY: `Unalign<Self>` is trivially aligned, so
5678                // `Ref::sized_from_suffix` cannot fail due to unmet alignment
5679                // requirements.
5680                unsafe { core::hint::unreachable_unchecked() }
5681            }
5682            Err(CastError::Validity(i)) => match i {},
5683        }
5684    }
5685
5686    /// Reads a copy of `self` from an `io::Read`.
5687    ///
5688    /// This is useful for interfacing with operating system byte sinks (files,
5689    /// sockets, etc.).
5690    ///
5691    /// # Examples
5692    ///
5693    /// ```no_run
5694    /// use zerocopy::{byteorder::big_endian::*, FromBytes};
5695    /// use std::fs::File;
5696    /// # use zerocopy_derive::*;
5697    ///
5698    /// #[derive(FromBytes)]
5699    /// #[repr(C)]
5700    /// struct BitmapFileHeader {
5701    ///     signature: [u8; 2],
5702    ///     size: U32,
5703    ///     reserved: U64,
5704    ///     offset: U64,
5705    /// }
5706    ///
5707    /// let mut file = File::open("image.bin").unwrap();
5708    /// let header = BitmapFileHeader::read_from_io(&mut file).unwrap();
5709    /// ```
5710    #[cfg(feature = "std")]
5711    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
5712    #[inline(always)]
5713    fn read_from_io<R>(mut src: R) -> io::Result<Self>
5714    where
5715        Self: Sized,
5716        R: io::Read,
5717    {
5718        // NOTE(#2319, #2320): We do `buf.zero()` separately rather than
5719        // constructing `let buf = CoreMaybeUninit::zeroed()` because, if `Self`
5720        // contains padding bytes, then a typed copy of `CoreMaybeUninit<Self>`
5721        // will not necessarily preserve zeros written to those padding byte
5722        // locations, and so `buf` could contain uninitialized bytes.
5723        let mut buf = CoreMaybeUninit::<Self>::uninit();
5724        buf.zero();
5725
5726        let ptr = Ptr::from_mut(&mut buf);
5727        // SAFETY: After `buf.zero()`, `buf` consists entirely of initialized,
5728        // zeroed bytes. Since `MaybeUninit` has no validity requirements, `ptr`
5729        // cannot be used to write values which will violate `buf`'s bit
5730        // validity. Since `ptr` has `Exclusive` aliasing, nothing other than
5731        // `ptr` may be used to mutate `ptr`'s referent, and so its bit validity
5732        // cannot be violated even though `buf` may have more permissive bit
5733        // validity than `ptr`.
5734        let ptr = unsafe { ptr.assume_validity::<invariant::Initialized>() };
5735        let ptr = ptr.as_bytes();
5736        src.read_exact(ptr.as_mut())?;
5737        // SAFETY: `buf` entirely consists of initialized bytes, and `Self` is
5738        // `FromBytes`.
5739        Ok(unsafe { buf.assume_init() })
5740    }
5741
5742    #[deprecated(since = "0.8.0", note = "renamed to `FromBytes::ref_from_bytes`")]
5743    #[doc(hidden)]
5744    #[must_use = "has no side effects"]
5745    #[inline(always)]
5746    fn ref_from(source: &[u8]) -> Option<&Self>
5747    where
5748        Self: KnownLayout + Immutable,
5749    {
5750        Self::ref_from_bytes(source).ok()
5751    }
5752
5753    #[deprecated(since = "0.8.0", note = "renamed to `FromBytes::mut_from_bytes`")]
5754    #[doc(hidden)]
5755    #[must_use = "has no side effects"]
5756    #[inline(always)]
5757    fn mut_from(source: &mut [u8]) -> Option<&mut Self>
5758    where
5759        Self: KnownLayout + IntoBytes,
5760    {
5761        Self::mut_from_bytes(source).ok()
5762    }
5763
5764    #[deprecated(since = "0.8.0", note = "renamed to `FromBytes::ref_from_prefix_with_elems`")]
5765    #[doc(hidden)]
5766    #[must_use = "has no side effects"]
5767    #[inline(always)]
5768    fn slice_from_prefix(source: &[u8], count: usize) -> Option<(&[Self], &[u8])>
5769    where
5770        Self: Sized + Immutable,
5771    {
5772        <[Self]>::ref_from_prefix_with_elems(source, count).ok()
5773    }
5774
5775    #[deprecated(since = "0.8.0", note = "renamed to `FromBytes::ref_from_suffix_with_elems`")]
5776    #[doc(hidden)]
5777    #[must_use = "has no side effects"]
5778    #[inline(always)]
5779    fn slice_from_suffix(source: &[u8], count: usize) -> Option<(&[u8], &[Self])>
5780    where
5781        Self: Sized + Immutable,
5782    {
5783        <[Self]>::ref_from_suffix_with_elems(source, count).ok()
5784    }
5785
5786    #[deprecated(since = "0.8.0", note = "renamed to `FromBytes::mut_from_prefix_with_elems`")]
5787    #[doc(hidden)]
5788    #[must_use = "has no side effects"]
5789    #[inline(always)]
5790    fn mut_slice_from_prefix(source: &mut [u8], count: usize) -> Option<(&mut [Self], &mut [u8])>
5791    where
5792        Self: Sized + IntoBytes,
5793    {
5794        <[Self]>::mut_from_prefix_with_elems(source, count).ok()
5795    }
5796
5797    #[deprecated(since = "0.8.0", note = "renamed to `FromBytes::mut_from_suffix_with_elems`")]
5798    #[doc(hidden)]
5799    #[must_use = "has no side effects"]
5800    #[inline(always)]
5801    fn mut_slice_from_suffix(source: &mut [u8], count: usize) -> Option<(&mut [u8], &mut [Self])>
5802    where
5803        Self: Sized + IntoBytes,
5804    {
5805        <[Self]>::mut_from_suffix_with_elems(source, count).ok()
5806    }
5807
5808    #[deprecated(since = "0.8.0", note = "renamed to `FromBytes::read_from_bytes`")]
5809    #[doc(hidden)]
5810    #[must_use = "has no side effects"]
5811    #[inline(always)]
5812    fn read_from(source: &[u8]) -> Option<Self>
5813    where
5814        Self: Sized,
5815    {
5816        Self::read_from_bytes(source).ok()
5817    }
5818}
5819
5820/// Interprets the given affix of `source`'s bytes as a `&T`.
5821///
5822/// This method uses `meta` if provided; otherwise, it computes the largest
5823/// possible size of `T` that can fit in the prefix or suffix bytes of `source`.
5824/// It returns both a reference to those bytes interpreted as a `T`, and a
5825/// reference to the excess bytes. If there are insufficient bytes, or if that
5826/// affix of `source` is not appropriately aligned, this returns `Err` containing
5827/// the original `&S`.
5828#[inline(always)]
5829fn ref_from_prefix_suffix<S, T>(
5830    source: &S,
5831    meta: Option<T::PointerMetadata>,
5832    cast_type: CastType,
5833) -> Result<(&T, &[u8]), CastError<&S, T>>
5834where
5835    S: IntoBytes + Immutable + ?Sized,
5836    T: FromBytes + KnownLayout + Immutable + ?Sized,
5837{
5838    let (slf, prefix_suffix) = Ptr::from_ref(source.as_bytes())
5839        .try_cast_into::<_, BecauseImmutable>(cast_type, meta)
5840        .map_err(|err| {
5841            err.map_src(
5842                #[inline(always)]
5843                |_| source,
5844            )
5845        })?;
5846    Ok((slf.recall_validity().as_ref(), prefix_suffix.as_ref()))
5847}
5848
5849/// Interprets the given affix of the given bytes as a `&mut Self` without
5850/// copying.
5851///
5852/// This method computes the largest possible size of `Self` that can fit in the
5853/// prefix or suffix bytes of `source`, then attempts to return both a reference
5854/// to those bytes interpreted as a `Self`, and a reference to the excess bytes.
5855/// If there are insufficient bytes, or if that affix of `source` is not
5856/// appropriately aligned, this returns `Err`.
5857#[inline(always)]
5858fn mut_from_prefix_suffix<T: FromBytes + IntoBytes + KnownLayout + ?Sized>(
5859    source: &mut [u8],
5860    meta: Option<T::PointerMetadata>,
5861    cast_type: CastType,
5862) -> Result<(&mut T, &mut [u8]), CastError<&mut [u8], T>> {
5863    let (slf, prefix_suffix) = Ptr::from_mut(source)
5864        .try_cast_into::<_, BecauseExclusive>(cast_type, meta)
5865        .map_err(|err| err.map_src(|s| s.as_mut()))?;
5866    Ok((slf.recall_validity::<_, (_, (_, _))>().as_mut(), prefix_suffix.as_mut()))
5867}
5868
5869/// Analyzes whether a type is [`IntoBytes`].
5870///
5871/// This derive analyzes, at compile time, whether the annotated type satisfies
5872/// the [safety conditions] of `IntoBytes` and implements `IntoBytes` if it is
5873/// sound to do so. This derive can be applied to structs and enums (see below
5874/// for union support); e.g.:
5875///
5876/// ```
5877/// # use zerocopy_derive::{IntoBytes};
5878/// #[derive(IntoBytes)]
5879/// #[repr(C)]
5880/// struct MyStruct {
5881/// # /*
5882///     ...
5883/// # */
5884/// }
5885///
5886/// #[derive(IntoBytes)]
5887/// #[repr(u8)]
5888/// enum MyEnum {
5889/// #   Variant,
5890/// # /*
5891///     ...
5892/// # */
5893/// }
5894/// ```
5895///
5896/// [safety conditions]: trait@IntoBytes#safety
5897///
5898/// # Error Messages
5899///
5900/// On Rust toolchains prior to 1.78.0, due to the way that the custom derive
5901/// for `IntoBytes` is implemented, you may get an error like this:
5902///
5903/// ```text
5904/// error[E0277]: the trait bound `(): PaddingFree<Foo, true>` is not satisfied
5905///   --> lib.rs:23:10
5906///    |
5907///  1 | #[derive(IntoBytes)]
5908///    |          ^^^^^^^^^ the trait `PaddingFree<Foo, true>` is not implemented for `()`
5909///    |
5910///    = help: the following implementations were found:
5911///                   <() as PaddingFree<T, false>>
5912/// ```
5913///
5914/// This error indicates that the type being annotated has padding bytes, which
5915/// is illegal for `IntoBytes` types. Consider reducing the alignment of some
5916/// fields by using types in the [`byteorder`] module, wrapping field types in
5917/// [`Unalign`], adding explicit struct fields where those padding bytes would
5918/// be, or using `#[repr(packed)]`. See the Rust Reference's page on [type
5919/// layout] for more information about type layout and padding.
5920///
5921/// [type layout]: https://doc.rust-lang.org/reference/type-layout.html
5922///
5923/// # Unions
5924///
5925/// Currently, union bit validity is [up in the air][union-validity], and so
5926/// zerocopy does not support `#[derive(IntoBytes)]` on unions by default.
5927/// However, implementing `IntoBytes` on a union type is likely sound on all
5928/// existing Rust toolchains - it's just that it may become unsound in the
5929/// future. You can opt-in to `#[derive(IntoBytes)]` support on unions by
5930/// passing the unstable `zerocopy_derive_union_into_bytes` cfg:
5931///
5932/// ```shell
5933/// $ RUSTFLAGS='--cfg zerocopy_derive_union_into_bytes' cargo build
5934/// ```
5935///
5936/// However, it is your responsibility to ensure that this derive is sound on
5937/// the specific versions of the Rust toolchain you are using! We make no
5938/// stability or soundness guarantees regarding this cfg, and may remove it at
5939/// any point.
5940///
5941/// We are actively working with Rust to stabilize the necessary language
5942/// guarantees to support this in a forwards-compatible way, which will enable
5943/// us to remove the cfg gate. As part of this effort, we need to know how much
5944/// demand there is for this feature. If you would like to use `IntoBytes` on
5945/// unions, [please let us know][discussion].
5946///
5947/// [union-validity]: https://github.com/rust-lang/unsafe-code-guidelines/issues/438
5948/// [discussion]: https://github.com/google/zerocopy/discussions/1802
5949///
5950/// # Analysis
5951///
5952/// *This section describes, roughly, the analysis performed by this derive to
5953/// determine whether it is sound to implement `IntoBytes` for a given type.
5954/// Unless you are modifying the implementation of this derive, or attempting to
5955/// manually implement `IntoBytes` for a type yourself, you don't need to read
5956/// this section.*
5957///
5958/// If a type has the following properties, then this derive can implement
5959/// `IntoBytes` for that type:
5960///
5961/// - If the type is a struct, its fields must be [`IntoBytes`]. Additionally:
5962///     - if the type is `repr(transparent)` or `repr(packed)`, it is
5963///       [`IntoBytes`] if its fields are [`IntoBytes`]; else,
5964///     - if the type is `repr(C)` with at most one field, it is [`IntoBytes`]
5965///       if its field is [`IntoBytes`]; else,
5966///     - if the type has no generic parameters, it is [`IntoBytes`] if the type
5967///       is sized and has no padding bytes; else,
5968///     - if the type is `repr(C)` without an `align(N)` modifier for `N > 1`
5969///       (it may have `align(1)` or `packed(N)`), and every field is `T`,
5970///       `[T; N]`, or a final `[T]` for the same type parameter `T`, it is
5971///       [`IntoBytes`]; else,
5972///     - if the type is `repr(C)`, its fields must be [`Unaligned`].
5973/// - If the type is an enum:
5974///   - It must have a defined representation (`repr`s `C`, `u8`, `u16`, `u32`,
5975///     `u64`, `usize`, `i8`, `i16`, `i32`, `i64`, or `isize`).
5976///   - It must have no padding bytes.
5977///   - Its fields must be [`IntoBytes`].
5978///
5979/// This analysis is subject to change. Unsafe code may *only* rely on the
5980/// documented [safety conditions] of `FromBytes`, and must *not* rely on the
5981/// implementation details of this derive.
5982///
5983/// [Rust Reference]: https://doc.rust-lang.org/reference/type-layout.html
5984#[cfg(any(feature = "derive", test))]
5985#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
5986pub use zerocopy_derive::IntoBytes;
5987
5988/// Types that can be converted to an immutable slice of initialized bytes.
5989///
5990/// Any `IntoBytes` type can be converted to a slice of initialized bytes of the
5991/// same size. This is useful for efficiently serializing structured data as raw
5992/// bytes.
5993///
5994/// # Implementation
5995///
5996/// **Do not implement this trait yourself!** Instead, use
5997/// [`#[derive(IntoBytes)]`][derive]; e.g.:
5998///
5999/// ```
6000/// # use zerocopy_derive::IntoBytes;
6001/// #[derive(IntoBytes)]
6002/// #[repr(C)]
6003/// struct MyStruct {
6004/// # /*
6005///     ...
6006/// # */
6007/// }
6008///
6009/// #[derive(IntoBytes)]
6010/// #[repr(u8)]
6011/// enum MyEnum {
6012/// #   Variant0,
6013/// # /*
6014///     ...
6015/// # */
6016/// }
6017/// ```
6018///
6019/// This derive performs a sophisticated, compile-time safety analysis to
6020/// determine whether a type is `IntoBytes`. See the [derive
6021/// documentation][derive] for guidance on how to interpret error messages
6022/// produced by the derive's analysis.
6023///
6024/// # Safety
6025///
6026/// *This section describes what is required in order for `T: IntoBytes`, and
6027/// what unsafe code may assume of such types. If you don't plan on implementing
6028/// `IntoBytes` manually, and you don't plan on writing unsafe code that
6029/// operates on `IntoBytes` types, then you don't need to read this section.*
6030///
6031/// If `T: IntoBytes`, then unsafe code may assume that it is sound to treat any
6032/// `t: T` as an immutable `[u8]` of length `size_of_val(t)`. If a type is
6033/// marked as `IntoBytes` which violates this contract, it may cause undefined
6034/// behavior.
6035///
6036/// `#[derive(IntoBytes)]` only permits [types which satisfy these
6037/// requirements][derive-analysis].
6038///
6039#[cfg_attr(
6040    feature = "derive",
6041    doc = "[derive]: zerocopy_derive::IntoBytes",
6042    doc = "[derive-analysis]: zerocopy_derive::IntoBytes#analysis"
6043)]
6044#[cfg_attr(
6045    not(feature = "derive"),
6046    doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.IntoBytes.html"),
6047    doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.IntoBytes.html#analysis"),
6048)]
6049#[cfg_attr(
6050    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
6051    diagnostic::on_unimplemented(note = "Consider adding `#[derive(IntoBytes)]` to `{Self}`")
6052)]
6053pub unsafe trait IntoBytes {
6054    // The `Self: Sized` bound makes it so that this function doesn't prevent
6055    // `IntoBytes` from being object safe. Note that other `IntoBytes` methods
6056    // prevent object safety, but those provide a benefit in exchange for object
6057    // safety. If at some point we remove those methods, change their type
6058    // signatures, or move them out of this trait so that `IntoBytes` is object
6059    // safe again, it's important that this function not prevent object safety.
6060    #[doc(hidden)]
6061    fn only_derive_is_allowed_to_implement_this_trait()
6062    where
6063        Self: Sized;
6064
6065    /// Gets the bytes of this value.
6066    ///
6067    /// # Examples
6068    ///
6069    /// ```
6070    /// use zerocopy::IntoBytes;
6071    /// # use zerocopy_derive::*;
6072    ///
6073    /// #[derive(IntoBytes, Immutable)]
6074    /// #[repr(C)]
6075    /// struct PacketHeader {
6076    ///     src_port: [u8; 2],
6077    ///     dst_port: [u8; 2],
6078    ///     length: [u8; 2],
6079    ///     checksum: [u8; 2],
6080    /// }
6081    ///
6082    /// let header = PacketHeader {
6083    ///     src_port: [0, 1],
6084    ///     dst_port: [2, 3],
6085    ///     length: [4, 5],
6086    ///     checksum: [6, 7],
6087    /// };
6088    ///
6089    /// let bytes = header.as_bytes();
6090    ///
6091    /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]);
6092    /// ```
6093    ///
6094    #[doc = codegen_section!(
6095        header = "h5",
6096        bench = "as_bytes",
6097        format = "coco",
6098        arity = 2,
6099        [
6100            open
6101            @index 1
6102            @title "Sized"
6103            @variant "static_size"
6104        ],
6105        [
6106            @index 2
6107            @title "Unsized"
6108            @variant "dynamic_size"
6109        ]
6110    )]
6111    #[must_use = "has no side effects"]
6112    #[inline(always)]
6113    fn as_bytes(&self) -> &[u8]
6114    where
6115        Self: Immutable,
6116    {
6117        // Note that this method does not have a `Self: Sized` bound;
6118        // `size_of_val` works for unsized values too.
6119        let len = mem::size_of_val(self);
6120        let slf: *const Self = self;
6121
6122        // SAFETY:
6123        // - `slf.cast::<u8>()` is valid for reads for `len * size_of::<u8>()`
6124        //   many bytes because...
6125        //   - `slf` is the same pointer as `self`, and `self` is a reference
6126        //     which points to an object whose size is `len`. Thus...
6127        //     - The entire region of `len` bytes starting at `slf` is contained
6128        //       within a single allocation.
6129        //     - `slf` is non-null.
6130        //   - `slf` is trivially aligned to `align_of::<u8>() == 1`.
6131        // - `Self: IntoBytes` ensures that all of the bytes of `slf` are
6132        //   initialized.
6133        // - Since `slf` is derived from `self`, and `self` is an immutable
6134        //   reference, the only other references to this memory region that
6135        //   could exist are other immutable references, which by `Self:
6136        //   Immutable` don't permit mutation.
6137        // - The total size of the resulting slice is no larger than
6138        //   `isize::MAX` because no allocation produced by safe code can be
6139        //   larger than `isize::MAX`.
6140        //
6141        // FIXME(#429): Add references to docs and quotes.
6142        unsafe { slice::from_raw_parts(slf.cast::<u8>(), len) }
6143    }
6144
6145    /// Gets the bytes of this value mutably.
6146    ///
6147    /// # Examples
6148    ///
6149    /// ```
6150    /// use zerocopy::IntoBytes;
6151    /// # use zerocopy_derive::*;
6152    ///
6153    /// # #[derive(Eq, PartialEq, Debug)]
6154    /// #[derive(FromBytes, IntoBytes, Immutable)]
6155    /// #[repr(C)]
6156    /// struct PacketHeader {
6157    ///     src_port: [u8; 2],
6158    ///     dst_port: [u8; 2],
6159    ///     length: [u8; 2],
6160    ///     checksum: [u8; 2],
6161    /// }
6162    ///
6163    /// let mut header = PacketHeader {
6164    ///     src_port: [0, 1],
6165    ///     dst_port: [2, 3],
6166    ///     length: [4, 5],
6167    ///     checksum: [6, 7],
6168    /// };
6169    ///
6170    /// let bytes = header.as_mut_bytes();
6171    ///
6172    /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]);
6173    ///
6174    /// bytes.reverse();
6175    ///
6176    /// assert_eq!(header, PacketHeader {
6177    ///     src_port: [7, 6],
6178    ///     dst_port: [5, 4],
6179    ///     length: [3, 2],
6180    ///     checksum: [1, 0],
6181    /// });
6182    /// ```
6183    ///
6184    #[doc = codegen_section!(
6185        header = "h5",
6186        name = "as_mut_bytes",
6187        /// See [`IntoBytes::as_bytes`](#method.as_bytes.codegen).
6188    )]
6189    #[must_use = "has no side effects"]
6190    #[inline(always)]
6191    fn as_mut_bytes(&mut self) -> &mut [u8]
6192    where
6193        Self: FromBytes,
6194    {
6195        // Note that this method does not have a `Self: Sized` bound;
6196        // `size_of_val` works for unsized values too.
6197        let len = mem::size_of_val(self);
6198        let slf: *mut Self = self;
6199
6200        // SAFETY:
6201        // - `slf.cast::<u8>()` is valid for reads and writes for `len *
6202        //   size_of::<u8>()` many bytes because...
6203        //   - `slf` is the same pointer as `self`, and `self` is a reference
6204        //     which points to an object whose size is `len`. Thus...
6205        //     - The entire region of `len` bytes starting at `slf` is contained
6206        //       within a single allocation.
6207        //     - `slf` is non-null.
6208        //   - `slf` is trivially aligned to `align_of::<u8>() == 1`.
6209        // - `Self: IntoBytes` ensures that all of the bytes of `slf` are
6210        //   initialized.
6211        // - `Self: FromBytes` ensures that no write to this memory region
6212        //   could result in it containing an invalid `Self`.
6213        // - Since `slf` is derived from `self`, and `self` is a mutable
6214        //   reference, no other references to this memory region can exist.
6215        // - The total size of the resulting slice is no larger than
6216        //   `isize::MAX` because no allocation produced by safe code can be
6217        //   larger than `isize::MAX`.
6218        //
6219        // FIXME(#429): Add references to docs and quotes.
6220        unsafe { slice::from_raw_parts_mut(slf.cast::<u8>(), len) }
6221    }
6222
6223    /// Writes a copy of `self` to `dst`.
6224    ///
6225    /// If `dst.len() != size_of_val(self)`, `write_to` returns `Err`.
6226    ///
6227    /// # Examples
6228    ///
6229    /// ```
6230    /// use zerocopy::IntoBytes;
6231    /// # use zerocopy_derive::*;
6232    ///
6233    /// #[derive(IntoBytes, Immutable)]
6234    /// #[repr(C)]
6235    /// struct PacketHeader {
6236    ///     src_port: [u8; 2],
6237    ///     dst_port: [u8; 2],
6238    ///     length: [u8; 2],
6239    ///     checksum: [u8; 2],
6240    /// }
6241    ///
6242    /// let header = PacketHeader {
6243    ///     src_port: [0, 1],
6244    ///     dst_port: [2, 3],
6245    ///     length: [4, 5],
6246    ///     checksum: [6, 7],
6247    /// };
6248    ///
6249    /// let mut bytes = [0, 0, 0, 0, 0, 0, 0, 0];
6250    ///
6251    /// header.write_to(&mut bytes[..]);
6252    ///
6253    /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]);
6254    /// ```
6255    ///
6256    /// If too many or too few target bytes are provided, `write_to` returns
6257    /// `Err` and leaves the target bytes unmodified:
6258    ///
6259    /// ```
6260    /// # use zerocopy::IntoBytes;
6261    /// # let header = u128::MAX;
6262    /// let mut excessive_bytes = &mut [0u8; 128][..];
6263    ///
6264    /// let write_result = header.write_to(excessive_bytes);
6265    ///
6266    /// assert!(write_result.is_err());
6267    /// assert_eq!(excessive_bytes, [0u8; 128]);
6268    /// ```
6269    ///
6270    #[doc = codegen_section!(
6271        header = "h5",
6272        bench = "write_to",
6273        format = "coco",
6274        arity = 2,
6275        [
6276            open
6277            @index 1
6278            @title "Sized"
6279            @variant "static_size"
6280        ],
6281        [
6282            @index 2
6283            @title "Unsized"
6284            @variant "dynamic_size"
6285        ]
6286    )]
6287    #[must_use = "callers should check the return value to see if the operation succeeded"]
6288    #[cfg_attr(zerocopy_inline_always, inline(always))]
6289    #[cfg_attr(not(zerocopy_inline_always), inline)]
6290    #[allow(clippy::mut_from_ref)] // False positive: `&self -> &mut [u8]`
6291    fn write_to(&self, dst: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
6292    where
6293        Self: Immutable,
6294    {
6295        let src = self.as_bytes();
6296        if dst.len() == src.len() {
6297            // SAFETY: Within this branch of the conditional, we have ensured
6298            // that `dst.len()` is equal to `src.len()`. Neither the size of the
6299            // source nor the size of the destination change between the above
6300            // size check and the invocation of `copy_unchecked`.
6301            unsafe { util::copy_unchecked(src, dst) }
6302            Ok(())
6303        } else {
6304            Err(SizeError::new(self))
6305        }
6306    }
6307
6308    /// Writes a copy of `self` to the prefix of `dst`.
6309    ///
6310    /// `write_to_prefix` writes `self` to the first `size_of_val(self)` bytes
6311    /// of `dst`. If `dst.len() < size_of_val(self)`, it returns `Err`.
6312    ///
6313    /// # Examples
6314    ///
6315    /// ```
6316    /// use zerocopy::IntoBytes;
6317    /// # use zerocopy_derive::*;
6318    ///
6319    /// #[derive(IntoBytes, Immutable)]
6320    /// #[repr(C)]
6321    /// struct PacketHeader {
6322    ///     src_port: [u8; 2],
6323    ///     dst_port: [u8; 2],
6324    ///     length: [u8; 2],
6325    ///     checksum: [u8; 2],
6326    /// }
6327    ///
6328    /// let header = PacketHeader {
6329    ///     src_port: [0, 1],
6330    ///     dst_port: [2, 3],
6331    ///     length: [4, 5],
6332    ///     checksum: [6, 7],
6333    /// };
6334    ///
6335    /// let mut bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
6336    ///
6337    /// header.write_to_prefix(&mut bytes[..]);
6338    ///
6339    /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7, 0, 0]);
6340    /// ```
6341    ///
6342    /// If insufficient target bytes are provided, `write_to_prefix` returns
6343    /// `Err` and leaves the target bytes unmodified:
6344    ///
6345    /// ```
6346    /// # use zerocopy::IntoBytes;
6347    /// # let header = u128::MAX;
6348    /// let mut insufficient_bytes = &mut [0, 0][..];
6349    ///
6350    /// let write_result = header.write_to_suffix(insufficient_bytes);
6351    ///
6352    /// assert!(write_result.is_err());
6353    /// assert_eq!(insufficient_bytes, [0, 0]);
6354    /// ```
6355    ///
6356    #[doc = codegen_section!(
6357        header = "h5",
6358        bench = "write_to_prefix",
6359        format = "coco",
6360        arity = 2,
6361        [
6362            open
6363            @index 1
6364            @title "Sized"
6365            @variant "static_size"
6366        ],
6367        [
6368            @index 2
6369            @title "Unsized"
6370            @variant "dynamic_size"
6371        ]
6372    )]
6373    #[must_use = "callers should check the return value to see if the operation succeeded"]
6374    #[cfg_attr(zerocopy_inline_always, inline(always))]
6375    #[cfg_attr(not(zerocopy_inline_always), inline)]
6376    #[allow(clippy::mut_from_ref)] // False positive: `&self -> &mut [u8]`
6377    fn write_to_prefix(&self, dst: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
6378    where
6379        Self: Immutable,
6380    {
6381        let src = self.as_bytes();
6382        match dst.get_mut(..src.len()) {
6383            Some(dst) => {
6384                // SAFETY: Within this branch of the `match`, we have ensured
6385                // through fallible subslicing that `dst.len()` is equal to
6386                // `src.len()`. Neither the size of the source nor the size of
6387                // the destination change between the above subslicing operation
6388                // and the invocation of `copy_unchecked`.
6389                unsafe { util::copy_unchecked(src, dst) }
6390                Ok(())
6391            }
6392            None => Err(SizeError::new(self)),
6393        }
6394    }
6395
6396    /// Writes a copy of `self` to the suffix of `dst`.
6397    ///
6398    /// `write_to_suffix` writes `self` to the last `size_of_val(self)` bytes of
6399    /// `dst`. If `dst.len() < size_of_val(self)`, it returns `Err`.
6400    ///
6401    /// # Examples
6402    ///
6403    /// ```
6404    /// use zerocopy::IntoBytes;
6405    /// # use zerocopy_derive::*;
6406    ///
6407    /// #[derive(IntoBytes, Immutable)]
6408    /// #[repr(C)]
6409    /// struct PacketHeader {
6410    ///     src_port: [u8; 2],
6411    ///     dst_port: [u8; 2],
6412    ///     length: [u8; 2],
6413    ///     checksum: [u8; 2],
6414    /// }
6415    ///
6416    /// let header = PacketHeader {
6417    ///     src_port: [0, 1],
6418    ///     dst_port: [2, 3],
6419    ///     length: [4, 5],
6420    ///     checksum: [6, 7],
6421    /// };
6422    ///
6423    /// let mut bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
6424    ///
6425    /// header.write_to_suffix(&mut bytes[..]);
6426    ///
6427    /// assert_eq!(bytes, [0, 0, 0, 1, 2, 3, 4, 5, 6, 7]);
6428    ///
6429    /// let mut insufficient_bytes = &mut [0, 0][..];
6430    ///
6431    /// let write_result = header.write_to_suffix(insufficient_bytes);
6432    ///
6433    /// assert!(write_result.is_err());
6434    /// assert_eq!(insufficient_bytes, [0, 0]);
6435    /// ```
6436    ///
6437    /// If insufficient target bytes are provided, `write_to_suffix` returns
6438    /// `Err` and leaves the target bytes unmodified:
6439    ///
6440    /// ```
6441    /// # use zerocopy::IntoBytes;
6442    /// # let header = u128::MAX;
6443    /// let mut insufficient_bytes = &mut [0, 0][..];
6444    ///
6445    /// let write_result = header.write_to_suffix(insufficient_bytes);
6446    ///
6447    /// assert!(write_result.is_err());
6448    /// assert_eq!(insufficient_bytes, [0, 0]);
6449    /// ```
6450    ///
6451    #[doc = codegen_section!(
6452        header = "h5",
6453        bench = "write_to_suffix",
6454        format = "coco",
6455        arity = 2,
6456        [
6457            open
6458            @index 1
6459            @title "Sized"
6460            @variant "static_size"
6461        ],
6462        [
6463            @index 2
6464            @title "Unsized"
6465            @variant "dynamic_size"
6466        ]
6467    )]
6468    #[must_use = "callers should check the return value to see if the operation succeeded"]
6469    #[cfg_attr(zerocopy_inline_always, inline(always))]
6470    #[cfg_attr(not(zerocopy_inline_always), inline)]
6471    #[allow(clippy::mut_from_ref)] // False positive: `&self -> &mut [u8]`
6472    fn write_to_suffix(&self, dst: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
6473    where
6474        Self: Immutable,
6475    {
6476        let src = self.as_bytes();
6477        let start = if let Some(start) = dst.len().checked_sub(src.len()) {
6478            start
6479        } else {
6480            return Err(SizeError::new(self));
6481        };
6482        let dst = if let Some(dst) = dst.get_mut(start..) {
6483            dst
6484        } else {
6485            // get_mut() should never return None here. We return a `SizeError`
6486            // rather than .unwrap() because in the event the branch is not
6487            // optimized away, returning a value is generally lighter-weight
6488            // than panicking.
6489            return Err(SizeError::new(self));
6490        };
6491        // SAFETY: Through fallible subslicing of `dst`, we have ensured that
6492        // `dst.len()` is equal to `src.len()`. Neither the size of the source
6493        // nor the size of the destination change between the above subslicing
6494        // operation and the invocation of `copy_unchecked`.
6495        unsafe {
6496            util::copy_unchecked(src, dst);
6497        }
6498        Ok(())
6499    }
6500
6501    /// Writes a copy of `self` to an `io::Write`.
6502    ///
6503    /// This is a shorthand for `dst.write_all(self.as_bytes())`, and is useful
6504    /// for interfacing with operating system byte sinks (files, sockets, etc.).
6505    ///
6506    /// # Examples
6507    ///
6508    /// ```no_run
6509    /// use zerocopy::{byteorder::big_endian::U16, FromBytes, IntoBytes};
6510    /// use std::fs::File;
6511    /// # use zerocopy_derive::*;
6512    ///
6513    /// #[derive(FromBytes, IntoBytes, Immutable, KnownLayout)]
6514    /// #[repr(C, packed)]
6515    /// struct GrayscaleImage {
6516    ///     height: U16,
6517    ///     width: U16,
6518    ///     pixels: [U16],
6519    /// }
6520    ///
6521    /// let image = GrayscaleImage::ref_from_bytes(&[0, 0, 0, 0][..]).unwrap();
6522    /// let mut file = File::create("image.bin").unwrap();
6523    /// image.write_to_io(&mut file).unwrap();
6524    /// ```
6525    ///
6526    /// If the write fails, `write_to_io` returns `Err` and a partial write may
6527    /// have occurred; e.g.:
6528    ///
6529    /// ```
6530    /// # use zerocopy::IntoBytes;
6531    ///
6532    /// let src = u128::MAX;
6533    /// let mut dst = [0u8; 2];
6534    ///
6535    /// let write_result = src.write_to_io(&mut dst[..]);
6536    ///
6537    /// assert!(write_result.is_err());
6538    /// assert_eq!(dst, [255, 255]);
6539    /// ```
6540    #[cfg(feature = "std")]
6541    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
6542    #[inline(always)]
6543    fn write_to_io<W>(&self, mut dst: W) -> io::Result<()>
6544    where
6545        Self: Immutable,
6546        W: io::Write,
6547    {
6548        dst.write_all(self.as_bytes())
6549    }
6550
6551    #[deprecated(since = "0.8.0", note = "`IntoBytes::as_bytes_mut` was renamed to `as_mut_bytes`")]
6552    #[doc(hidden)]
6553    #[inline]
6554    fn as_bytes_mut(&mut self) -> &mut [u8]
6555    where
6556        Self: FromBytes,
6557    {
6558        self.as_mut_bytes()
6559    }
6560}
6561
6562/// Analyzes whether a type is [`Unaligned`].
6563///
6564/// This derive analyzes, at compile time, whether the annotated type satisfies
6565/// the [safety conditions] of `Unaligned` and implements `Unaligned` if it is
6566/// sound to do so. This derive can be applied to structs, enums, and unions;
6567/// e.g.:
6568///
6569/// ```
6570/// # use zerocopy_derive::Unaligned;
6571/// #[derive(Unaligned)]
6572/// #[repr(C)]
6573/// struct MyStruct {
6574/// # /*
6575///     ...
6576/// # */
6577/// }
6578///
6579/// #[derive(Unaligned)]
6580/// #[repr(u8)]
6581/// enum MyEnum {
6582/// #   Variant0,
6583/// # /*
6584///     ...
6585/// # */
6586/// }
6587///
6588/// #[derive(Unaligned)]
6589/// #[repr(packed)]
6590/// union MyUnion {
6591/// #   variant: u8,
6592/// # /*
6593///     ...
6594/// # */
6595/// }
6596/// ```
6597///
6598/// # Analysis
6599///
6600/// *This section describes, roughly, the analysis performed by this derive to
6601/// determine whether it is sound to implement `Unaligned` for a given type.
6602/// Unless you are modifying the implementation of this derive, or attempting to
6603/// manually implement `Unaligned` for a type yourself, you don't need to read
6604/// this section.*
6605///
6606/// If a type has the following properties, then this derive can implement
6607/// `Unaligned` for that type:
6608///
6609/// - If the type is a struct or union:
6610///   - If `repr(align(N))` is provided, `N` must equal 1.
6611///   - If the type is `repr(C)` or `repr(transparent)`, all fields must be
6612///     [`Unaligned`].
6613///   - If the type is not `repr(C)` or `repr(transparent)`, it must be
6614///     `repr(packed)` or `repr(packed(1))`.
6615/// - If the type is an enum:
6616///   - If `repr(align(N))` is provided, `N` must equal 1.
6617///   - It must be a field-less enum (meaning that all variants have no fields).
6618///   - It must be `repr(i8)` or `repr(u8)`.
6619///
6620/// [safety conditions]: trait@Unaligned#safety
6621#[cfg(any(feature = "derive", test))]
6622#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
6623pub use zerocopy_derive::Unaligned;
6624
6625/// Types with no alignment requirement.
6626///
6627/// If `T: Unaligned`, then `align_of::<T>() == 1`.
6628///
6629/// # Implementation
6630///
6631/// **Do not implement this trait yourself!** Instead, use
6632/// [`#[derive(Unaligned)]`][derive]; e.g.:
6633///
6634/// ```
6635/// # use zerocopy_derive::Unaligned;
6636/// #[derive(Unaligned)]
6637/// #[repr(C)]
6638/// struct MyStruct {
6639/// # /*
6640///     ...
6641/// # */
6642/// }
6643///
6644/// #[derive(Unaligned)]
6645/// #[repr(u8)]
6646/// enum MyEnum {
6647/// #   Variant0,
6648/// # /*
6649///     ...
6650/// # */
6651/// }
6652///
6653/// #[derive(Unaligned)]
6654/// #[repr(packed)]
6655/// union MyUnion {
6656/// #   variant: u8,
6657/// # /*
6658///     ...
6659/// # */
6660/// }
6661/// ```
6662///
6663/// This derive performs a sophisticated, compile-time safety analysis to
6664/// determine whether a type is `Unaligned`.
6665///
6666/// # Safety
6667///
6668/// *This section describes what is required in order for `T: Unaligned`, and
6669/// what unsafe code may assume of such types. If you don't plan on implementing
6670/// `Unaligned` manually, and you don't plan on writing unsafe code that
6671/// operates on `Unaligned` types, then you don't need to read this section.*
6672///
6673/// If `T: Unaligned`, then unsafe code may assume that it is sound to produce a
6674/// reference to `T` at any memory location regardless of alignment. If a type
6675/// is marked as `Unaligned` which violates this contract, it may cause
6676/// undefined behavior.
6677///
6678/// `#[derive(Unaligned)]` only permits [types which satisfy these
6679/// requirements][derive-analysis].
6680///
6681#[cfg_attr(
6682    feature = "derive",
6683    doc = "[derive]: zerocopy_derive::Unaligned",
6684    doc = "[derive-analysis]: zerocopy_derive::Unaligned#analysis"
6685)]
6686#[cfg_attr(
6687    not(feature = "derive"),
6688    doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Unaligned.html"),
6689    doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Unaligned.html#analysis"),
6690)]
6691#[cfg_attr(
6692    not(no_zerocopy_diagnostic_on_unimplemented_1_78_0),
6693    diagnostic::on_unimplemented(note = "Consider adding `#[derive(Unaligned)]` to `{Self}`")
6694)]
6695pub unsafe trait Unaligned {
6696    // The `Self: Sized` bound makes it so that `Unaligned` is still object
6697    // safe.
6698    #[doc(hidden)]
6699    fn only_derive_is_allowed_to_implement_this_trait()
6700    where
6701        Self: Sized;
6702}
6703
6704/// Derives optimized [`PartialEq`] and [`Eq`] implementations.
6705///
6706/// This derive can be applied to structs and enums implementing both
6707/// [`Immutable`] and [`IntoBytes`]; e.g.:
6708///
6709/// ```
6710/// # use zerocopy_derive::{ByteEq, Immutable, IntoBytes};
6711/// #[derive(ByteEq, Immutable, IntoBytes)]
6712/// #[repr(C)]
6713/// struct MyStruct {
6714/// # /*
6715///     ...
6716/// # */
6717/// }
6718///
6719/// #[derive(ByteEq, Immutable, IntoBytes)]
6720/// #[repr(u8)]
6721/// enum MyEnum {
6722/// #   Variant,
6723/// # /*
6724///     ...
6725/// # */
6726/// }
6727/// ```
6728///
6729/// The standard library's [`derive(Eq, PartialEq)`][derive@PartialEq] computes
6730/// equality by individually comparing each field. Instead, the implementation
6731/// of [`PartialEq::eq`] emitted by `derive(ByteHash)` converts the entirety of
6732/// `self` and `other` to byte slices and compares those slices for equality.
6733/// This may have performance advantages.
6734#[cfg(any(feature = "derive", test))]
6735#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
6736pub use zerocopy_derive::ByteEq;
6737/// Derives an optimized [`Hash`] implementation.
6738///
6739/// This derive can be applied to structs and enums implementing both
6740/// [`Immutable`] and [`IntoBytes`]; e.g.:
6741///
6742/// ```
6743/// # use zerocopy_derive::{ByteHash, Immutable, IntoBytes};
6744/// #[derive(ByteHash, Immutable, IntoBytes)]
6745/// #[repr(C)]
6746/// struct MyStruct {
6747/// # /*
6748///     ...
6749/// # */
6750/// }
6751///
6752/// #[derive(ByteHash, Immutable, IntoBytes)]
6753/// #[repr(u8)]
6754/// enum MyEnum {
6755/// #   Variant,
6756/// # /*
6757///     ...
6758/// # */
6759/// }
6760/// ```
6761///
6762/// The standard library's [`derive(Hash)`][derive@Hash] produces hashes by
6763/// individually hashing each field and combining the results. Instead, the
6764/// implementations of [`Hash::hash()`] and [`Hash::hash_slice()`] generated by
6765/// `derive(ByteHash)` convert the entirety of `self` to a byte slice and hashes
6766/// it in a single call to [`Hasher::write()`]. This may have performance
6767/// advantages.
6768///
6769/// [`Hash`]: core::hash::Hash
6770/// [`Hash::hash()`]: core::hash::Hash::hash()
6771/// [`Hash::hash_slice()`]: core::hash::Hash::hash_slice()
6772#[cfg(any(feature = "derive", test))]
6773#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
6774pub use zerocopy_derive::ByteHash;
6775/// Implements [`SplitAt`].
6776///
6777/// This derive can be applied to structs; e.g.:
6778///
6779/// ```
6780/// # use zerocopy_derive::{ByteEq, Immutable, IntoBytes};
6781/// #[derive(ByteEq, Immutable, IntoBytes)]
6782/// #[repr(C)]
6783/// struct MyStruct {
6784/// # /*
6785///     ...
6786/// # */
6787/// }
6788/// ```
6789#[cfg(any(feature = "derive", test))]
6790#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
6791pub use zerocopy_derive::SplitAt;
6792
6793#[cfg(feature = "alloc")]
6794#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
6795#[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
6796mod alloc_support {
6797    use super::*;
6798
6799    /// Extends a `Vec<T>` by pushing `additional` new items onto the end of the
6800    /// vector. The new items are initialized with zeros.
6801    #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
6802    #[doc(hidden)]
6803    #[deprecated(since = "0.8.0", note = "moved to `FromZeros`")]
6804    #[inline(always)]
6805    pub fn extend_vec_zeroed<T: FromZeros>(
6806        v: &mut Vec<T>,
6807        additional: usize,
6808    ) -> Result<(), AllocError> {
6809        <T as FromZeros>::extend_vec_zeroed(v, additional)
6810    }
6811
6812    /// Inserts `additional` new items into `Vec<T>` at `position`. The new
6813    /// items are initialized with zeros.
6814    ///
6815    /// # Panics
6816    ///
6817    /// Panics if `position > v.len()`.
6818    #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
6819    #[doc(hidden)]
6820    #[deprecated(since = "0.8.0", note = "moved to `FromZeros`")]
6821    #[inline(always)]
6822    pub fn insert_vec_zeroed<T: FromZeros>(
6823        v: &mut Vec<T>,
6824        position: usize,
6825        additional: usize,
6826    ) -> Result<(), AllocError> {
6827        <T as FromZeros>::insert_vec_zeroed(v, position, additional)
6828    }
6829}
6830
6831#[cfg(feature = "alloc")]
6832#[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
6833#[doc(hidden)]
6834pub use alloc_support::*;
6835
6836#[cfg(test)]
6837#[allow(clippy::assertions_on_result_states, clippy::unreadable_literal)]
6838mod tests {
6839    use static_assertions::assert_impl_all;
6840
6841    use super::*;
6842    use crate::util::testutil::*;
6843
6844    // An unsized type.
6845    //
6846    // This is used to test the custom derives of our traits. The `[u8]` type
6847    // gets a hand-rolled impl, so it doesn't exercise our custom derives.
6848    #[derive(Debug, Eq, PartialEq, FromBytes, IntoBytes, Unaligned, Immutable)]
6849    #[repr(transparent)]
6850    struct Unsized([u8]);
6851
6852    impl Unsized {
6853        fn from_mut_slice(slc: &mut [u8]) -> &mut Unsized {
6854            // SAFETY: This *probably* sound - since the layouts of `[u8]` and
6855            // `Unsized` are the same, so are the layouts of `&mut [u8]` and
6856            // `&mut Unsized`. [1] Even if it turns out that this isn't actually
6857            // guaranteed by the language spec, we can just change this since
6858            // it's in test code.
6859            //
6860            // [1] https://github.com/rust-lang/unsafe-code-guidelines/issues/375
6861            unsafe { mem::transmute(slc) }
6862        }
6863    }
6864
6865    // These types exercise a nested slice DST whose inner trailing-padding
6866    // operation cannot be flattened into the alignment of the packed outer
6867    // type. For `NestedPackedDstOuter<[u8]>`, the trailing slice begins at
6868    // offset 7, but the size for `elems` elements is
6869    // `2 + round_up(5 + elems, 4)`.
6870    //
6871    // The Reference rejects directly placing an alignment-4 field in a
6872    // `repr(packed(2))` type. Rust currently accepts this construction through
6873    // generic indirection. So long as Rust accepts it, this test deliberately
6874    // treats its layout as following the otherwise-applicable `repr(C)` and
6875    // `repr(packed)` rules.
6876    #[derive(FromBytes, Immutable, KnownLayout)]
6877    #[repr(C, align(4))]
6878    struct NestedPackedDstWord([u8; 4]);
6879
6880    #[derive(FromBytes, Immutable, KnownLayout)]
6881    #[repr(C)]
6882    struct NestedPackedDstInner<T: ?Sized> {
6883        a: NestedPackedDstWord,
6884        b: u8,
6885        tail: T,
6886    }
6887
6888    #[derive(FromBytes, Immutable, KnownLayout)]
6889    #[repr(C, packed(2))]
6890    struct NestedPackedDstOuter<T: ?Sized> {
6891        z: u8,
6892        inner: ManuallyDrop<NestedPackedDstInner<T>>,
6893    }
6894
6895    #[repr(C, align(2))]
6896    struct Align2<T>(T);
6897
6898    #[test]
6899    fn test_known_layout() {
6900        // Test that `$ty` and `ManuallyDrop<$ty>` have the expected layout.
6901        // Test that `PhantomData<$ty>` has the same layout as `()` regardless
6902        // of `$ty`.
6903        macro_rules! test {
6904            ($ty:ty, $expect:expr) => {
6905                let expect = $expect;
6906                assert_eq!(<$ty as KnownLayout>::LAYOUT, expect);
6907                assert_eq!(<ManuallyDrop<$ty> as KnownLayout>::LAYOUT, expect);
6908                assert_eq!(<PhantomData<$ty> as KnownLayout>::LAYOUT, <() as KnownLayout>::LAYOUT);
6909            };
6910        }
6911
6912        let layout = |offset, align, trailing_slice_elem_size, statically_shallow_unpadded| {
6913            let align = NonZeroUsize::new(align).unwrap();
6914            let size_phase = offset % align;
6915            DstLayout {
6916                align,
6917                size_info: match trailing_slice_elem_size {
6918                    None => SizeInfo::Sized { size: offset },
6919                    Some(elem_size) => SizeInfo::SliceDst(TrailingSliceLayout {
6920                        offset,
6921                        elem_size,
6922                        size_base: offset - size_phase,
6923                        size_rounding_align_and_phase: RoundingAlignAndPhase::new(
6924                            align, size_phase,
6925                        ),
6926                    }),
6927                },
6928                statically_shallow_unpadded,
6929            }
6930        };
6931
6932        test!((), layout(0, 1, None, false));
6933        test!(u8, layout(1, 1, None, false));
6934        // Use `align_of` because `u64` alignment may be smaller than 8 on some
6935        // platforms.
6936        test!(u64, layout(8, mem::align_of::<u64>(), None, false));
6937        test!(AU64, layout(8, 8, None, false));
6938
6939        test!(Option<&'static ()>, usize::LAYOUT);
6940
6941        test!([()], layout(0, 1, Some(0), true));
6942        test!([u8], layout(0, 1, Some(1), true));
6943        test!(str, layout(0, 1, Some(1), true));
6944
6945        // Test `size_for_metadata_unchecked`
6946        // SAFETY: Sized types have empty metadata and fit in `usize`.
6947        assert_eq!(unsafe { <() as KnownLayout>::size_for_metadata_unchecked(()) }, 0);
6948        // SAFETY: Sized types have empty metadata and fit in `usize`.
6949        assert_eq!(unsafe { <u8 as KnownLayout>::size_for_metadata_unchecked(()) }, 1);
6950        // SAFETY: Sized types have empty metadata and fit in `usize`.
6951        assert_eq!(unsafe { <u64 as KnownLayout>::size_for_metadata_unchecked(()) }, 8);
6952        // SAFETY: 10 elements of `u8` (10 bytes) fit in `usize`.
6953        assert_eq!(unsafe { <[u8] as KnownLayout>::size_for_metadata_unchecked(10) }, 10);
6954        // SAFETY: 10 elements of `u16` (20 bytes) fit in `usize`.
6955        assert_eq!(unsafe { <[u16] as KnownLayout>::size_for_metadata_unchecked(10) }, 20);
6956        // SAFETY: 10 elements of `()` (0 bytes) fit in `usize`.
6957        assert_eq!(unsafe { <[()] as KnownLayout>::size_for_metadata_unchecked(10) }, 0);
6958        // SAFETY: `u8::LAYOUT` describes a sized type.
6959        assert_eq!(unsafe { ().size_for_metadata_unchecked(u8::LAYOUT) }, 1);
6960        // SAFETY: `<[u8]>::LAYOUT` describes a slice DST with 10 bytes fitting in `usize`.
6961        assert_eq!(unsafe { 10usize.size_for_metadata_unchecked(<[u8]>::LAYOUT) }, 10);
6962    }
6963
6964    #[test]
6965    fn test_known_layout_pointer_to_metadata() {
6966        fn test<T>(data: *mut T, elems: usize) {
6967            let ptr = ptr::slice_from_raw_parts_mut(data, elems);
6968            assert_eq!(<[T] as KnownLayout>::pointer_to_metadata(ptr), elems);
6969        }
6970
6971        for elems in [0, 1, usize::MAX] {
6972            test(ptr::null_mut::<u8>(), elems);
6973        }
6974
6975        test(NonNull::<u8>::dangling().as_ptr(), 0);
6976
6977        let mut bytes = [1, 2, 3];
6978        test(bytes.as_mut_ptr(), bytes.len());
6979        assert_eq!(bytes, [1, 2, 3]);
6980
6981        test(NonNull::<()>::dangling().as_ptr(), usize::MAX);
6982
6983        // Retaining and inspecting a raw pointer after freeing its allocation
6984        // is safe so long as the pointer is not dereferenced.
6985        let deallocated = {
6986            let mut byte = Box::new(0u8);
6987            let ptr: *mut u8 = &mut *byte;
6988            drop(byte);
6989            ptr
6990        };
6991        test(deallocated, 3);
6992
6993        // Metadata extraction requires neither element storage nor alignment
6994        // for `T`; it does not access the pointer's referent.
6995        test(NonNull::<u8>::dangling().as_ptr().cast::<u64>(), usize::MAX);
6996    }
6997
6998    #[cfg(feature = "derive")]
6999    #[test]
7000    fn test_known_layout_pointer_to_metadata_derive() {
7001        #[derive(KnownLayout)]
7002        #[repr(C)]
7003        struct Dst {
7004            prefix: u8,
7005            trailing: [u8],
7006        }
7007
7008        for elems in [0, 1, usize::MAX] {
7009            let ptr = ptr::slice_from_raw_parts_mut(ptr::null_mut::<u8>(), elems);
7010            #[allow(clippy::as_conversions)]
7011            let ptr = ptr as *mut Dst;
7012            assert_eq!(Dst::pointer_to_metadata(ptr), elems);
7013        }
7014    }
7015
7016    #[test]
7017    fn test_nested_packed_dst_layout() {
7018        fn assert_native_size<const N: usize>(expected: usize) {
7019            let value = NestedPackedDstOuter {
7020                z: 0,
7021                inner: ManuallyDrop::new(NestedPackedDstInner {
7022                    a: NestedPackedDstWord([0; 4]),
7023                    b: 0,
7024                    tail: [0; N],
7025                }),
7026            };
7027            let value: &NestedPackedDstOuter<[u8]> = &value;
7028            assert_eq!(mem::size_of_val(value), expected);
7029            assert_eq!(NestedPackedDstOuter::<[u8]>::size_for_metadata(N), Some(expected));
7030        }
7031
7032        assert_native_size::<0>(10);
7033        assert_native_size::<1>(10);
7034        assert_native_size::<2>(10);
7035        assert_native_size::<3>(10);
7036        assert_native_size::<4>(14);
7037        assert_native_size::<7>(14);
7038        assert_native_size::<8>(18);
7039
7040        let layout = NestedPackedDstOuter::<[u8]>::LAYOUT;
7041        assert_eq!(layout.align.get(), 2);
7042        assert!(layout.requires_dynamic_padding());
7043        assert_eq!(
7044            layout.size_info,
7045            SizeInfo::SliceDst(TrailingSliceLayout {
7046                offset: 7,
7047                elem_size: 1,
7048                size_base: 6,
7049                size_rounding_align_and_phase: RoundingAlignAndPhase::new(
7050                    NonZeroUsize::new(4).unwrap(),
7051                    1
7052                ),
7053            })
7054        );
7055
7056        // Eight bytes used to be incorrectly accepted for a zero-element
7057        // value. The actual Rust layout requires ten bytes.
7058        let short = Align2([0u8; 8]);
7059        assert!(NestedPackedDstOuter::<[u8]>::ref_from_bytes_with_elems(&short.0, 0).is_err());
7060        assert!(pointer::Ptr::from_ref(&short.0[..])
7061            .try_cast_into::<NestedPackedDstOuter<[u8]>, pointer::BecauseImmutable>(
7062                CastType::Prefix,
7063                Some(0),
7064            )
7065            .is_err());
7066
7067        let full = Align2([0, 0, 0, 0, 0, 0, 0, 0, b'S', b'!']);
7068        let value = NestedPackedDstOuter::<[u8]>::ref_from_bytes_with_elems(&full.0, 0).unwrap();
7069        assert_eq!(mem::size_of_val(value), 10);
7070
7071        // When metadata is inferred, lengths 0 through 3 all produce a
7072        // ten-byte object. Parsing chooses the largest trailing-slice length
7073        // which fits exactly.
7074        let inferred = NestedPackedDstOuter::<[u8]>::ref_from_bytes(&full.0).unwrap();
7075        assert_eq!(pointer::Ptr::from_ref(inferred).len(), 3);
7076
7077        // Trailing padding includes the inner type's padding, even when the
7078        // outer type's alignment is reduced by packing.
7079        let trailing_layout = trailing_slice_layout::<NestedPackedDstOuter<[u8]>>();
7080        for (elems, expected) in [(0, 3), (1, 2), (2, 1), (3, 0), (4, 3)] {
7081            assert_eq!(trailing_layout.padding_for_elems(elems), expected);
7082        }
7083    }
7084
7085    // Before Rust 1.76, rust-lang/rust#118537 caused `addr_of_mut!` to
7086    // miscompute the offset of an unsized field in a packed struct. The fix is
7087    // rust-lang/rust#118540. Keep the layout and parsing regression above on
7088    // all supported compilers, and gate only the projection regression which
7089    // necessarily exercises that independent compiler bug.
7090    #[rustversion::since(1.76.0)]
7091    #[test]
7092    fn test_nested_packed_dst_projection() {
7093        let full = Align2([0, 0, 0, 0, 0, 0, 0, 0, b'S', b'!']);
7094
7095        // The projected inner value occupies the final eight bytes of the full
7096        // ten-byte input, including the two sentinel bytes.
7097        let (value, rest) = pointer::Ptr::from_ref(&full.0[..])
7098            .try_cast_into::<NestedPackedDstOuter<[u8]>, pointer::BecauseImmutable>(
7099                CastType::Prefix,
7100                Some(0),
7101            )
7102            .unwrap();
7103        assert!(rest.as_ref().is_empty());
7104        let inner = value.project::<project_clients::TryFromBytesDerive, _, { STRUCT_VARIANT_ID }, { ident_id!(inner) }>().unwrap();
7105        assert_eq!(
7106            inner.as_bytes::<pointer::BecauseImmutable>().as_ref(),
7107            &[0, 0, 0, 0, 0, 0, b'S', b'!']
7108        );
7109    }
7110
7111    #[cfg(feature = "derive")]
7112    #[test]
7113    fn test_known_layout_derive() {
7114        // In this and other files (`late_compile_pass.rs`,
7115        // `mid_compile_pass.rs`, and `struct.rs`), we test success and failure
7116        // modes of `derive(KnownLayout)` for the following combination of
7117        // properties:
7118        //
7119        // +------------+--------------------------------------+-----------+
7120        // |            |      trailing field properties       |           |
7121        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7122        // |------------+----------+----------------+----------+-----------|
7123        // |          N |        N |              N |        N |      KL00 |
7124        // |          N |        N |              N |        Y |      KL01 |
7125        // |          N |        N |              Y |        N |      KL02 |
7126        // |          N |        N |              Y |        Y |      KL03 |
7127        // |          N |        Y |              N |        N |      KL04 |
7128        // |          N |        Y |              N |        Y |      KL05 |
7129        // |          N |        Y |              Y |        N |      KL06 |
7130        // |          N |        Y |              Y |        Y |      KL07 |
7131        // |          Y |        N |              N |        N |      KL08 |
7132        // |          Y |        N |              N |        Y |      KL09 |
7133        // |          Y |        N |              Y |        N |      KL10 |
7134        // |          Y |        N |              Y |        Y |      KL11 |
7135        // |          Y |        Y |              N |        N |      KL12 |
7136        // |          Y |        Y |              N |        Y |      KL13 |
7137        // |          Y |        Y |              Y |        N |      KL14 |
7138        // |          Y |        Y |              Y |        Y |      KL15 |
7139        // +------------+----------+----------------+----------+-----------+
7140
7141        struct NotKnownLayout<T = ()> {
7142            _t: T,
7143        }
7144
7145        #[derive(KnownLayout)]
7146        #[repr(C)]
7147        struct AlignSize<const ALIGN: usize, const SIZE: usize>
7148        where
7149            elain::Align<ALIGN>: elain::Alignment,
7150        {
7151            _align: elain::Align<ALIGN>,
7152            size: [u8; SIZE],
7153        }
7154
7155        type AU16 = AlignSize<2, 2>;
7156        type AU32 = AlignSize<4, 4>;
7157
7158        fn _assert_kl<T: ?Sized + KnownLayout>(_: &T) {}
7159
7160        let sized_layout = |align, size| DstLayout {
7161            align: NonZeroUsize::new(align).unwrap(),
7162            size_info: SizeInfo::Sized { size },
7163            statically_shallow_unpadded: false,
7164        };
7165
7166        let unsized_layout = |align, elem_size, offset, statically_shallow_unpadded| {
7167            let align = NonZeroUsize::new(align).unwrap();
7168            let size_phase = offset % align;
7169            DstLayout {
7170                align,
7171                size_info: SizeInfo::SliceDst(TrailingSliceLayout {
7172                    offset,
7173                    elem_size,
7174                    size_base: offset - size_phase,
7175                    size_rounding_align_and_phase: RoundingAlignAndPhase::new(align, size_phase),
7176                }),
7177                statically_shallow_unpadded,
7178            }
7179        };
7180
7181        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7182        // |          N |        N |              N |        Y |      KL01 |
7183        #[allow(dead_code)]
7184        #[derive(KnownLayout)]
7185        struct KL01(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
7186
7187        let expected = DstLayout::for_type::<KL01>();
7188
7189        assert_eq!(<KL01 as KnownLayout>::LAYOUT, expected);
7190        assert_eq!(<KL01 as KnownLayout>::LAYOUT, sized_layout(4, 8));
7191
7192        // ...with `align(N)`:
7193        #[allow(dead_code)]
7194        #[derive(KnownLayout)]
7195        #[repr(align(64))]
7196        struct KL01Align(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
7197
7198        let expected = DstLayout::for_type::<KL01Align>();
7199
7200        assert_eq!(<KL01Align as KnownLayout>::LAYOUT, expected);
7201        assert_eq!(<KL01Align as KnownLayout>::LAYOUT, sized_layout(64, 64));
7202
7203        // ...with `packed`:
7204        #[allow(dead_code)]
7205        #[derive(KnownLayout)]
7206        #[repr(packed)]
7207        struct KL01Packed(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
7208
7209        let expected = DstLayout::for_type::<KL01Packed>();
7210
7211        assert_eq!(<KL01Packed as KnownLayout>::LAYOUT, expected);
7212        assert_eq!(<KL01Packed as KnownLayout>::LAYOUT, sized_layout(1, 6));
7213
7214        // ...with `packed(N)`:
7215        #[allow(dead_code)]
7216        #[derive(KnownLayout)]
7217        #[repr(packed(2))]
7218        struct KL01PackedN(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
7219
7220        assert_impl_all!(KL01PackedN: KnownLayout);
7221
7222        let expected = DstLayout::for_type::<KL01PackedN>();
7223
7224        assert_eq!(<KL01PackedN as KnownLayout>::LAYOUT, expected);
7225        assert_eq!(<KL01PackedN as KnownLayout>::LAYOUT, sized_layout(2, 6));
7226
7227        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7228        // |          N |        N |              Y |        Y |      KL03 |
7229        #[allow(dead_code)]
7230        #[derive(KnownLayout)]
7231        struct KL03(NotKnownLayout, u8);
7232
7233        let expected = DstLayout::for_type::<KL03>();
7234
7235        assert_eq!(<KL03 as KnownLayout>::LAYOUT, expected);
7236        assert_eq!(<KL03 as KnownLayout>::LAYOUT, sized_layout(1, 1));
7237
7238        // ... with `align(N)`
7239        #[allow(dead_code)]
7240        #[derive(KnownLayout)]
7241        #[repr(align(64))]
7242        struct KL03Align(NotKnownLayout<AU32>, u8);
7243
7244        let expected = DstLayout::for_type::<KL03Align>();
7245
7246        assert_eq!(<KL03Align as KnownLayout>::LAYOUT, expected);
7247        assert_eq!(<KL03Align as KnownLayout>::LAYOUT, sized_layout(64, 64));
7248
7249        // ... with `packed`:
7250        #[allow(dead_code)]
7251        #[derive(KnownLayout)]
7252        #[repr(packed)]
7253        struct KL03Packed(NotKnownLayout<AU32>, u8);
7254
7255        let expected = DstLayout::for_type::<KL03Packed>();
7256
7257        assert_eq!(<KL03Packed as KnownLayout>::LAYOUT, expected);
7258        assert_eq!(<KL03Packed as KnownLayout>::LAYOUT, sized_layout(1, 5));
7259
7260        // ... with `packed(N)`
7261        #[allow(dead_code)]
7262        #[derive(KnownLayout)]
7263        #[repr(packed(2))]
7264        struct KL03PackedN(NotKnownLayout<AU32>, u8);
7265
7266        assert_impl_all!(KL03PackedN: KnownLayout);
7267
7268        let expected = DstLayout::for_type::<KL03PackedN>();
7269
7270        assert_eq!(<KL03PackedN as KnownLayout>::LAYOUT, expected);
7271        assert_eq!(<KL03PackedN as KnownLayout>::LAYOUT, sized_layout(2, 6));
7272
7273        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7274        // |          N |        Y |              N |        Y |      KL05 |
7275        #[allow(dead_code)]
7276        #[derive(KnownLayout)]
7277        struct KL05<T>(u8, T);
7278
7279        fn _test_kl05<T>(t: T) -> impl KnownLayout {
7280            KL05(0u8, t)
7281        }
7282
7283        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7284        // |          N |        Y |              Y |        Y |      KL07 |
7285        #[allow(dead_code)]
7286        #[derive(KnownLayout)]
7287        struct KL07<T: KnownLayout>(u8, T);
7288
7289        fn _test_kl07<T: KnownLayout>(t: T) -> impl KnownLayout {
7290            let _ = KL07(0u8, t);
7291        }
7292
7293        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7294        // |          Y |        N |              Y |        N |      KL10 |
7295        #[allow(dead_code)]
7296        #[derive(KnownLayout)]
7297        #[repr(C)]
7298        struct KL10(NotKnownLayout<AU32>, [u8]);
7299
7300        let expected = DstLayout::new_zst(None)
7301            .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), None)
7302            .extend(<[u8] as KnownLayout>::LAYOUT, None)
7303            .pad_to_align();
7304
7305        assert_eq!(<KL10 as KnownLayout>::LAYOUT, expected);
7306        assert_eq!(<KL10 as KnownLayout>::LAYOUT, unsized_layout(4, 1, 4, false));
7307
7308        // ...with `align(N)`:
7309        #[allow(dead_code)]
7310        #[derive(KnownLayout)]
7311        #[repr(C, align(64))]
7312        struct KL10Align(NotKnownLayout<AU32>, [u8]);
7313
7314        let repr_align = NonZeroUsize::new(64);
7315
7316        let expected = DstLayout::new_zst(repr_align)
7317            .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), None)
7318            .extend(<[u8] as KnownLayout>::LAYOUT, None)
7319            .pad_to_align();
7320
7321        assert_eq!(<KL10Align as KnownLayout>::LAYOUT, expected);
7322        assert_eq!(<KL10Align as KnownLayout>::LAYOUT, unsized_layout(64, 1, 4, false));
7323
7324        // ...with `packed`:
7325        #[allow(dead_code)]
7326        #[derive(KnownLayout)]
7327        #[repr(C, packed)]
7328        struct KL10Packed(NotKnownLayout<AU32>, [u8]);
7329
7330        let repr_packed = NonZeroUsize::new(1);
7331
7332        let expected = DstLayout::new_zst(None)
7333            .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), repr_packed)
7334            .extend(<[u8] as KnownLayout>::LAYOUT, repr_packed)
7335            .pad_to_align();
7336
7337        assert_eq!(<KL10Packed as KnownLayout>::LAYOUT, expected);
7338        assert_eq!(<KL10Packed as KnownLayout>::LAYOUT, unsized_layout(1, 1, 4, false));
7339
7340        // ...with `packed(N)`:
7341        #[allow(dead_code)]
7342        #[derive(KnownLayout)]
7343        #[repr(C, packed(2))]
7344        struct KL10PackedN(NotKnownLayout<AU32>, [u8]);
7345
7346        let repr_packed = NonZeroUsize::new(2);
7347
7348        let expected = DstLayout::new_zst(None)
7349            .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), repr_packed)
7350            .extend(<[u8] as KnownLayout>::LAYOUT, repr_packed)
7351            .pad_to_align();
7352
7353        assert_eq!(<KL10PackedN as KnownLayout>::LAYOUT, expected);
7354        assert_eq!(<KL10PackedN as KnownLayout>::LAYOUT, unsized_layout(2, 1, 4, false));
7355
7356        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7357        // |          Y |        N |              Y |        Y |      KL11 |
7358        #[allow(dead_code)]
7359        #[derive(KnownLayout)]
7360        #[repr(C)]
7361        struct KL11(NotKnownLayout<AU64>, u8);
7362
7363        let expected = DstLayout::new_zst(None)
7364            .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), None)
7365            .extend(<u8 as KnownLayout>::LAYOUT, None)
7366            .pad_to_align();
7367
7368        assert_eq!(<KL11 as KnownLayout>::LAYOUT, expected);
7369        assert_eq!(<KL11 as KnownLayout>::LAYOUT, sized_layout(8, 16));
7370
7371        // ...with `align(N)`:
7372        #[allow(dead_code)]
7373        #[derive(KnownLayout)]
7374        #[repr(C, align(64))]
7375        struct KL11Align(NotKnownLayout<AU64>, u8);
7376
7377        let repr_align = NonZeroUsize::new(64);
7378
7379        let expected = DstLayout::new_zst(repr_align)
7380            .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), None)
7381            .extend(<u8 as KnownLayout>::LAYOUT, None)
7382            .pad_to_align();
7383
7384        assert_eq!(<KL11Align as KnownLayout>::LAYOUT, expected);
7385        assert_eq!(<KL11Align as KnownLayout>::LAYOUT, sized_layout(64, 64));
7386
7387        // ...with `packed`:
7388        #[allow(dead_code)]
7389        #[derive(KnownLayout)]
7390        #[repr(C, packed)]
7391        struct KL11Packed(NotKnownLayout<AU64>, u8);
7392
7393        let repr_packed = NonZeroUsize::new(1);
7394
7395        let expected = DstLayout::new_zst(None)
7396            .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), repr_packed)
7397            .extend(<u8 as KnownLayout>::LAYOUT, repr_packed)
7398            .pad_to_align();
7399
7400        assert_eq!(<KL11Packed as KnownLayout>::LAYOUT, expected);
7401        assert_eq!(<KL11Packed as KnownLayout>::LAYOUT, sized_layout(1, 9));
7402
7403        // ...with `packed(N)`:
7404        #[allow(dead_code)]
7405        #[derive(KnownLayout)]
7406        #[repr(C, packed(2))]
7407        struct KL11PackedN(NotKnownLayout<AU64>, u8);
7408
7409        let repr_packed = NonZeroUsize::new(2);
7410
7411        let expected = DstLayout::new_zst(None)
7412            .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), repr_packed)
7413            .extend(<u8 as KnownLayout>::LAYOUT, repr_packed)
7414            .pad_to_align();
7415
7416        assert_eq!(<KL11PackedN as KnownLayout>::LAYOUT, expected);
7417        assert_eq!(<KL11PackedN as KnownLayout>::LAYOUT, sized_layout(2, 10));
7418
7419        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7420        // |          Y |        Y |              Y |        N |      KL14 |
7421        #[allow(dead_code)]
7422        #[derive(KnownLayout)]
7423        #[repr(C)]
7424        struct KL14<T: ?Sized + KnownLayout>(u8, T);
7425
7426        fn _test_kl14<T: ?Sized + KnownLayout>(kl: &KL14<T>) {
7427            _assert_kl(kl)
7428        }
7429
7430        // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name |
7431        // |          Y |        Y |              Y |        Y |      KL15 |
7432        #[allow(dead_code)]
7433        #[derive(KnownLayout)]
7434        #[repr(C)]
7435        struct KL15<T: KnownLayout>(u8, T);
7436
7437        fn _test_kl15<T: KnownLayout>(t: T) -> impl KnownLayout {
7438            let _ = KL15(0u8, t);
7439        }
7440
7441        // Test a variety of combinations of field types:
7442        //  - ()
7443        //  - u8
7444        //  - AU16
7445        //  - [()]
7446        //  - [u8]
7447        //  - [AU16]
7448
7449        #[allow(clippy::upper_case_acronyms, dead_code)]
7450        #[derive(KnownLayout)]
7451        #[repr(C)]
7452        struct KLTU<T, U: ?Sized>(T, U);
7453
7454        assert_eq!(<KLTU<(), ()> as KnownLayout>::LAYOUT, sized_layout(1, 0));
7455
7456        assert_eq!(<KLTU<(), u8> as KnownLayout>::LAYOUT, sized_layout(1, 1));
7457
7458        assert_eq!(<KLTU<(), AU16> as KnownLayout>::LAYOUT, sized_layout(2, 2));
7459
7460        assert_eq!(<KLTU<(), [()]> as KnownLayout>::LAYOUT, unsized_layout(1, 0, 0, false));
7461
7462        assert_eq!(<KLTU<(), [u8]> as KnownLayout>::LAYOUT, unsized_layout(1, 1, 0, false));
7463
7464        assert_eq!(<KLTU<(), [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 0, false));
7465
7466        assert_eq!(<KLTU<u8, ()> as KnownLayout>::LAYOUT, sized_layout(1, 1));
7467
7468        assert_eq!(<KLTU<u8, u8> as KnownLayout>::LAYOUT, sized_layout(1, 2));
7469
7470        assert_eq!(<KLTU<u8, AU16> as KnownLayout>::LAYOUT, sized_layout(2, 4));
7471
7472        assert_eq!(<KLTU<u8, [()]> as KnownLayout>::LAYOUT, unsized_layout(1, 0, 1, false));
7473
7474        assert_eq!(<KLTU<u8, [u8]> as KnownLayout>::LAYOUT, unsized_layout(1, 1, 1, false));
7475
7476        assert_eq!(<KLTU<u8, [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 2, false));
7477
7478        assert_eq!(<KLTU<AU16, ()> as KnownLayout>::LAYOUT, sized_layout(2, 2));
7479
7480        assert_eq!(<KLTU<AU16, u8> as KnownLayout>::LAYOUT, sized_layout(2, 4));
7481
7482        assert_eq!(<KLTU<AU16, AU16> as KnownLayout>::LAYOUT, sized_layout(2, 4));
7483
7484        assert_eq!(<KLTU<AU16, [()]> as KnownLayout>::LAYOUT, unsized_layout(2, 0, 2, false));
7485
7486        assert_eq!(<KLTU<AU16, [u8]> as KnownLayout>::LAYOUT, unsized_layout(2, 1, 2, false));
7487
7488        assert_eq!(<KLTU<AU16, [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 2, false));
7489
7490        // Test a variety of field counts.
7491
7492        #[derive(KnownLayout)]
7493        #[repr(C)]
7494        struct KLF0;
7495
7496        assert_eq!(<KLF0 as KnownLayout>::LAYOUT, sized_layout(1, 0));
7497
7498        #[derive(KnownLayout)]
7499        #[repr(C)]
7500        struct KLF1([u8]);
7501
7502        assert_eq!(<KLF1 as KnownLayout>::LAYOUT, unsized_layout(1, 1, 0, true));
7503
7504        #[derive(KnownLayout)]
7505        #[repr(C)]
7506        struct KLF2(NotKnownLayout<u8>, [u8]);
7507
7508        assert_eq!(<KLF2 as KnownLayout>::LAYOUT, unsized_layout(1, 1, 1, false));
7509
7510        #[derive(KnownLayout)]
7511        #[repr(C)]
7512        struct KLF3(NotKnownLayout<u8>, NotKnownLayout<AU16>, [u8]);
7513
7514        assert_eq!(<KLF3 as KnownLayout>::LAYOUT, unsized_layout(2, 1, 4, false));
7515
7516        #[derive(KnownLayout)]
7517        #[repr(C)]
7518        struct KLF4(NotKnownLayout<u8>, NotKnownLayout<AU16>, NotKnownLayout<AU32>, [u8]);
7519
7520        assert_eq!(<KLF4 as KnownLayout>::LAYOUT, unsized_layout(4, 1, 8, false));
7521    }
7522
7523    #[test]
7524    fn test_object_safety() {
7525        fn _takes_immutable(_: &dyn Immutable) {}
7526        fn _takes_unaligned(_: &dyn Unaligned) {}
7527    }
7528
7529    #[test]
7530    fn test_from_zeros_only() {
7531        // Test types that implement `FromZeros` but not `FromBytes`.
7532
7533        assert!(!bool::new_zeroed());
7534        assert_eq!(char::new_zeroed(), '\0');
7535
7536        #[cfg(feature = "alloc")]
7537        {
7538            assert_eq!(bool::new_box_zeroed(), Ok(Box::new(false)));
7539            assert_eq!(char::new_box_zeroed(), Ok(Box::new('\0')));
7540
7541            assert_eq!(
7542                <[bool]>::new_box_zeroed_with_elems(3).unwrap().as_ref(),
7543                [false, false, false]
7544            );
7545            assert_eq!(
7546                <[char]>::new_box_zeroed_with_elems(3).unwrap().as_ref(),
7547                ['\0', '\0', '\0']
7548            );
7549
7550            assert_eq!(bool::new_vec_zeroed(3).unwrap().as_ref(), [false, false, false]);
7551            assert_eq!(char::new_vec_zeroed(3).unwrap().as_ref(), ['\0', '\0', '\0']);
7552        }
7553
7554        let mut string = "hello".to_string();
7555        let s: &mut str = string.as_mut();
7556        assert_eq!(s, "hello");
7557        s.zero();
7558        assert_eq!(s, "\0\0\0\0\0");
7559    }
7560
7561    #[test]
7562    fn test_zst_count_preserved() {
7563        // Test that, when an explicit count is provided to for a type with a
7564        // ZST trailing slice element, that count is preserved. This is
7565        // important since, for such types, all element counts result in objects
7566        // of the same size, and so the correct behavior is ambiguous. However,
7567        // preserving the count as requested by the user is the behavior that we
7568        // document publicly.
7569
7570        // FromZeros methods
7571        #[cfg(feature = "alloc")]
7572        assert_eq!(<[()]>::new_box_zeroed_with_elems(3).unwrap().len(), 3);
7573        #[cfg(feature = "alloc")]
7574        assert_eq!(<()>::new_vec_zeroed(3).unwrap().len(), 3);
7575
7576        // FromBytes methods
7577        assert_eq!(<[()]>::ref_from_bytes_with_elems(&[][..], 3).unwrap().len(), 3);
7578        assert_eq!(<[()]>::ref_from_prefix_with_elems(&[][..], 3).unwrap().0.len(), 3);
7579        assert_eq!(<[()]>::ref_from_suffix_with_elems(&[][..], 3).unwrap().1.len(), 3);
7580        assert_eq!(<[()]>::mut_from_bytes_with_elems(&mut [][..], 3).unwrap().len(), 3);
7581        assert_eq!(<[()]>::mut_from_prefix_with_elems(&mut [][..], 3).unwrap().0.len(), 3);
7582        assert_eq!(<[()]>::mut_from_suffix_with_elems(&mut [][..], 3).unwrap().1.len(), 3);
7583    }
7584
7585    #[test]
7586    fn test_read_write() {
7587        const VAL: u64 = 0x12345678;
7588        #[cfg(target_endian = "big")]
7589        const VAL_BYTES: [u8; 8] = VAL.to_be_bytes();
7590        #[cfg(target_endian = "little")]
7591        const VAL_BYTES: [u8; 8] = VAL.to_le_bytes();
7592        const ZEROS: [u8; 8] = [0u8; 8];
7593
7594        // Test `FromBytes::{read_from, read_from_prefix, read_from_suffix}`.
7595
7596        assert_eq!(u64::read_from_bytes(&VAL_BYTES[..]), Ok(VAL));
7597        // The first 8 bytes are from `VAL_BYTES` and the second 8 bytes are all
7598        // zeros.
7599        let bytes_with_prefix: [u8; 16] = transmute!([VAL_BYTES, [0; 8]]);
7600        assert_eq!(u64::read_from_prefix(&bytes_with_prefix[..]), Ok((VAL, &ZEROS[..])));
7601        assert_eq!(u64::read_from_suffix(&bytes_with_prefix[..]), Ok((&VAL_BYTES[..], 0)));
7602        // The first 8 bytes are all zeros and the second 8 bytes are from
7603        // `VAL_BYTES`
7604        let bytes_with_suffix: [u8; 16] = transmute!([[0; 8], VAL_BYTES]);
7605        assert_eq!(u64::read_from_prefix(&bytes_with_suffix[..]), Ok((0, &VAL_BYTES[..])));
7606        assert_eq!(u64::read_from_suffix(&bytes_with_suffix[..]), Ok((&ZEROS[..], VAL)));
7607
7608        // Test `IntoBytes::{write_to, write_to_prefix, write_to_suffix}`.
7609
7610        let mut bytes = [0u8; 8];
7611        assert_eq!(VAL.write_to(&mut bytes[..]), Ok(()));
7612        assert_eq!(bytes, VAL_BYTES);
7613        let mut bytes = [0u8; 16];
7614        assert_eq!(VAL.write_to_prefix(&mut bytes[..]), Ok(()));
7615        let want: [u8; 16] = transmute!([VAL_BYTES, [0; 8]]);
7616        assert_eq!(bytes, want);
7617        let mut bytes = [0u8; 16];
7618        assert_eq!(VAL.write_to_suffix(&mut bytes[..]), Ok(()));
7619        let want: [u8; 16] = transmute!([[0; 8], VAL_BYTES]);
7620        assert_eq!(bytes, want);
7621    }
7622
7623    #[test]
7624    #[cfg(feature = "std")]
7625    fn test_read_io_with_padding_soundness() {
7626        // This test is designed to exhibit potential UB in
7627        // `FromBytes::read_from_io`. (see #2319, #2320).
7628
7629        // On most platforms (where `align_of::<u16>() == 2`), `WithPadding`
7630        // will have inter-field padding between `x` and `y`.
7631        #[derive(FromBytes)]
7632        #[repr(C)]
7633        struct WithPadding {
7634            x: u8,
7635            y: u16,
7636        }
7637        struct ReadsInRead;
7638        impl std::io::Read for ReadsInRead {
7639            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
7640                // This body branches on every byte of `buf`, ensuring that it
7641                // exhibits UB if any byte of `buf` is uninitialized.
7642                if buf.iter().all(|&x| x == 0) {
7643                    Ok(buf.len())
7644                } else {
7645                    buf.iter_mut().for_each(|x| *x = 0);
7646                    Ok(buf.len())
7647                }
7648            }
7649        }
7650        assert!(matches!(WithPadding::read_from_io(ReadsInRead), Ok(WithPadding { x: 0, y: 0 })));
7651    }
7652
7653    #[test]
7654    #[cfg(feature = "std")]
7655    fn test_read_write_io() {
7656        let mut long_buffer = [0, 0, 0, 0];
7657        assert!(matches!(u16::MAX.write_to_io(&mut long_buffer[..]), Ok(())));
7658        assert_eq!(long_buffer, [255, 255, 0, 0]);
7659        assert!(matches!(u16::read_from_io(&long_buffer[..]), Ok(u16::MAX)));
7660
7661        let mut short_buffer = [0, 0];
7662        assert!(u32::MAX.write_to_io(&mut short_buffer[..]).is_err());
7663        assert_eq!(short_buffer, [255, 255]);
7664        assert!(u32::read_from_io(&short_buffer[..]).is_err());
7665    }
7666
7667    #[test]
7668    fn test_try_from_bytes_try_read_from() {
7669        assert_eq!(<bool as TryFromBytes>::try_read_from_bytes(&[0]), Ok(false));
7670        assert_eq!(<bool as TryFromBytes>::try_read_from_bytes(&[1]), Ok(true));
7671
7672        assert_eq!(<bool as TryFromBytes>::try_read_from_prefix(&[0, 2]), Ok((false, &[2][..])));
7673        assert_eq!(<bool as TryFromBytes>::try_read_from_prefix(&[1, 2]), Ok((true, &[2][..])));
7674
7675        assert_eq!(<bool as TryFromBytes>::try_read_from_suffix(&[2, 0]), Ok((&[2][..], false)));
7676        assert_eq!(<bool as TryFromBytes>::try_read_from_suffix(&[2, 1]), Ok((&[2][..], true)));
7677
7678        // If we don't pass enough bytes, it fails.
7679        assert!(matches!(
7680            <u8 as TryFromBytes>::try_read_from_bytes(&[]),
7681            Err(TryReadError::Size(_))
7682        ));
7683        assert!(matches!(
7684            <u8 as TryFromBytes>::try_read_from_prefix(&[]),
7685            Err(TryReadError::Size(_))
7686        ));
7687        assert!(matches!(
7688            <u8 as TryFromBytes>::try_read_from_suffix(&[]),
7689            Err(TryReadError::Size(_))
7690        ));
7691
7692        // If we pass too many bytes, it fails.
7693        assert!(matches!(
7694            <u8 as TryFromBytes>::try_read_from_bytes(&[0, 0]),
7695            Err(TryReadError::Size(_))
7696        ));
7697
7698        // If we pass an invalid value, it fails.
7699        assert!(matches!(
7700            <bool as TryFromBytes>::try_read_from_bytes(&[2]),
7701            Err(TryReadError::Validity(_))
7702        ));
7703        assert!(matches!(
7704            <bool as TryFromBytes>::try_read_from_prefix(&[2, 0]),
7705            Err(TryReadError::Validity(_))
7706        ));
7707        assert!(matches!(
7708            <bool as TryFromBytes>::try_read_from_suffix(&[0, 2]),
7709            Err(TryReadError::Validity(_))
7710        ));
7711
7712        // Reading from a misaligned buffer should still succeed. Since `AU64`'s
7713        // alignment is 8, and since we read from two adjacent addresses one
7714        // byte apart, it is guaranteed that at least one of them (though
7715        // possibly both) will be misaligned.
7716        let bytes: [u8; 9] = [0, 0, 0, 0, 0, 0, 0, 0, 0];
7717        assert_eq!(<AU64 as TryFromBytes>::try_read_from_bytes(&bytes[..8]), Ok(AU64(0)));
7718        assert_eq!(<AU64 as TryFromBytes>::try_read_from_bytes(&bytes[1..9]), Ok(AU64(0)));
7719
7720        assert_eq!(
7721            <AU64 as TryFromBytes>::try_read_from_prefix(&bytes[..8]),
7722            Ok((AU64(0), &[][..]))
7723        );
7724        assert_eq!(
7725            <AU64 as TryFromBytes>::try_read_from_prefix(&bytes[1..9]),
7726            Ok((AU64(0), &[][..]))
7727        );
7728
7729        assert_eq!(
7730            <AU64 as TryFromBytes>::try_read_from_suffix(&bytes[..8]),
7731            Ok((&[][..], AU64(0)))
7732        );
7733        assert_eq!(
7734            <AU64 as TryFromBytes>::try_read_from_suffix(&bytes[1..9]),
7735            Ok((&[][..], AU64(0)))
7736        );
7737    }
7738
7739    #[test]
7740    fn test_try_read_from_typed_source() {
7741        #[derive(IntoBytes, Immutable)]
7742        #[repr(transparent)]
7743        struct Source<T: ?Sized>(T);
7744
7745        fn check<S: IntoBytes + Immutable + ?Sized>(source: &S, valid: bool) {
7746            match try_read_from::<_, [bool; 4]>(source) {
7747                Ok(value) => {
7748                    assert!(valid);
7749                    assert_eq!(value, [false, true, false, true]);
7750                }
7751                Err(error) => {
7752                    assert!(!valid);
7753                    assert!(matches!(error, TryReadError::Validity(_)));
7754                    assert!(ptr::eq(error.into_src(), source));
7755                }
7756            }
7757
7758            let error = try_read_from::<_, [bool; 5]>(source).unwrap_err();
7759            assert!(matches!(error, TryReadError::Size(_)));
7760            assert!(ptr::eq(error.into_src(), source));
7761        }
7762
7763        for (value, valid) in [(u16::from_ne_bytes([0, 1]), true), (0x0202, false)] {
7764            let source = Source([value; 2]);
7765            check(&source, valid);
7766            let source: &Source<[u16]> = &source;
7767            check(source, valid);
7768        }
7769
7770        let source = Source([(); 2]);
7771        assert!(try_read_from::<_, ()>(&source).is_ok());
7772        let source: &Source<[()]> = &source;
7773        assert!(try_read_from::<_, ()>(source).is_ok());
7774    }
7775
7776    #[test]
7777    fn test_try_read_initialized_padding() {
7778        #[derive(KnownLayout, Immutable, Debug, PartialEq, Eq)]
7779        #[repr(C, align(8))]
7780        struct Padded(u8);
7781
7782        // SAFETY: `Padded` has only a `u8` field and padding, so all
7783        // initialized byte sequences are valid. Per
7784        // https://doc.rust-lang.org/1.93.1/reference/behavior-considered-undefined.html#invalid-values:
7785        //
7786        //   An integer (`i*`/`u*`), floating point value (`f*`), or raw pointer
7787        //   must be initialized, i.e., must not be obtained from uninitialized
7788        //   memory.
7789        //
7790        //   A `struct`, tuple, and array requires all fields/elements to be
7791        //   valid at their respective type.
7792        const _: () = unsafe {
7793            unsafe_impl!(=> TryFromBytes for Padded; |candidate| {
7794                // Observe every byte while validation is running, including
7795                // padding that a typed move of `MaybeUninit<Padded>` could
7796                // discard. The returned `Padded` need not retain its padding.
7797                assert_eq!(candidate.as_bytes::<BecauseImmutable>().as_ref(), &[0xA5; 8]);
7798                true
7799            })
7800        };
7801
7802        let source = [0xA5; 8];
7803        assert_eq!(Padded::try_read_from_bytes(&source), Ok(Padded(0xA5)));
7804
7805        let prefix_source = [0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0];
7806        let (value, suffix) = Padded::try_read_from_prefix(&prefix_source).unwrap();
7807        assert_eq!(value, Padded(0xA5));
7808        assert!(ptr::eq(suffix, &prefix_source[8..]));
7809
7810        let suffix_source = [0, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5];
7811        let (prefix, value) = Padded::try_read_from_suffix(&suffix_source).unwrap();
7812        assert_eq!(value, Padded(0xA5));
7813        assert!(ptr::eq(prefix, &suffix_source[..1]));
7814    }
7815
7816    #[test]
7817    fn test_try_read_error_sources_and_zero_sized() {
7818        let invalid = [2, 3];
7819        for (error, source) in [
7820            (bool::try_read_from_bytes(&invalid[..1]).unwrap_err(), &invalid[..1]),
7821            (bool::try_read_from_prefix(&invalid).unwrap_err(), &invalid[..]),
7822            (bool::try_read_from_suffix(&invalid).unwrap_err(), &invalid[..]),
7823        ] {
7824            assert!(matches!(error, TryReadError::Validity(_)));
7825            assert!(ptr::eq(error.into_src(), source));
7826        }
7827        for source in [&[][..], &invalid[..]] {
7828            let error = bool::try_read_from_bytes(source).unwrap_err();
7829            assert!(matches!(error, TryReadError::Size(_)));
7830            assert!(ptr::eq(error.into_src(), source));
7831        }
7832        for error in [
7833            bool::try_read_from_prefix(&invalid[..0]).unwrap_err(),
7834            bool::try_read_from_suffix(&invalid[..0]).unwrap_err(),
7835        ] {
7836            assert!(matches!(error, TryReadError::Size(_)));
7837            assert!(ptr::eq(error.into_src(), &invalid[..0]));
7838        }
7839
7840        assert_eq!(<()>::try_read_from_bytes(&[]), Ok(()));
7841        assert_eq!(<()>::try_read_from_prefix(&invalid), Ok(((), &invalid[..])));
7842        assert_eq!(<()>::try_read_from_suffix(&invalid), Ok((&invalid[..], ())));
7843    }
7844
7845    #[test]
7846    fn test_ref_from_mut_from_bytes() {
7847        // Test `FromBytes::{ref_from_bytes, mut_from_bytes}{,_prefix,Suffix}`
7848        // success cases. Exhaustive coverage for these methods is covered by
7849        // the `Ref` tests above, which these helper methods defer to.
7850
7851        let mut buf =
7852            Align::<[u8; 16], AU64>::new([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
7853
7854        assert_eq!(
7855            AU64::ref_from_bytes(&buf.t[8..]).unwrap().0.to_ne_bytes(),
7856            [8, 9, 10, 11, 12, 13, 14, 15]
7857        );
7858        let suffix = AU64::mut_from_bytes(&mut buf.t[8..]).unwrap();
7859        suffix.0 = 0x0101010101010101;
7860        // The `[u8:9]` is a non-half size of the full buffer, which would catch
7861        // `from_prefix` having the same implementation as `from_suffix` (issues #506, #511).
7862        assert_eq!(
7863            <[u8; 9]>::ref_from_suffix(&buf.t[..]).unwrap(),
7864            (&[0, 1, 2, 3, 4, 5, 6][..], &[7u8, 1, 1, 1, 1, 1, 1, 1, 1])
7865        );
7866        let (prefix, suffix) = AU64::mut_from_suffix(&mut buf.t[1..]).unwrap();
7867        assert_eq!(prefix, &mut [1u8, 2, 3, 4, 5, 6, 7][..]);
7868        suffix.0 = 0x0202020202020202;
7869        let (prefix, suffix) = <[u8; 10]>::mut_from_suffix(&mut buf.t[..]).unwrap();
7870        assert_eq!(prefix, &mut [0u8, 1, 2, 3, 4, 5][..]);
7871        suffix[0] = 42;
7872        assert_eq!(
7873            <[u8; 9]>::ref_from_prefix(&buf.t[..]).unwrap(),
7874            (&[0u8, 1, 2, 3, 4, 5, 42, 7, 2], &[2u8, 2, 2, 2, 2, 2, 2][..])
7875        );
7876        <[u8; 2]>::mut_from_prefix(&mut buf.t[..]).unwrap().0[1] = 30;
7877        assert_eq!(buf.t, [0, 30, 2, 3, 4, 5, 42, 7, 2, 2, 2, 2, 2, 2, 2, 2]);
7878    }
7879
7880    #[test]
7881    fn test_ref_from_mut_from_bytes_error() {
7882        // Test `FromBytes::{ref_from_bytes, mut_from_bytes}{,_prefix,Suffix}`
7883        // error cases.
7884
7885        // Fail because the buffer is too large.
7886        let mut buf = Align::<[u8; 16], AU64>::default();
7887        // `buf.t` should be aligned to 8, so only the length check should fail.
7888        assert!(AU64::ref_from_bytes(&buf.t[..]).is_err());
7889        assert!(AU64::mut_from_bytes(&mut buf.t[..]).is_err());
7890        assert!(<[u8; 8]>::ref_from_bytes(&buf.t[..]).is_err());
7891        assert!(<[u8; 8]>::mut_from_bytes(&mut buf.t[..]).is_err());
7892
7893        // Fail because the buffer is too small.
7894        let mut buf = Align::<[u8; 4], AU64>::default();
7895        assert!(AU64::ref_from_bytes(&buf.t[..]).is_err());
7896        assert!(AU64::mut_from_bytes(&mut buf.t[..]).is_err());
7897        assert!(<[u8; 8]>::ref_from_bytes(&buf.t[..]).is_err());
7898        assert!(<[u8; 8]>::mut_from_bytes(&mut buf.t[..]).is_err());
7899        assert!(AU64::ref_from_prefix(&buf.t[..]).is_err());
7900        assert!(AU64::mut_from_prefix(&mut buf.t[..]).is_err());
7901        assert!(AU64::ref_from_suffix(&buf.t[..]).is_err());
7902        assert!(AU64::mut_from_suffix(&mut buf.t[..]).is_err());
7903        assert!(<[u8; 8]>::ref_from_prefix(&buf.t[..]).is_err());
7904        assert!(<[u8; 8]>::mut_from_prefix(&mut buf.t[..]).is_err());
7905        assert!(<[u8; 8]>::ref_from_suffix(&buf.t[..]).is_err());
7906        assert!(<[u8; 8]>::mut_from_suffix(&mut buf.t[..]).is_err());
7907
7908        // Fail because the alignment is insufficient.
7909        let mut buf = Align::<[u8; 13], AU64>::default();
7910        assert!(AU64::ref_from_bytes(&buf.t[1..]).is_err());
7911        assert!(AU64::mut_from_bytes(&mut buf.t[1..]).is_err());
7912        assert!(AU64::ref_from_bytes(&buf.t[1..]).is_err());
7913        assert!(AU64::mut_from_bytes(&mut buf.t[1..]).is_err());
7914        assert!(AU64::ref_from_prefix(&buf.t[1..]).is_err());
7915        assert!(AU64::mut_from_prefix(&mut buf.t[1..]).is_err());
7916        assert!(AU64::ref_from_suffix(&buf.t[..]).is_err());
7917        assert!(AU64::mut_from_suffix(&mut buf.t[..]).is_err());
7918    }
7919
7920    #[test]
7921    fn test_to_methods() {
7922        /// Run a series of tests by calling `IntoBytes` methods on `t`.
7923        ///
7924        /// `bytes` is the expected byte sequence returned from `t.as_bytes()`
7925        /// before `t` has been modified. `post_mutation` is the expected
7926        /// sequence returned from `t.as_bytes()` after `t.as_mut_bytes()[0]`
7927        /// has had its bits flipped (by applying `^= 0xFF`).
7928        ///
7929        /// `N` is the size of `t` in bytes.
7930        fn test<T: FromBytes + IntoBytes + Immutable + Debug + Eq + ?Sized, const N: usize>(
7931            t: &mut T,
7932            bytes: &[u8],
7933            post_mutation: &T,
7934        ) {
7935            // Test that we can access the underlying bytes, and that we get the
7936            // right bytes and the right number of bytes.
7937            assert_eq!(t.as_bytes(), bytes);
7938
7939            // Test that changes to the underlying byte slices are reflected in
7940            // the original object.
7941            t.as_mut_bytes()[0] ^= 0xFF;
7942            assert_eq!(t, post_mutation);
7943            t.as_mut_bytes()[0] ^= 0xFF;
7944
7945            // `write_to` rejects slices that are too small or too large.
7946            assert!(t.write_to(&mut vec![0; N - 1][..]).is_err());
7947            assert!(t.write_to(&mut vec![0; N + 1][..]).is_err());
7948
7949            // `write_to` works as expected.
7950            let mut bytes = [0; N];
7951            assert_eq!(t.write_to(&mut bytes[..]), Ok(()));
7952            assert_eq!(bytes, t.as_bytes());
7953
7954            // `write_to_prefix` rejects slices that are too small.
7955            assert!(t.write_to_prefix(&mut vec![0; N - 1][..]).is_err());
7956
7957            // `write_to_prefix` works with exact-sized slices.
7958            let mut bytes = [0; N];
7959            assert_eq!(t.write_to_prefix(&mut bytes[..]), Ok(()));
7960            assert_eq!(bytes, t.as_bytes());
7961
7962            // `write_to_prefix` works with too-large slices, and any bytes past
7963            // the prefix aren't modified.
7964            let mut too_many_bytes = vec![0; N + 1];
7965            too_many_bytes[N] = 123;
7966            assert_eq!(t.write_to_prefix(&mut too_many_bytes[..]), Ok(()));
7967            assert_eq!(&too_many_bytes[..N], t.as_bytes());
7968            assert_eq!(too_many_bytes[N], 123);
7969
7970            // `write_to_suffix` rejects slices that are too small.
7971            assert!(t.write_to_suffix(&mut vec![0; N - 1][..]).is_err());
7972
7973            // `write_to_suffix` works with exact-sized slices.
7974            let mut bytes = [0; N];
7975            assert_eq!(t.write_to_suffix(&mut bytes[..]), Ok(()));
7976            assert_eq!(bytes, t.as_bytes());
7977
7978            // `write_to_suffix` works with too-large slices, and any bytes
7979            // before the suffix aren't modified.
7980            let mut too_many_bytes = vec![0; N + 1];
7981            too_many_bytes[0] = 123;
7982            assert_eq!(t.write_to_suffix(&mut too_many_bytes[..]), Ok(()));
7983            assert_eq!(&too_many_bytes[1..], t.as_bytes());
7984            assert_eq!(too_many_bytes[0], 123);
7985        }
7986
7987        #[derive(Debug, Eq, PartialEq, FromBytes, IntoBytes, Immutable)]
7988        #[repr(C)]
7989        struct Foo {
7990            a: u32,
7991            b: Wrapping<u32>,
7992            c: Option<NonZeroU32>,
7993        }
7994
7995        let expected_bytes: Vec<u8> = if cfg!(target_endian = "little") {
7996            vec![1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]
7997        } else {
7998            vec![0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0]
7999        };
8000        let post_mutation_expected_a =
8001            if cfg!(target_endian = "little") { 0x00_00_00_FE } else { 0xFF_00_00_01 };
8002        test::<_, 12>(
8003            &mut Foo { a: 1, b: Wrapping(2), c: None },
8004            expected_bytes.as_bytes(),
8005            &Foo { a: post_mutation_expected_a, b: Wrapping(2), c: None },
8006        );
8007        test::<_, 3>(
8008            Unsized::from_mut_slice(&mut [1, 2, 3]),
8009            &[1, 2, 3],
8010            Unsized::from_mut_slice(&mut [0xFE, 2, 3]),
8011        );
8012    }
8013
8014    #[test]
8015    fn test_array() {
8016        #[derive(FromBytes, IntoBytes, Immutable)]
8017        #[repr(C)]
8018        struct Foo {
8019            a: [u16; 33],
8020        }
8021
8022        let foo = Foo { a: [0xFFFF; 33] };
8023        let expected = [0xFFu8; 66];
8024        assert_eq!(foo.as_bytes(), &expected[..]);
8025    }
8026
8027    #[test]
8028    fn test_new_zeroed() {
8029        assert!(!bool::new_zeroed());
8030        assert_eq!(u64::new_zeroed(), 0);
8031        // This test exists in order to exercise unsafe code, especially when
8032        // running under Miri.
8033        #[allow(clippy::unit_cmp)]
8034        {
8035            assert_eq!(<()>::new_zeroed(), ());
8036        }
8037    }
8038
8039    #[test]
8040    fn test_transparent_packed_generic_struct() {
8041        #[derive(IntoBytes, FromBytes, Unaligned)]
8042        #[repr(transparent)]
8043        #[allow(dead_code)] // We never construct this type
8044        struct Foo<T> {
8045            _t: T,
8046            _phantom: PhantomData<()>,
8047        }
8048
8049        assert_impl_all!(Foo<u32>: FromZeros, FromBytes, IntoBytes);
8050        assert_impl_all!(Foo<u8>: Unaligned);
8051
8052        #[derive(IntoBytes, FromBytes, Unaligned)]
8053        #[repr(C, packed)]
8054        #[allow(dead_code)] // We never construct this type
8055        struct Bar<T, U> {
8056            _t: T,
8057            _u: U,
8058        }
8059
8060        assert_impl_all!(Bar<u8, AU64>: FromZeros, FromBytes, IntoBytes, Unaligned);
8061    }
8062
8063    #[cfg(feature = "alloc")]
8064    mod alloc {
8065        use super::*;
8066
8067        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
8068        #[test]
8069        fn test_extend_vec_zeroed() {
8070            // Test extending when there is an existing allocation.
8071            let mut v = vec![100u16, 200, 300];
8072            FromZeros::extend_vec_zeroed(&mut v, 3).unwrap();
8073            assert_eq!(v.len(), 6);
8074            assert_eq!(&*v, &[100, 200, 300, 0, 0, 0]);
8075            drop(v);
8076
8077            // Test extending when there is no existing allocation.
8078            let mut v: Vec<u64> = Vec::new();
8079            FromZeros::extend_vec_zeroed(&mut v, 3).unwrap();
8080            assert_eq!(v.len(), 3);
8081            assert_eq!(&*v, &[0, 0, 0]);
8082            drop(v);
8083        }
8084
8085        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
8086        #[test]
8087        fn test_extend_vec_zeroed_zst() {
8088            // Test extending when there is an existing (fake) allocation.
8089            let mut v = vec![(), (), ()];
8090            <()>::extend_vec_zeroed(&mut v, 3).unwrap();
8091            assert_eq!(v.len(), 6);
8092            assert_eq!(&*v, &[(), (), (), (), (), ()]);
8093            drop(v);
8094
8095            // Test extending when there is no existing (fake) allocation.
8096            let mut v: Vec<()> = Vec::new();
8097            <()>::extend_vec_zeroed(&mut v, 3).unwrap();
8098            assert_eq!(&*v, &[(), (), ()]);
8099            drop(v);
8100        }
8101
8102        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
8103        #[test]
8104        fn test_insert_vec_zeroed() {
8105            // Insert at start (no existing allocation).
8106            let mut v: Vec<u64> = Vec::new();
8107            u64::insert_vec_zeroed(&mut v, 0, 2).unwrap();
8108            assert_eq!(v.len(), 2);
8109            assert_eq!(&*v, &[0, 0]);
8110            drop(v);
8111
8112            // Insert at start.
8113            let mut v = vec![100u64, 200, 300];
8114            u64::insert_vec_zeroed(&mut v, 0, 2).unwrap();
8115            assert_eq!(v.len(), 5);
8116            assert_eq!(&*v, &[0, 0, 100, 200, 300]);
8117            drop(v);
8118
8119            // Insert at middle.
8120            let mut v = vec![100u64, 200, 300];
8121            u64::insert_vec_zeroed(&mut v, 1, 1).unwrap();
8122            assert_eq!(v.len(), 4);
8123            assert_eq!(&*v, &[100, 0, 200, 300]);
8124            drop(v);
8125
8126            // Insert at end.
8127            let mut v = vec![100u64, 200, 300];
8128            u64::insert_vec_zeroed(&mut v, 3, 1).unwrap();
8129            assert_eq!(v.len(), 4);
8130            assert_eq!(&*v, &[100, 200, 300, 0]);
8131            drop(v);
8132        }
8133
8134        #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
8135        #[test]
8136        fn test_insert_vec_zeroed_zst() {
8137            // Insert at start (no existing fake allocation).
8138            let mut v: Vec<()> = Vec::new();
8139            <()>::insert_vec_zeroed(&mut v, 0, 2).unwrap();
8140            assert_eq!(v.len(), 2);
8141            assert_eq!(&*v, &[(), ()]);
8142            drop(v);
8143
8144            // Insert at start.
8145            let mut v = vec![(), (), ()];
8146            <()>::insert_vec_zeroed(&mut v, 0, 2).unwrap();
8147            assert_eq!(v.len(), 5);
8148            assert_eq!(&*v, &[(), (), (), (), ()]);
8149            drop(v);
8150
8151            // Insert at middle.
8152            let mut v = vec![(), (), ()];
8153            <()>::insert_vec_zeroed(&mut v, 1, 1).unwrap();
8154            assert_eq!(v.len(), 4);
8155            assert_eq!(&*v, &[(), (), (), ()]);
8156            drop(v);
8157
8158            // Insert at end.
8159            let mut v = vec![(), (), ()];
8160            <()>::insert_vec_zeroed(&mut v, 3, 1).unwrap();
8161            assert_eq!(v.len(), 4);
8162            assert_eq!(&*v, &[(), (), (), ()]);
8163            drop(v);
8164        }
8165
8166        #[test]
8167        fn test_new_box_zeroed() {
8168            assert_eq!(u64::new_box_zeroed(), Ok(Box::new(0)));
8169            assert_eq!(Wrapping::<u64>::new_box_zeroed(), Ok(Box::new(Wrapping(0))));
8170        }
8171
8172        #[test]
8173        fn test_new_box_zeroed_array() {
8174            drop(<[u32; 0x1000]>::new_box_zeroed());
8175        }
8176
8177        #[test]
8178        fn test_new_box_zeroed_zst() {
8179            // This test exists in order to exercise unsafe code, especially
8180            // when running under Miri.
8181            #[allow(clippy::unit_cmp)]
8182            {
8183                assert_eq!(<()>::new_box_zeroed(), Ok(Box::new(())));
8184            }
8185        }
8186
8187        #[cfg(not(no_zerocopy_allocator_api_1_100_0))]
8188        #[test]
8189        fn test_new_box_zeroed_in() {
8190            assert_eq!(
8191                u64::new_box_zeroed_in(::alloc::alloc::Global),
8192                Ok(Box::new_in(0, ::alloc::alloc::Global)),
8193            );
8194            assert_eq!(
8195                Wrapping::<u64>::new_box_zeroed_in(::alloc::alloc::Global),
8196                Ok(Box::new_in(Wrapping(0), ::alloc::alloc::Global)),
8197            );
8198        }
8199
8200        #[cfg(not(no_zerocopy_allocator_api_1_100_0))]
8201        #[test]
8202        fn test_new_box_zeroed_in_array() {
8203            drop(<[u32; 0x1000]>::new_box_zeroed_in(::alloc::alloc::Global));
8204        }
8205
8206        #[cfg(not(no_zerocopy_allocator_api_1_100_0))]
8207        #[test]
8208        fn test_new_box_zeroed_in_zst() {
8209            #[derive(FromZeros, PartialEq, Debug)]
8210            #[repr(C, align(64))]
8211            struct AlignedZst;
8212
8213            // This test exists in order to exercise unsafe code, especially
8214            // when running under Miri.
8215            #[allow(clippy::unit_cmp)]
8216            {
8217                assert_eq!(
8218                    <()>::new_box_zeroed_in(::alloc::alloc::Global),
8219                    Ok(Box::new_in((), ::alloc::alloc::Global)),
8220                );
8221            }
8222            let b = AlignedZst::new_box_zeroed_in(::alloc::alloc::Global).unwrap();
8223            assert_eq!(*b, AlignedZst);
8224            assert_eq!(Box::as_ptr(&b).addr() % 64, 0);
8225        }
8226
8227        #[cfg(not(no_zerocopy_allocator_api_1_100_0))]
8228        #[test]
8229        fn test_new_box_zeroed_in_custom_allocator() {
8230            #[derive(Default, Debug)]
8231            struct TrackingAllocator {
8232                allocated: Cell<usize>,
8233                deallocated: Cell<usize>,
8234                fail: Cell<bool>,
8235            }
8236
8237            // SAFETY: `TrackingAllocator` delegates all allocation and
8238            // deallocation directly to `::alloc::alloc::Global`, which
8239            // satisfies the `Allocator` safety contract.
8240            unsafe impl Allocator for TrackingAllocator {
8241                fn allocate(
8242                    &self,
8243                    layout: Layout,
8244                ) -> Result<NonNull<[u8]>, core::alloc::AllocError> {
8245                    if self.fail.get() {
8246                        return Err(core::alloc::AllocError);
8247                    }
8248                    let ptr = ::alloc::alloc::Global.allocate(layout)?;
8249                    // Dirty the allocation so we verify `new_box_zeroed_in`
8250                    // calls `allocate_zeroed` (which zeroes the bytes).
8251                    // SAFETY: `ptr` is a newly allocated, valid `[u8]` block of
8252                    // length `ptr.len()`.
8253                    unsafe {
8254                        ptr.cast::<u8>().as_ptr().write_bytes(0xFF, layout.size());
8255                    }
8256                    self.allocated.set(self.allocated.get() + 1);
8257                    Ok(ptr)
8258                }
8259
8260                unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
8261                    self.deallocated.set(self.deallocated.get() + 1);
8262                    // SAFETY: The caller upholds the `deallocate` preconditions
8263                    // for blocks allocated via `::alloc::alloc::Global`.
8264                    unsafe { ::alloc::alloc::Global.deallocate(ptr, layout) };
8265                }
8266            }
8267
8268            let alloc = TrackingAllocator::default();
8269            let b = <[u64; 4]>::new_box_zeroed_in(&alloc).unwrap();
8270            assert_eq!(*b, [0, 0, 0, 0]);
8271            assert_eq!(alloc.allocated.get(), 1);
8272            assert_eq!(alloc.deallocated.get(), 0);
8273            drop(b);
8274            assert_eq!(alloc.deallocated.get(), 1);
8275
8276            // ZST should not call `allocate` or `deallocate`.
8277            alloc.fail.set(true);
8278            let b = <()>::new_box_zeroed_in(&alloc).unwrap();
8279            assert_eq!(alloc.allocated.get(), 1);
8280            drop(b);
8281            assert_eq!(alloc.deallocated.get(), 1);
8282
8283            // Allocation failure should return `Err(AllocError)` without
8284            // panicking or leaking.
8285            let res = u64::new_box_zeroed_in(&alloc);
8286            assert_eq!(res.unwrap_err(), AllocError);
8287            assert_eq!(alloc.allocated.get(), 1);
8288            assert_eq!(alloc.deallocated.get(), 1);
8289
8290            // Also exercise passing an owned allocator by value.
8291            let b = u64::new_box_zeroed_in(TrackingAllocator::default()).unwrap();
8292            assert_eq!(*b, 0);
8293        }
8294
8295        #[test]
8296        fn test_new_box_zeroed_with_elems() {
8297            let mut s: Box<[u64]> = <[u64]>::new_box_zeroed_with_elems(3).unwrap();
8298            assert_eq!(s.len(), 3);
8299            assert_eq!(&*s, &[0, 0, 0]);
8300            s[1] = 3;
8301            assert_eq!(&*s, &[0, 3, 0]);
8302        }
8303
8304        #[test]
8305        fn test_new_box_zeroed_with_elems_nested_packed_dst() {
8306            let mut value = NestedPackedDstOuter::<[u8]>::new_box_zeroed_with_elems(0).unwrap();
8307            assert_eq!(mem::size_of_val(&*value), 10);
8308
8309            // Exercise the whole-object write that exposed the former
8310            // under-allocation under Miri and AddressSanitizer.
8311            value.zero();
8312        }
8313
8314        #[test]
8315        fn test_new_box_zeroed_with_elems_empty() {
8316            let s: Box<[u64]> = <[u64]>::new_box_zeroed_with_elems(0).unwrap();
8317            assert_eq!(s.len(), 0);
8318        }
8319
8320        #[test]
8321        fn test_new_box_zeroed_with_elems_zst() {
8322            let mut s: Box<[()]> = <[()]>::new_box_zeroed_with_elems(3).unwrap();
8323            assert_eq!(s.len(), 3);
8324            assert!(s.get(10).is_none());
8325            // This test exists in order to exercise unsafe code, especially
8326            // when running under Miri.
8327            #[allow(clippy::unit_cmp)]
8328            {
8329                assert_eq!(s[1], ());
8330            }
8331            s[2] = ();
8332        }
8333
8334        #[test]
8335        fn test_new_box_zeroed_with_elems_zst_empty() {
8336            let s: Box<[()]> = <[()]>::new_box_zeroed_with_elems(0).unwrap();
8337            assert_eq!(s.len(), 0);
8338        }
8339
8340        #[test]
8341        fn new_box_zeroed_with_elems_errors() {
8342            assert_eq!(<[u16]>::new_box_zeroed_with_elems(usize::MAX), Err(AllocError));
8343
8344            let max = <usize as core::convert::TryFrom<_>>::try_from(isize::MAX).unwrap();
8345            assert_eq!(
8346                <[u16]>::new_box_zeroed_with_elems((max / mem::size_of::<u16>()) + 1),
8347                Err(AllocError)
8348            );
8349        }
8350    }
8351
8352    #[test]
8353    #[allow(deprecated)]
8354    fn test_deprecated_from_bytes() {
8355        let val = 0u32;
8356        let bytes = val.as_bytes();
8357
8358        assert!(u32::ref_from(bytes).is_some());
8359        // mut_from needs mut bytes
8360        let mut val = 0u32;
8361        let mut_bytes = val.as_mut_bytes();
8362        assert!(u32::mut_from(mut_bytes).is_some());
8363
8364        assert!(u32::read_from(bytes).is_some());
8365
8366        let (slc, rest) = <u32>::slice_from_prefix(bytes, 0).unwrap();
8367        assert!(slc.is_empty());
8368        assert_eq!(rest.len(), 4);
8369
8370        let (rest, slc) = <u32>::slice_from_suffix(bytes, 0).unwrap();
8371        assert!(slc.is_empty());
8372        assert_eq!(rest.len(), 4);
8373
8374        let (slc, rest) = <u32>::mut_slice_from_prefix(mut_bytes, 0).unwrap();
8375        assert!(slc.is_empty());
8376        assert_eq!(rest.len(), 4);
8377
8378        let (rest, slc) = <u32>::mut_slice_from_suffix(mut_bytes, 0).unwrap();
8379        assert!(slc.is_empty());
8380        assert_eq!(rest.len(), 4);
8381    }
8382
8383    #[test]
8384    fn test_ref_from_prefix_suffix_typed_source() {
8385        #[derive(IntoBytes, Immutable)]
8386        #[repr(transparent)]
8387        struct Source<T: ?Sized>(T);
8388
8389        fn check<S: IntoBytes + Immutable + ?Sized>(source: &S) {
8390            let bytes = source.as_bytes();
8391            assert_eq!(bytes.len(), 4);
8392
8393            for cast_type in [CastType::Prefix, CastType::Suffix] {
8394                let (expected, expected_rest) = match cast_type {
8395                    CastType::Prefix => (&bytes[..3], &bytes[3..]),
8396                    CastType::Suffix => (&bytes[1..], &bytes[..1]),
8397                };
8398                for meta in [None, Some(1)] {
8399                    let (value, rest) =
8400                        ref_from_prefix_suffix::<_, [[u8; 3]]>(source, meta, cast_type).unwrap();
8401                    assert_eq!(value, &[expected]);
8402                    assert!(ptr::eq(value.as_bytes(), expected));
8403                    assert!(ptr::eq(rest, expected_rest));
8404                }
8405
8406                let err =
8407                    ref_from_prefix_suffix::<_, [u8; 5]>(source, None, cast_type).unwrap_err();
8408                assert!(matches!(err, CastError::Size(_)));
8409                assert!(ptr::eq(err.into_src(), source));
8410
8411                let err =
8412                    ref_from_prefix_suffix::<_, [u8]>(source, Some(5), cast_type).unwrap_err();
8413                assert!(matches!(err, CastError::Size(_)));
8414                assert!(ptr::eq(err.into_src(), source));
8415            }
8416        }
8417
8418        check(&Source([0x0102u16, 0x0304]));
8419        let source = Source([false, true, false, true]);
8420        let source: &Source<[bool]> = &source;
8421        check(source);
8422    }
8423
8424    #[test]
8425    fn test_ref_from_prefix_suffix_typed_source_alignment_error() {
8426        let storage = Align::<[bool; 9], AU64>::new([false; 9]);
8427        for cast_type in [CastType::Prefix, CastType::Suffix] {
8428            let source = match cast_type {
8429                CastType::Prefix => &storage.t[1..],
8430                CastType::Suffix => &storage.t[..],
8431            };
8432            let err = ref_from_prefix_suffix::<_, AU64>(source, None, cast_type).unwrap_err();
8433            assert!(matches!(err, CastError::Alignment(_)));
8434            let recovered: &[bool] = err.into_src();
8435            assert!(ptr::eq(recovered, source));
8436
8437            let err = try_ref_from_prefix_suffix::<_, AU64>(source, cast_type, None).unwrap_err();
8438            assert!(matches!(err, TryCastError::Alignment(_)));
8439            let recovered: &[bool] = err.into_src();
8440            assert!(ptr::eq(recovered, source));
8441        }
8442    }
8443
8444    #[test]
8445    fn test_try_ref_from_prefix_suffix_typed_source() {
8446        #[derive(IntoBytes, Immutable)]
8447        #[repr(transparent)]
8448        struct Source<T: ?Sized>(T);
8449
8450        fn check<S: IntoBytes + Immutable + ?Sized>(source: &S) {
8451            let bytes = source.as_bytes();
8452            assert_eq!(bytes, [0, 1, 0, 1]);
8453
8454            for cast_type in [CastType::Prefix, CastType::Suffix] {
8455                let (expected, expected_rest) = match cast_type {
8456                    CastType::Prefix => (&bytes[..3], &bytes[3..]),
8457                    CastType::Suffix => (&bytes[1..], &bytes[..1]),
8458                };
8459                for meta in [None, Some(1)] {
8460                    let (value, rest) =
8461                        try_ref_from_prefix_suffix::<_, [[bool; 3]]>(source, cast_type, meta)
8462                            .unwrap();
8463                    assert_eq!(value.as_bytes(), expected);
8464                    assert!(ptr::eq(value.as_bytes(), expected));
8465                    assert!(ptr::eq(rest, expected_rest));
8466                }
8467
8468                let err = try_ref_from_prefix_suffix::<_, [bool; 5]>(source, cast_type, None)
8469                    .unwrap_err();
8470                assert!(matches!(err, TryCastError::Size(_)));
8471                assert!(ptr::eq(err.into_src(), source));
8472
8473                let err = try_ref_from_prefix_suffix::<_, [bool]>(source, cast_type, Some(5))
8474                    .unwrap_err();
8475                assert!(matches!(err, TryCastError::Size(_)));
8476                assert!(ptr::eq(err.into_src(), source));
8477            }
8478        }
8479
8480        check(&Source([u16::from_ne_bytes([0, 1]); 2]));
8481        let source = Source([false, true, false, true]);
8482        let source: &Source<[bool]> = &source;
8483        check(source);
8484    }
8485
8486    #[test]
8487    fn test_try_ref_from_prefix_suffix_typed_source_validity_error() {
8488        fn check<S: IntoBytes + Immutable + ?Sized>(source: &S) {
8489            for cast_type in [CastType::Prefix, CastType::Suffix] {
8490                let err =
8491                    try_ref_from_prefix_suffix::<_, bool>(source, cast_type, None).unwrap_err();
8492                assert!(matches!(err, TryCastError::Validity(_)));
8493                assert!(ptr::eq(err.into_src(), source));
8494
8495                for meta in [None, Some(1)] {
8496                    let err = try_ref_from_prefix_suffix::<_, [bool]>(source, cast_type, meta)
8497                        .unwrap_err();
8498                    assert!(matches!(err, TryCastError::Validity(_)));
8499                    assert!(ptr::eq(err.into_src(), source));
8500                }
8501            }
8502        }
8503
8504        let source = [u16::from_ne_bytes([2, 2]); 2];
8505        check(&source);
8506        check(&source[..]);
8507        check(source.as_bytes());
8508    }
8509
8510    #[test]
8511    fn test_try_ref_from_prefix_suffix() {
8512        use crate::util::testutil::Align;
8513        let bytes = &Align::<[u8; 4], u32>::new([0u8; 4]).t[..];
8514        let (r, rest): (&u32, &[u8]) = u32::try_ref_from_prefix(bytes).unwrap();
8515        assert_eq!(*r, 0);
8516        assert_eq!(rest.len(), 0);
8517
8518        let (rest, r): (&[u8], &u32) = u32::try_ref_from_suffix(bytes).unwrap();
8519        assert_eq!(*r, 0);
8520        assert_eq!(rest.len(), 0);
8521    }
8522
8523    #[test]
8524    fn test_raw_dangling() {
8525        use crate::util::AsAddress;
8526        let ptr: NonNull<u32> = u32::raw_dangling();
8527        assert_eq!(AsAddress::addr(ptr), 1);
8528
8529        let ptr: NonNull<[u32]> = <[u32]>::raw_dangling();
8530        assert_eq!(AsAddress::addr(ptr), 1);
8531    }
8532
8533    #[test]
8534    fn test_try_ref_from_prefix_with_elems() {
8535        use crate::util::testutil::Align;
8536        let bytes = &Align::<[u8; 8], u32>::new([0u8; 8]).t[..];
8537        let (r, rest): (&[u32], &[u8]) = <[u32]>::try_ref_from_prefix_with_elems(bytes, 2).unwrap();
8538        assert_eq!(r.len(), 2);
8539        assert_eq!(rest.len(), 0);
8540    }
8541
8542    #[test]
8543    fn test_try_ref_from_suffix_with_elems() {
8544        use crate::util::testutil::Align;
8545        let bytes = &Align::<[u8; 8], u32>::new([0u8; 8]).t[..];
8546        let (rest, r): (&[u8], &[u32]) = <[u32]>::try_ref_from_suffix_with_elems(bytes, 2).unwrap();
8547        assert_eq!(r.len(), 2);
8548        assert_eq!(rest.len(), 0);
8549    }
8550}