Skip to main content

zerocopy/
ref.rs

1// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0 OR MIT
2//
3// Copyright 2024 The Fuchsia Authors
4//
5// Licensed under the 2-Clause BSD License <LICENSE-BSD or
6// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
7// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
8// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
9// This file may not be copied, modified, or distributed except according to
10// those terms.
11use super::*;
12use crate::pointer::{
13    BecauseMutationCompatible, BecauseSharedCompatible, MutationCompatible, TransmuteFromPtr,
14};
15
16mod def {
17    use core::marker::PhantomData;
18
19    use crate::{
20        ByteSlice, ByteSliceMut, CloneableByteSlice, CopyableByteSlice, IntoByteSlice,
21        IntoByteSliceMut, KnownLayout, PointerMetadata,
22    };
23
24    /// A typed reference derived from a byte slice.
25    ///
26    /// A `Ref<B, T>` is a reference to a `T` which is stored in a byte slice, `B`.
27    /// Unlike a native reference (`&T` or `&mut T`), `Ref<B, T>` has the same
28    /// mutability as the byte slice it was constructed from (`B`).
29    ///
30    /// # Examples
31    ///
32    /// `Ref` can be used to treat a sequence of bytes as a structured type, and
33    /// to read and write the fields of that type as if the byte slice reference
34    /// were simply a reference to that type.
35    ///
36    /// ```rust
37    /// use zerocopy::*;
38    /// # use zerocopy_derive::*;
39    ///
40    /// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
41    /// #[repr(C)]
42    /// struct UdpHeader {
43    ///     src_port: [u8; 2],
44    ///     dst_port: [u8; 2],
45    ///     length: [u8; 2],
46    ///     checksum: [u8; 2],
47    /// }
48    ///
49    /// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
50    /// #[repr(C, packed)]
51    /// struct UdpPacket {
52    ///     header: UdpHeader,
53    ///     body: [u8],
54    /// }
55    ///
56    /// impl UdpPacket {
57    ///     pub fn parse<B: ByteSlice>(bytes: B) -> Option<Ref<B, UdpPacket>> {
58    ///         Ref::from_bytes(bytes).ok()
59    ///     }
60    /// }
61    /// ```
62    pub struct Ref<B, T: ?Sized> {
63        // INVARIANTS:
64        // - The referent (via `.deref`, `.deref_mut`, `.into`) byte slice is
65        //   aligned to `T`'s alignment, and its size is valid for `T`.
66        // - If `T: KnownLayout`, let `metadata` be
67        //   `T::PointerMetadata::from_elem_count` applied to `elem_count`.
68        //   Then `T::size_for_metadata(metadata)` is `Some(referent.len())`.
69        bytes: B,
70        // Ignored when `T` does not implement `KnownLayout`.
71        elem_count: usize,
72        _marker: PhantomData<T>,
73    }
74
75    impl<B, T> Ref<B, T> {
76        /// Constructs a new `Ref` to a sized `T`.
77        ///
78        /// # Safety
79        ///
80        /// `bytes` dereferences (via [`deref`], [`deref_mut`], and [`into`]) to
81        /// a byte slice which is aligned to `T`'s alignment and whose size is
82        /// `size_of::<T>()`.
83        ///
84        /// [`deref`]: core::ops::Deref::deref
85        /// [`deref_mut`]: core::ops::DerefMut::deref_mut
86        /// [`into`]: core::convert::Into::into
87        pub(super) unsafe fn new_sized_unchecked(bytes: B) -> Ref<B, T> {
88            // INVARIANTS: The caller has promised that `bytes`'s referent is
89            // validly aligned and has size `size_of::<T>()`. If `T:
90            // KnownLayout`, then, since `T` is sized, `T::PointerMetadata` is
91            // `()`. `from_elem_count` returns `()` for any element count, and
92            // `T::size_for_metadata(()) == Some(size_of::<T>())`. `size_of`
93            // reports this size in bytes [1].
94            //
95            // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of.html:
96            //
97            //     Returns the size of a type in bytes.
98            Ref { bytes, elem_count: 0, _marker: PhantomData }
99        }
100    }
101
102    impl<B, T: KnownLayout + ?Sized> Ref<B, T> {
103        /// Constructs a new `Ref`.
104        ///
105        /// # Safety
106        ///
107        /// `bytes` dereferences (via [`deref`], [`deref_mut`], and [`into`]) to
108        /// a byte slice which is aligned to `T`'s alignment and satisfies
109        /// `T::size_for_metadata(metadata) == Some(referent.len())`.
110        ///
111        /// [`deref`]: core::ops::Deref::deref
112        /// [`deref_mut`]: core::ops::DerefMut::deref_mut
113        /// [`into`]: core::convert::Into::into
114        pub(super) unsafe fn new_unchecked(bytes: B, metadata: T::PointerMetadata) -> Ref<B, T> {
115            // INVARIANTS: The caller has promised that `bytes`'s referent is
116            // validly aligned and has exactly the size described by `metadata`.
117            // `KnownLayout::PointerMetadata` is `()` for sized types and
118            // `usize` for slice DSTs. For both permitted metadata types,
119            // `from_elem_count(metadata.to_elem_count()) == metadata`: `()`
120            // round-trips through zero, while `usize` round-trips through
121            // itself. Thus, storing the element count preserves the metadata
122            // whose size the caller validated. This agrees with Rust's
123            // language-level definition of slice pointer metadata [1].
124            //
125            // [1] Per https://doc.rust-lang.org/1.56.0/reference/dynamically-sized-types.html:
126            //
127            //     Pointers to slices also store the number of elements of the
128            //     slice.
129            Ref { bytes, elem_count: metadata.to_elem_count(), _marker: PhantomData }
130        }
131
132        /// Gets the pointer metadata represented by this `Ref`.
133        #[inline(always)]
134        pub(super) fn pointer_metadata(&self) -> T::PointerMetadata {
135            // INVARIANTS: `KnownLayout::PointerMetadata` is either `()` or
136            // `usize`. For `()`, `from_elem_count` ignores the element count;
137            // for `usize`, it returns the element count unchanged.
138            T::PointerMetadata::from_elem_count(self.elem_count)
139        }
140    }
141
142    impl<B: ByteSlice, T: ?Sized> Ref<B, T> {
143        /// Access the byte slice as a [`ByteSlice`].
144        ///
145        /// # Safety
146        ///
147        /// The caller promises not to call methods on the returned
148        /// [`ByteSlice`] other than `ByteSlice` methods (for example, via
149        /// `Any::downcast_ref`).
150        ///
151        /// `as_byte_slice` promises to return a `ByteSlice` whose referent is
152        /// validly aligned for `T` and has a valid size for `T`. If `T:
153        /// KnownLayout`, then `T::size_for_metadata(self.pointer_metadata())`
154        /// returns `Some(referent.len())`.
155        pub(crate) unsafe fn as_byte_slice(&self) -> &impl ByteSlice {
156            // INVARIANTS: The caller promises not to call methods other than
157            // those on `ByteSlice`. Since `B: ByteSlice`, dereference stability
158            // guarantees that calling `ByteSlice` methods will not change the
159            // address or length of `self.bytes`'s referent.
160            //
161            // SAFETY: By invariant on `self`, the alignment, size, and metadata
162            // postconditions are upheld.
163            &self.bytes
164        }
165    }
166
167    impl<B: ByteSliceMut, T: ?Sized> Ref<B, T> {
168        /// Access the byte slice as a [`ByteSliceMut`].
169        ///
170        /// # Safety
171        ///
172        /// The caller promises not to call methods on the returned
173        /// [`ByteSliceMut`] other than `ByteSliceMut` methods (for example, via
174        /// `Any::downcast_mut`).
175        ///
176        /// `as_byte_slice_mut` promises to return a `ByteSliceMut` whose
177        /// referent is validly aligned for `T` and has a valid size for `T`. If
178        /// `T: KnownLayout`, then
179        /// `T::size_for_metadata(self.pointer_metadata())` returns
180        /// `Some(referent.len())`.
181        pub(crate) unsafe fn as_byte_slice_mut(&mut self) -> &mut impl ByteSliceMut {
182            // INVARIANTS: The caller promises not to call methods other than
183            // those on `ByteSliceMut`. Since `B: ByteSlice`, dereference
184            // stability guarantees that calling `ByteSlice` methods will not
185            // change the address or length of `self.bytes`'s referent.
186            //
187            // SAFETY: By invariant on `self`, the alignment, size, and metadata
188            // postconditions are upheld.
189            &mut self.bytes
190        }
191    }
192
193    impl<'a, B: IntoByteSlice<'a>, T: ?Sized> Ref<B, T> {
194        /// Access the byte slice as an [`IntoByteSlice`].
195        ///
196        /// # Safety
197        ///
198        /// The caller promises not to call methods on the returned
199        /// [`IntoByteSlice`] other than `IntoByteSlice` methods (for example,
200        /// via `Any::downcast_ref`).
201        ///
202        /// `into_byte_slice` promises to return an `IntoByteSlice` whose
203        /// referent is validly aligned for `T` and has a valid size for `T`. If
204        /// `T: KnownLayout`, then
205        /// `T::size_for_metadata(self.pointer_metadata())` returns
206        /// `Some(referent.len())`.
207        pub(crate) unsafe fn into_byte_slice(self) -> impl IntoByteSlice<'a> {
208            // INVARIANTS: The caller promises not to call methods other than
209            // those on `IntoByteSlice`. Since `B: ByteSlice`, dereference
210            // stability guarantees that calling `ByteSlice` methods will not
211            // change the address or length of `self.bytes`'s referent.
212            //
213            // SAFETY: By invariant on `self`, the alignment, size, and metadata
214            // postconditions are upheld.
215            self.bytes
216        }
217    }
218
219    impl<'a, B: IntoByteSliceMut<'a>, T: ?Sized> Ref<B, T> {
220        /// Access the byte slice as an [`IntoByteSliceMut`].
221        ///
222        /// # Safety
223        ///
224        /// The caller promises not to call methods on the returned
225        /// [`IntoByteSliceMut`] other than `IntoByteSliceMut` methods (for
226        /// example, via `Any::downcast_mut`).
227        ///
228        /// `into_byte_slice_mut` promises to return an `IntoByteSliceMut` whose
229        /// referent is validly aligned for `T` and has a valid size for `T`. If
230        /// `T: KnownLayout`, then
231        /// `T::size_for_metadata(self.pointer_metadata())` returns
232        /// `Some(referent.len())`.
233        pub(crate) unsafe fn into_byte_slice_mut(self) -> impl IntoByteSliceMut<'a> {
234            // INVARIANTS: The caller promises not to call methods other than
235            // those on `IntoByteSliceMut`. Since `B: ByteSlice`, dereference
236            // stability guarantees that calling `ByteSlice` methods will not
237            // change the address or length of `self.bytes`'s referent.
238            //
239            // SAFETY: By invariant on `self`, the alignment, size, and metadata
240            // postconditions are upheld.
241            self.bytes
242        }
243    }
244
245    impl<B: CloneableByteSlice + Clone, T: ?Sized> Clone for Ref<B, T> {
246        #[inline]
247        fn clone(&self) -> Ref<B, T> {
248            // INVARIANTS: Since `B: CloneableByteSlice`, `self.bytes.clone()` has
249            // the same address and length as `self.bytes`. We copy
250            // `self.elem_count`, so the clone also has the same metadata. Since
251            // `self` upholds the field invariants, so does the clone.
252            Ref { bytes: self.bytes.clone(), elem_count: self.elem_count, _marker: PhantomData }
253        }
254    }
255
256    // INVARIANTS: Since `B: CopyableByteSlice`, the copied `Ref`'s `bytes` has the
257    // same address and length as the original `Ref`'s `bytes`. The copied
258    // `elem_count` has the same metadata. Since the original upholds the field
259    // invariants, so does the copy.
260    impl<B: CopyableByteSlice + Copy, T: ?Sized> Copy for Ref<B, T> {}
261}
262
263#[allow(unreachable_pub)] // This is a false positive on our MSRV toolchain.
264pub use def::Ref;
265
266use crate::pointer::{
267    invariant::{Aligned, BecauseExclusive, Initialized, Safe, Unaligned},
268    BecauseRead, PtrInner,
269};
270
271impl<B, T> Ref<B, T>
272where
273    B: ByteSlice,
274{
275    #[must_use = "has no side effects"]
276    pub(crate) fn sized_from(bytes: B) -> Result<Ref<B, T>, CastError<B, T>> {
277        if bytes.len() != mem::size_of::<T>() {
278            return Err(SizeError::new(bytes).into());
279        }
280        if let Err(err) = util::validate_aligned_to::<_, T>(bytes.deref()) {
281            return Err(err.with_src(bytes).into());
282        }
283
284        // SAFETY: `size_of` returns `T`'s size in bytes [1]. The equality check
285        // above therefore establishes that `bytes` has exactly that byte
286        // length, and `validate_aligned_to` establishes alignment.
287        //
288        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of.html:
289        //
290        //     Returns the size of a type in bytes.
291        Ok(unsafe { Ref::new_sized_unchecked(bytes) })
292    }
293}
294
295impl<B, T> Ref<B, T>
296where
297    B: SplitByteSlice,
298{
299    #[must_use = "has no side effects"]
300    pub(crate) fn sized_from_prefix(bytes: B) -> Result<(Ref<B, T>, B), CastError<B, T>> {
301        if bytes.len() < mem::size_of::<T>() {
302            return Err(SizeError::new(bytes).into());
303        }
304        if let Err(err) = util::validate_aligned_to::<_, T>(bytes.deref()) {
305            return Err(err.with_src(bytes).into());
306        }
307        let (bytes, suffix) = bytes.split_at(mem::size_of::<T>()).map_err(
308            #[inline(always)]
309            |b| SizeError::new(b).into(),
310        )?;
311        // SAFETY: We just validated alignment and that `bytes` is at least as
312        // large as `T`. `bytes.split_at(mem::size_of::<T>())?` ensures that the
313        // new `bytes` is exactly the size of `T`, measured in bytes as specified
314        // for `size_of` [1]. By safety postcondition on
315        // `SplitByteSlice::split_at` we can rely on `split_at` to produce the
316        // correct `bytes` and `suffix`.
317        //
318        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of.html:
319        //
320        //     Returns the size of a type in bytes.
321        let r = unsafe { Ref::new_sized_unchecked(bytes) };
322        Ok((r, suffix))
323    }
324
325    #[must_use = "has no side effects"]
326    pub(crate) fn sized_from_suffix(bytes: B) -> Result<(B, Ref<B, T>), CastError<B, T>> {
327        let bytes_len = bytes.len();
328        let split_at = if let Some(split_at) = bytes_len.checked_sub(mem::size_of::<T>()) {
329            split_at
330        } else {
331            return Err(SizeError::new(bytes).into());
332        };
333        let (prefix, bytes) = bytes.split_at(split_at).map_err(|b| SizeError::new(b).into())?;
334        if let Err(err) = util::validate_aligned_to::<_, T>(bytes.deref()) {
335            return Err(err.with_src(bytes).into());
336        }
337        // SAFETY: Since `split_at` is defined as `bytes_len - size_of::<T>()`,
338        // the `bytes` which results from `let (prefix, bytes) =
339        // bytes.split_at(split_at)?` has length `size_of::<T>()`, measured in
340        // bytes as specified for `size_of` [1]. After constructing `bytes`, we
341        // validate that it has the proper alignment. By safety postcondition on
342        // `SplitByteSlice::split_at` we can rely on `split_at` to produce the
343        // correct `prefix` and `bytes`.
344        //
345        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of.html:
346        //
347        //     Returns the size of a type in bytes.
348        let r = unsafe { Ref::new_sized_unchecked(bytes) };
349        Ok((prefix, r))
350    }
351}
352
353impl<B, T> Ref<B, T>
354where
355    B: ByteSlice,
356    T: KnownLayout + Immutable + ?Sized,
357{
358    /// Constructs a `Ref` from a byte slice.
359    ///
360    /// If the length of `source` is not a [valid size of `T`][valid-size], or
361    /// if `source` is not appropriately aligned for `T`, this returns `Err`. If
362    /// [`T: Unaligned`][t-unaligned], you can [infallibly discard the alignment
363    /// error][size-error-from].
364    ///
365    /// `T` may be a sized type, a slice, or a [slice DST][slice-dst].
366    ///
367    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
368    /// [t-unaligned]: crate::Unaligned
369    /// [size-error-from]: error/struct.SizeError.html#method.from-1
370    /// [slice-dst]: KnownLayout#dynamically-sized-types
371    ///
372    /// # Compile-Time Assertions
373    ///
374    /// This method cannot yet be used on unsized types whose dynamically-sized
375    /// component is zero-sized. Attempting to use this method on such types
376    /// results in a compile-time assertion error; e.g.:
377    ///
378    /// ```compile_fail,E0080
379    /// use zerocopy::*;
380    /// # use zerocopy_derive::*;
381    ///
382    /// #[derive(Immutable, KnownLayout)]
383    /// #[repr(C)]
384    /// struct ZSTy {
385    ///     leading_sized: u16,
386    ///     trailing_dst: [()],
387    /// }
388    ///
389    /// let _ = Ref::<_, ZSTy>::from_bytes(&b"UU"[..]); // ⚠ Compile Error!
390    /// ```
391    ///
392    #[doc = codegen_section!(
393        header = "h5",
394        bench = "ref_type_from_bytes",
395        format = "coco",
396        arity = 3,
397        [
398            open
399            @index 1
400            @title "Sized"
401            @variant "static_size"
402        ],
403        [
404            @index 2
405            @title "Unsized"
406            @variant "dynamic_size"
407        ],
408        [
409            @index 3
410            @title "Dynamically Padded"
411            @variant "dynamic_padding"
412        ]
413    )]
414    #[must_use = "has no side effects"]
415    #[inline]
416    pub fn from_bytes(source: B) -> Result<Ref<B, T>, CastError<B, T>> {
417        static_assert_dst_is_not_zst!(T);
418        let metadata = match Ptr::from_ref(source.deref())
419            .try_cast_into_no_leftover::<T, BecauseImmutable>(None)
420        {
421            Ok(ptr) => T::pointer_to_metadata(ptr.as_inner().as_ptr()),
422            Err(e) => return Err(e.with_src(()).with_src(source)),
423        };
424        // SAFETY: By its safety postcondition, `try_cast_into_no_leftover`
425        // returned a `Ptr<T>` aligned as required for references [2], over the
426        // same byte range as `source.deref()`. `pointer_to_metadata` returns
427        // the metadata stored in that pointer, and `size_for_metadata` computes
428        // the corresponding dynamically-known byte size [1]. Thus,
429        // `T::size_for_metadata(metadata)` is `Some(source.len())`.
430        // `ByteSlice` and its applicable subtraits guarantee that the stored
431        // `source` continues to dereference or convert to that address and
432        // length. These facts establish both preconditions of `new_unchecked`.
433        //
434        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of_val.html:
435        //
436        //     Returns the size of the pointed-to value in bytes.
437        //
438        //     ... when `T` has no statically-known size ... `size_of_val` can
439        //     be used to get the dynamically-known size.
440        //
441        // [2] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.align_of_val.html:
442        //
443        //     Returns the ABI-required minimum alignment of the type of the
444        //     value that `val` points to.
445        //
446        //     Every reference to a value of the type `T` must be a multiple of
447        //     this number.
448        Ok(unsafe { Ref::new_unchecked(source, metadata) })
449    }
450}
451
452impl<B, T> Ref<B, T>
453where
454    B: SplitByteSlice,
455    T: KnownLayout + Immutable + ?Sized,
456{
457    /// Constructs a `Ref` from the prefix of a byte slice.
458    ///
459    /// This method computes the [largest possible size of `T`][valid-size] that
460    /// can fit in the leading bytes of `source`, then attempts to return both a
461    /// `Ref` to those bytes, and a reference to the remaining bytes. If there
462    /// are insufficient bytes, or if `source` is not appropriately aligned,
463    /// this returns `Err`. If [`T: Unaligned`][t-unaligned], you can
464    /// [infallibly discard the alignment error][size-error-from].
465    ///
466    /// `T` may be a sized type, a slice, or a [slice DST][slice-dst].
467    ///
468    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
469    /// [t-unaligned]: crate::Unaligned
470    /// [size-error-from]: error/struct.SizeError.html#method.from-1
471    /// [slice-dst]: KnownLayout#dynamically-sized-types
472    ///
473    /// # Compile-Time Assertions
474    ///
475    /// This method cannot yet be used on unsized types whose dynamically-sized
476    /// component is zero-sized. Attempting to use this method on such types
477    /// results in a compile-time assertion error; e.g.:
478    ///
479    /// ```compile_fail,E0080
480    /// use zerocopy::*;
481    /// # use zerocopy_derive::*;
482    ///
483    /// #[derive(Immutable, KnownLayout)]
484    /// #[repr(C)]
485    /// struct ZSTy {
486    ///     leading_sized: u16,
487    ///     trailing_dst: [()],
488    /// }
489    ///
490    /// let _ = Ref::<_, ZSTy>::from_prefix(&b"UU"[..]); // ⚠ Compile Error!
491    /// ```
492    ///
493    #[doc = codegen_section!(
494        header = "h5",
495        bench = "ref_type_from_prefix",
496        format = "coco",
497        arity = 3,
498        [
499            open
500            @index 1
501            @title "Sized"
502            @variant "static_size"
503        ],
504        [
505            @index 2
506            @title "Unsized"
507            @variant "dynamic_size"
508        ],
509        [
510            @index 3
511            @title "Dynamically Padded"
512            @variant "dynamic_padding"
513        ]
514    )]
515    #[must_use = "has no side effects"]
516    #[inline]
517    pub fn from_prefix(source: B) -> Result<(Ref<B, T>, B), CastError<B, T>> {
518        static_assert_dst_is_not_zst!(T);
519        let (metadata, remainder) = match Ptr::from_ref(source.deref())
520            .try_cast_into::<T, BecauseImmutable>(CastType::Prefix, None)
521        {
522            Ok((ptr, remainder)) => (T::pointer_to_metadata(ptr.as_inner().as_ptr()), remainder),
523            Err(e) => {
524                return Err(e.with_src(()).with_src(source));
525            }
526        };
527
528        // SAFETY: `remainder` is constructed as a subset of `source`, and so it
529        // cannot have a larger size than `source`. Both of their `len` methods
530        // measure bytes (`source` deref's to `[u8]`, and `remainder` is a
531        // `Ptr<[u8]>`), so `source.len() >= remainder.len()`. Thus, this cannot
532        // underflow.
533        #[allow(unstable_name_collisions)]
534        let split_at = unsafe { source.len().unchecked_sub(remainder.len()) };
535        let (bytes, suffix) = source.split_at(split_at).map_err(|b| SizeError::new(b).into())?;
536        // SAFETY: By its safety postcondition, `try_cast_into` returned an
537        // `Ptr<T>` aligned as required for references [2], and a remainder
538        // which are non-overlapping, cover `source.deref()`, and place the
539        // `Ptr<T>` at `source.deref()`'s address.
540        // Therefore, `split_at` is the typed pointer's byte length. By the
541        // safety postcondition of `SplitByteSlice::split_at`, `bytes` has that
542        // length and address. `pointer_to_metadata` returns the metadata stored
543        // in the typed pointer, and `size_for_metadata` computes the
544        // corresponding dynamically-known byte size [1]. Thus,
545        // `T::size_for_metadata(metadata)` is `Some(bytes.len())`. The
546        // `SplitByteSlice` and `ByteSlice` contracts preserve the established
547        // address and length, satisfying both preconditions of
548        // `new_unchecked`.
549        //
550        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of_val.html:
551        //
552        //     Returns the size of the pointed-to value in bytes.
553        //
554        //     ... when `T` has no statically-known size ... `size_of_val` can
555        //     be used to get the dynamically-known size.
556        //
557        // [2] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.align_of_val.html:
558        //
559        //     Returns the ABI-required minimum alignment of the type of the
560        //     value that `val` points to.
561        //
562        //     Every reference to a value of the type `T` must be a multiple of
563        //     this number.
564        let r = unsafe { Ref::new_unchecked(bytes, metadata) };
565        Ok((r, suffix))
566    }
567
568    /// Constructs a `Ref` from the suffix of a byte slice.
569    ///
570    /// This method computes the [largest possible size of `T`][valid-size] that
571    /// can fit in the trailing bytes of `source`, then attempts to return both
572    /// a `Ref` to those bytes, and a reference to the preceding bytes. If there
573    /// are insufficient bytes, or if that suffix of `source` is not
574    /// appropriately aligned, this returns `Err`. If [`T:
575    /// Unaligned`][t-unaligned], you can [infallibly discard the alignment
576    /// error][size-error-from].
577    ///
578    /// `T` may be a sized type, a slice, or a [slice DST][slice-dst].
579    ///
580    /// [valid-size]: crate::KnownLayout#what-is-a-valid-size
581    /// [t-unaligned]: crate::Unaligned
582    /// [size-error-from]: error/struct.SizeError.html#method.from-1
583    /// [slice-dst]: KnownLayout#dynamically-sized-types
584    ///
585    /// # Compile-Time Assertions
586    ///
587    /// This method cannot yet be used on unsized types whose dynamically-sized
588    /// component is zero-sized. Attempting to use this method on such types
589    /// results in a compile-time assertion error; e.g.:
590    ///
591    /// ```compile_fail,E0080
592    /// use zerocopy::*;
593    /// # use zerocopy_derive::*;
594    ///
595    /// #[derive(Immutable, KnownLayout)]
596    /// #[repr(C)]
597    /// struct ZSTy {
598    ///     leading_sized: u16,
599    ///     trailing_dst: [()],
600    /// }
601    ///
602    /// let _ = Ref::<_, ZSTy>::from_suffix(&b"UU"[..]); // ⚠ Compile Error!
603    /// ```
604    ///
605    #[doc = codegen_section!(
606        header = "h5",
607        bench = "ref_type_from_suffix",
608        format = "coco",
609        arity = 3,
610        [
611            open
612            @index 1
613            @title "Sized"
614            @variant "static_size"
615        ],
616        [
617            @index 2
618            @title "Unsized"
619            @variant "dynamic_size"
620        ],
621        [
622            @index 3
623            @title "Dynamically Padded"
624            @variant "dynamic_padding"
625        ]
626    )]
627    #[must_use = "has no side effects"]
628    #[inline]
629    pub fn from_suffix(source: B) -> Result<(B, Ref<B, T>), CastError<B, T>> {
630        static_assert_dst_is_not_zst!(T);
631        let (metadata, remainder) = match Ptr::from_ref(source.deref())
632            .try_cast_into::<T, BecauseImmutable>(CastType::Suffix, None)
633        {
634            Ok((ptr, remainder)) => (T::pointer_to_metadata(ptr.as_inner().as_ptr()), remainder),
635            Err(e) => {
636                let e = e.with_src(());
637                return Err(e.with_src(source));
638            }
639        };
640
641        let split_at = remainder.len();
642        let (prefix, bytes) = source.split_at(split_at).map_err(|b| SizeError::new(b).into())?;
643        // SAFETY: By its safety postcondition, `try_cast_into` returned an
644        // `Ptr<T>` aligned as required for references [2], and a remainder
645        // which are non-overlapping, cover `source.deref()`, and place the
646        // remainder at `source.deref()`'s address. More precisely,
647        // `PtrInner::try_cast_into` constructs the typed suffix from the
648        // `r_slice` produced by `split_at_unchecked(split_at)` and returns its
649        // `l_slice` as `remainder`. Thus, even when `T` is zero-sized, the typed
650        // pointer and the `bytes` produced by splitting `source` at
651        // `remainder.len()` have the same address and length. By the safety
652        // postcondition of `SplitByteSlice::split_at`, `bytes` retains that
653        // address and length. `pointer_to_metadata` returns the metadata stored
654        // in the typed pointer, and `size_for_metadata` computes the
655        // corresponding dynamically-known byte size [1]. Thus,
656        // `T::size_for_metadata(metadata)` is `Some(bytes.len())`. The
657        // `SplitByteSlice` and `ByteSlice` contracts preserve the established
658        // address and length, satisfying both preconditions of
659        // `new_unchecked`.
660        //
661        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of_val.html:
662        //
663        //     Returns the size of the pointed-to value in bytes.
664        //
665        //     ... when `T` has no statically-known size ... `size_of_val` can
666        //     be used to get the dynamically-known size.
667        //
668        // [2] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.align_of_val.html:
669        //
670        //     Returns the ABI-required minimum alignment of the type of the
671        //     value that `val` points to.
672        //
673        //     Every reference to a value of the type `T` must be a multiple of
674        //     this number.
675        let r = unsafe { Ref::new_unchecked(bytes, metadata) };
676        Ok((prefix, r))
677    }
678}
679
680impl<B, T> Ref<B, T>
681where
682    B: ByteSlice,
683    T: KnownLayout<PointerMetadata = usize> + Immutable + ?Sized,
684{
685    /// Constructs a `Ref` from the given bytes with DST length equal to `count`
686    /// without copying.
687    ///
688    /// This method attempts to return a `Ref` to the prefix of `source`
689    /// interpreted as a `T` with `count` trailing elements, and a reference to
690    /// the remaining bytes. If the length of `source` is not equal to the size
691    /// of `Self` with `count` elements, or if `source` is not appropriately
692    /// aligned, this returns `Err`. If [`T: Unaligned`][t-unaligned], you can
693    /// [infallibly discard the alignment error][size-error-from].
694    ///
695    /// [t-unaligned]: crate::Unaligned
696    /// [size-error-from]: error/struct.SizeError.html#method.from-1
697    ///
698    /// # Compile-Time Assertions
699    ///
700    /// This method cannot yet be used on unsized types whose dynamically-sized
701    /// component is zero-sized. Attempting to use this method on such types
702    /// results in a compile-time assertion error; e.g.:
703    ///
704    /// ```compile_fail,E0080
705    /// use zerocopy::*;
706    /// # use zerocopy_derive::*;
707    ///
708    /// #[derive(Immutable, KnownLayout)]
709    /// #[repr(C)]
710    /// struct ZSTy {
711    ///     leading_sized: u16,
712    ///     trailing_dst: [()],
713    /// }
714    ///
715    /// let _ = Ref::<_, ZSTy>::from_bytes_with_elems(&b"UU"[..], 42); // ⚠ Compile Error!
716    /// ```
717    ///
718    #[doc = codegen_section!(
719        header = "h5",
720        bench = "ref_type_from_bytes_with_elems",
721        format = "coco",
722        arity = 2,
723        [
724            open
725            @index 1
726            @title "Unsized"
727            @variant "dynamic_size"
728        ],
729        [
730            @index 2
731            @title "Dynamically Padded"
732            @variant "dynamic_padding"
733        ]
734    )]
735    #[inline]
736    pub fn from_bytes_with_elems(source: B, count: usize) -> Result<Ref<B, T>, CastError<B, T>> {
737        static_assert_dst_is_not_zst!(T);
738        let expected_len = match T::size_for_metadata(count) {
739            Some(len) => len,
740            None => return Err(SizeError::new(source).into()),
741        };
742        if source.len() != expected_len {
743            return Err(SizeError::new(source).into());
744        }
745        if let Err(e) = Ptr::from_ref(source.deref())
746            .try_cast_into_no_leftover::<T, BecauseImmutable>(Some(count))
747        {
748            return Err(e.with_src(()).with_src(source));
749        }
750        // SAFETY: `size_for_metadata(count)` returned `expected_len`, and the
751        // equality check established that this is `source.len()`. This is the
752        // dynamically-known byte size described by `size_of_val` [1]. By its
753        // safety postcondition, `try_cast_into_no_leftover(Some(count))` only
754        // succeeded after producing a `Ptr<T>` aligned as required for
755        // references [2], with that metadata over the same byte range as
756        // `source.deref()`. `ByteSlice` and its applicable subtraits guarantee
757        // that the stored `source` continues to dereference or convert to that
758        // address and length. These facts establish both preconditions of
759        // `new_unchecked`.
760        //
761        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of_val.html:
762        //
763        //     Returns the size of the pointed-to value in bytes.
764        //
765        //     ... when `T` has no statically-known size ... `size_of_val` can
766        //     be used to get the dynamically-known size.
767        //
768        // [2] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.align_of_val.html:
769        //
770        //     Returns the ABI-required minimum alignment of the type of the
771        //     value that `val` points to.
772        //
773        //     Every reference to a value of the type `T` must be a multiple of
774        //     this number.
775        Ok(unsafe { Ref::new_unchecked(source, count) })
776    }
777}
778
779impl<B, T> Ref<B, T>
780where
781    B: SplitByteSlice,
782    T: KnownLayout<PointerMetadata = usize> + Immutable + ?Sized,
783{
784    /// Constructs a `Ref` from the prefix of the given bytes with DST
785    /// length equal to `count` without copying.
786    ///
787    /// This method attempts to return a `Ref` to the prefix of `source`
788    /// interpreted as a `T` with `count` trailing elements, and a reference to
789    /// the remaining bytes. If there are insufficient bytes, or if `source` is
790    /// not appropriately aligned, this returns `Err`. If [`T:
791    /// Unaligned`][t-unaligned], you can [infallibly discard the alignment
792    /// error][size-error-from].
793    ///
794    /// [t-unaligned]: crate::Unaligned
795    /// [size-error-from]: error/struct.SizeError.html#method.from-1
796    ///
797    /// # Compile-Time Assertions
798    ///
799    /// This method cannot yet be used on unsized types whose dynamically-sized
800    /// component is zero-sized. Attempting to use this method on such types
801    /// results in a compile-time assertion error; e.g.:
802    ///
803    /// ```compile_fail,E0080
804    /// use zerocopy::*;
805    /// # use zerocopy_derive::*;
806    ///
807    /// #[derive(Immutable, KnownLayout)]
808    /// #[repr(C)]
809    /// struct ZSTy {
810    ///     leading_sized: u16,
811    ///     trailing_dst: [()],
812    /// }
813    ///
814    /// let _ = Ref::<_, ZSTy>::from_prefix_with_elems(&b"UU"[..], 42); // ⚠ Compile Error!
815    /// ```
816    ///
817    #[doc = codegen_section!(
818        header = "h5",
819        bench = "ref_type_from_prefix_with_elems",
820        format = "coco",
821        arity = 2,
822        [
823            open
824            @index 1
825            @title "Unsized"
826            @variant "dynamic_size"
827        ],
828        [
829            @index 2
830            @title "Dynamically Padded"
831            @variant "dynamic_padding"
832        ]
833    )]
834    #[inline]
835    pub fn from_prefix_with_elems(
836        source: B,
837        count: usize,
838    ) -> Result<(Ref<B, T>, B), CastError<B, T>> {
839        static_assert_dst_is_not_zst!(T);
840        let remainder = match Ptr::from_ref(source.deref())
841            .try_cast_into::<T, BecauseImmutable>(CastType::Prefix, Some(count))
842        {
843            Ok((_, remainder)) => remainder,
844            Err(e) => return Err(e.with_src(()).with_src(source)),
845        };
846
847        // SAFETY: By `Ptr::try_cast_into`'s safety postcondition, `remainder`
848        // refers to a byte subrange within `source.deref()`, and by
849        // `ByteSlice`'s dereference-stability contract, `source.len()` equals
850        // `source.deref().len()`. Both `len` methods measure bytes, so
851        // `source.len() >= remainder.len()` and `unchecked_sub` cannot
852        // underflow.
853        #[allow(unstable_name_collisions)]
854        let split_at = unsafe { source.len().unchecked_sub(remainder.len()) };
855        let (bytes, suffix) = source.split_at(split_at).map_err(SizeError::new)?;
856        // SAFETY: By its safety postcondition, `try_cast_into` validated
857        // `Some(count)` via `T::size_for_metadata(count)` [1] and returned a
858        // `Ptr<T>` aligned as required for references [2] alongside a
859        // non-overlapping `remainder`, which together cover `source.deref()`
860        // and place the `Ptr<T>` at `source.deref()`'s address. Therefore,
861        // `split_at` equals that `Ptr<T>`'s byte length, for which
862        // `T::size_for_metadata(count)` returned `Some(split_at)`. By the
863        // safety postcondition of `SplitByteSlice::split_at`, `bytes` has
864        // `source.deref()`'s aligned address and length `split_at`, and
865        // `ByteSlice` and its applicable subtraits preserve that address and
866        // length across `deref`, `deref_mut`, and `into`, satisfying both
867        // preconditions of `new_unchecked`.
868        //
869        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of_val.html:
870        //
871        //     Returns the size of the pointed-to value in bytes.
872        //
873        //     ... when `T` has no statically-known size ... `size_of_val` can
874        //     be used to get the dynamically-known size.
875        //
876        // [2] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.align_of_val.html:
877        //
878        //     Returns the ABI-required minimum alignment of the type of the
879        //     value that `val` points to.
880        //
881        //     Every reference to a value of the type `T` must be a multiple of
882        //     this number.
883        let r = unsafe { Ref::new_unchecked(bytes, count) };
884        Ok((r, suffix))
885    }
886
887    /// Constructs a `Ref` from the suffix of the given bytes with DST length
888    /// equal to `count` without copying.
889    ///
890    /// This method attempts to return a `Ref` to the suffix of `source`
891    /// interpreted as a `T` with `count` trailing elements, and a reference to
892    /// the preceding bytes. If there are insufficient bytes, or if that suffix
893    /// of `source` is not appropriately aligned, this returns `Err`. If [`T:
894    /// Unaligned`][t-unaligned], you can [infallibly discard the alignment
895    /// error][size-error-from].
896    ///
897    /// [t-unaligned]: crate::Unaligned
898    /// [size-error-from]: error/struct.SizeError.html#method.from-1
899    ///
900    /// # Compile-Time Assertions
901    ///
902    /// This method cannot yet be used on unsized types whose dynamically-sized
903    /// component is zero-sized. Attempting to use this method on such types
904    /// results in a compile-time assertion error; e.g.:
905    ///
906    /// ```compile_fail,E0080
907    /// use zerocopy::*;
908    /// # use zerocopy_derive::*;
909    ///
910    /// #[derive(Immutable, KnownLayout)]
911    /// #[repr(C)]
912    /// struct ZSTy {
913    ///     leading_sized: u16,
914    ///     trailing_dst: [()],
915    /// }
916    ///
917    /// let _ = Ref::<_, ZSTy>::from_suffix_with_elems(&b"UU"[..], 42); // ⚠ Compile Error!
918    /// ```
919    ///
920    #[doc = codegen_section!(
921        header = "h5",
922        bench = "ref_type_from_suffix_with_elems",
923        format = "coco",
924        arity = 2,
925        [
926            open
927            @index 1
928            @title "Unsized"
929            @variant "dynamic_size"
930        ],
931        [
932            @index 2
933            @title "Dynamically Padded"
934            @variant "dynamic_padding"
935        ]
936    )]
937    #[inline]
938    pub fn from_suffix_with_elems(
939        source: B,
940        count: usize,
941    ) -> Result<(B, Ref<B, T>), CastError<B, T>> {
942        static_assert_dst_is_not_zst!(T);
943        let remainder = match Ptr::from_ref(source.deref())
944            .try_cast_into::<T, BecauseImmutable>(CastType::Suffix, Some(count))
945        {
946            Ok((_, remainder)) => remainder,
947            Err(e) => return Err(e.with_src(()).with_src(source)),
948        };
949
950        let split_at = remainder.len();
951        let (prefix, bytes) = source.split_at(split_at).map_err(SizeError::new)?;
952        // SAFETY: By its safety postcondition, `try_cast_into` validated
953        // `Some(count)` via `T::size_for_metadata(count)` [1] and returned a
954        // `Ptr<T>` aligned as required for references [2] alongside a
955        // non-overlapping `remainder`, which together cover `source.deref()`
956        // and place `remainder` at `source.deref()`'s address. More precisely,
957        // `PtrInner::try_cast_into` constructs the typed suffix from the
958        // `r_slice` produced by `split_at_unchecked(split_at)` and returns its
959        // `l_slice` as `remainder`. Thus, even when the `T` instance has size
960        // zero, the typed pointer and the `bytes` produced by splitting
961        // `source` at `remainder.len()` have the same aligned address and byte
962        // length, for which `T::size_for_metadata(count)` returned
963        // `Some(bytes.len())`. By `SplitByteSlice`, `ByteSlice`, and its
964        // applicable subtraits, `bytes` retains that address and length across
965        // `deref`, `deref_mut`, and `into`, satisfying both preconditions of
966        // `new_unchecked`.
967        //
968        // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of_val.html:
969        //
970        //     Returns the size of the pointed-to value in bytes.
971        //
972        //     ... when `T` has no statically-known size ... `size_of_val` can
973        //     be used to get the dynamically-known size.
974        //
975        // [2] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.align_of_val.html:
976        //
977        //     Returns the ABI-required minimum alignment of the type of the
978        //     value that `val` points to.
979        //
980        //     Every reference to a value of the type `T` must be a multiple of
981        //     this number.
982        let r = unsafe { Ref::new_unchecked(bytes, count) };
983        Ok((prefix, r))
984    }
985}
986
987impl<'a, B, T> Ref<B, T>
988where
989    B: 'a + IntoByteSlice<'a>,
990    T: FromBytes + KnownLayout + Immutable + ?Sized,
991{
992    /// Converts this `Ref` into a reference.
993    ///
994    /// `into_ref` consumes the `Ref`, and returns a reference to `T`.
995    ///
996    /// Note: this is an associated function, which means that you have to call
997    /// it as `Ref::into_ref(r)` instead of `r.into_ref()`. This is so that
998    /// there is no conflict with a method on the inner type.
999    ///
1000    #[doc = codegen_section!(
1001        header = "h5",
1002        bench = "ref_type_into_ref",
1003        format = "coco",
1004        arity = 3,
1005        [
1006            open
1007            @index 1
1008            @title "Sized"
1009            @variant "static_size"
1010        ],
1011        [
1012            @index 2
1013            @title "Unsized"
1014            @variant "dynamic_size"
1015        ],
1016        [
1017            @index 3
1018            @title "Dynamically Padded"
1019            @variant "dynamic_padding"
1020        ]
1021    )]
1022    #[must_use = "has no side effects"]
1023    #[inline(always)]
1024    pub fn into_ref(r: Self) -> &'a T {
1025        // Presumably unreachable, since we've guarded each constructor of `Ref`.
1026        static_assert_dst_is_not_zst!(T);
1027
1028        let metadata = r.pointer_metadata();
1029
1030        // SAFETY: We don't call any methods on `b` other than those provided by
1031        // `IntoByteSlice`.
1032        let b = unsafe { r.into_byte_slice() };
1033        let b = b.into_byte_slice();
1034
1035        if let crate::layout::SizeInfo::Sized { .. } = T::LAYOUT.size_info {
1036            let ptr = Ptr::from_ref(b);
1037            // SAFETY: We just checked that `T: Sized`. By invariant on `r`,
1038            // `b`'s size is equal to `size_of::<T>()`.
1039            let ptr = unsafe { cast_for_sized::<T, _, _, _>(ptr) };
1040
1041            // SAFETY: None of the preceding transformations modifies the
1042            // address of the pointer, and by invariant on `r`, we know that it
1043            // is validly-aligned.
1044            let ptr = unsafe { ptr.assume_alignment::<Aligned>() };
1045            return ptr.as_ref();
1046        }
1047
1048        // PANICS: By post-condition on `into_byte_slice`, `b` is aligned for
1049        // `T`, and its size is exactly the size encoded by `metadata`. By
1050        // post-condition, `b.into_byte_slice()` produces a byte slice with
1051        // identical address and length to that produced by `b.deref()`.
1052        let ptr = Ptr::from_ref(b.into_byte_slice())
1053            .try_cast_into_no_leftover::<T, BecauseImmutable>(Some(metadata))
1054            .expect("zerocopy internal error: into_ref should be infallible");
1055        let ptr = ptr.recall_validity();
1056        ptr.as_ref()
1057    }
1058}
1059
1060impl<'a, B, T> Ref<B, T>
1061where
1062    B: 'a + IntoByteSliceMut<'a>,
1063    T: FromBytes + IntoBytes + KnownLayout + ?Sized,
1064{
1065    /// Converts this `Ref` into a mutable reference.
1066    ///
1067    /// `into_mut` consumes the `Ref`, and returns a mutable reference to `T`.
1068    ///
1069    /// Note: this is an associated function, which means that you have to call
1070    /// it as `Ref::into_mut(r)` instead of `r.into_mut()`. This is so that
1071    /// there is no conflict with a method on the inner type.
1072    ///
1073    #[doc = codegen_section!(
1074        header = "h5",
1075        bench = "ref_type_into_mut",
1076        format = "coco",
1077        arity = 2,
1078        [
1079            open
1080            @index 1
1081            @title "Sized"
1082            @variant "static_size"
1083        ],
1084        [
1085            @index 2
1086            @title "Unsized"
1087            @variant "dynamic_size"
1088        ]
1089    )]
1090    #[must_use = "has no side effects"]
1091    #[inline(always)]
1092    pub fn into_mut(r: Self) -> &'a mut T {
1093        // Presumably unreachable, since we've guarded each constructor of `Ref`.
1094        static_assert_dst_is_not_zst!(T);
1095
1096        let metadata = r.pointer_metadata();
1097
1098        // SAFETY: We don't call any methods on `b` other than those provided by
1099        // `IntoByteSliceMut`.
1100        let b = unsafe { r.into_byte_slice_mut() };
1101        let b = b.into_byte_slice_mut();
1102
1103        if let crate::layout::SizeInfo::Sized { .. } = T::LAYOUT.size_info {
1104            let ptr = Ptr::from_mut(b);
1105            // SAFETY: We just checked that `T: Sized`. By invariant on `r`,
1106            // `b`'s size is equal to `size_of::<T>()`.
1107            let ptr = unsafe {
1108                cast_for_sized::<
1109                    T,
1110                    _,
1111                    (BecauseRead, BecauseExclusive),
1112                    (BecauseMutationCompatible, BecauseSharedCompatible),
1113                >(ptr)
1114            };
1115
1116            // SAFETY: None of the preceding transformations modifies the
1117            // address of the pointer, and by invariant on `r`, we know that it
1118            // is validly-aligned.
1119            let ptr = unsafe { ptr.assume_alignment::<Aligned>() };
1120            return ptr.as_mut();
1121        }
1122
1123        // PANICS: By post-condition on `into_byte_slice_mut`, `b` is aligned
1124        // for `T`, and its size is exactly the size encoded by `metadata`. By
1125        // post-condition, `b.into_byte_slice_mut()` produces a byte slice with
1126        // identical address and length to that produced by `b.deref_mut()`.
1127        let ptr = Ptr::from_mut(b.into_byte_slice_mut())
1128            .try_cast_into_no_leftover::<T, BecauseExclusive>(Some(metadata))
1129            .expect("zerocopy internal error: into_mut should be infallible");
1130        let ptr = ptr.recall_validity::<_, (_, (_, _))>();
1131        ptr.as_mut()
1132    }
1133}
1134
1135impl<B, T> Ref<B, T>
1136where
1137    B: ByteSlice,
1138    T: ?Sized,
1139{
1140    /// Gets the underlying bytes.
1141    ///
1142    /// Note: this is an associated function, which means that you have to call
1143    /// it as `Ref::bytes(r)` instead of `r.bytes()`. This is so that there is
1144    /// no conflict with a method on the inner type.
1145    ///
1146    #[doc = codegen_section!(
1147        header = "h5",
1148        bench = "ref_type_bytes",
1149        format = "coco",
1150        arity = 3,
1151        [
1152            open
1153            @index 1
1154            @title "Sized"
1155            @variant "static_size"
1156        ],
1157        [
1158            @index 2
1159            @title "Unsized"
1160            @variant "dynamic_size"
1161        ],
1162        [
1163            @index 3
1164            @title "Dynamically Padded"
1165            @variant "dynamic_padding"
1166        ]
1167    )]
1168    #[inline]
1169    pub fn bytes(r: &Self) -> &[u8] {
1170        // SAFETY: We don't call any methods on `b` other than those provided by
1171        // `ByteSlice`.
1172        unsafe { r.as_byte_slice().deref() }
1173    }
1174}
1175
1176impl<B, T> Ref<B, T>
1177where
1178    B: ByteSliceMut,
1179    T: ?Sized,
1180{
1181    /// Gets the underlying bytes mutably.
1182    ///
1183    /// Note: this is an associated function, which means that you have to call
1184    /// it as `Ref::bytes_mut(r)` instead of `r.bytes_mut()`. This is so that
1185    /// there is no conflict with a method on the inner type.
1186    ///
1187    #[doc = codegen_section!(
1188        header = "h5",
1189        bench = "ref_type_bytes_mut",
1190        format = "coco",
1191        arity = 3,
1192        [
1193            open
1194            @index 1
1195            @title "Sized"
1196            @variant "static_size"
1197        ],
1198        [
1199            @index 2
1200            @title "Unsized"
1201            @variant "dynamic_size"
1202        ],
1203        [
1204            @index 3
1205            @title "Dynamically Padded"
1206            @variant "dynamic_padding"
1207        ]
1208    )]
1209    #[inline]
1210    pub fn bytes_mut(r: &mut Self) -> &mut [u8] {
1211        // SAFETY: We don't call any methods on `b` other than those provided by
1212        // `ByteSliceMut`.
1213        unsafe { r.as_byte_slice_mut().deref_mut() }
1214    }
1215}
1216
1217impl<B, T> Ref<B, T>
1218where
1219    B: ByteSlice,
1220    T: FromBytes,
1221{
1222    /// Reads a copy of `T`.
1223    ///
1224    /// Note: this is an associated function, which means that you have to call
1225    /// it as `Ref::read(r)` instead of `r.read()`. This is so that there is no
1226    /// conflict with a method on the inner type.
1227    ///
1228    #[doc = codegen_section!(
1229        header = "h5",
1230        bench = "ref_type_read_static_size",
1231        format = "coco_static_size",
1232    )]
1233    #[must_use = "has no side effects"]
1234    #[inline]
1235    pub fn read(r: &Self) -> T {
1236        // SAFETY: We don't call any methods on `b` other than those provided by
1237        // `ByteSlice`.
1238        let b = unsafe { r.as_byte_slice() };
1239
1240        // SAFETY: By postcondition on `as_byte_slice`, we know that `b` is a
1241        // valid size and alignment for `T`. By safety invariant on `ByteSlice`,
1242        // we know that this is preserved via `.deref()`. Because `T:
1243        // FromBytes`, it is sound to interpret these bytes as a `T`.
1244        unsafe { ptr::read(b.deref().as_ptr().cast::<T>()) }
1245    }
1246}
1247
1248impl<B, T> Ref<B, T>
1249where
1250    B: ByteSliceMut,
1251    T: IntoBytes,
1252{
1253    /// Writes the bytes of `t` and then forgets `t`.
1254    ///
1255    /// Note: this is an associated function, which means that you have to call
1256    /// it as `Ref::write(r, t)` instead of `r.write(t)`. This is so that there
1257    /// is no conflict with a method on the inner type.
1258    ///
1259    #[doc = codegen_section!(
1260        header = "h5",
1261        bench = "ref_type_write_static_size",
1262        format = "coco_static_size",
1263    )]
1264    #[inline]
1265    pub fn write(r: &mut Self, t: T) {
1266        // SAFETY: We don't call any methods on `b` other than those provided by
1267        // `ByteSliceMut`.
1268        let b = unsafe { r.as_byte_slice_mut() };
1269
1270        // SAFETY: By postcondition on `as_byte_slice_mut`, we know that `b` is a
1271        // valid size and alignment for `T`. By safety invariant on
1272        // `ByteSlice`, we know that this is preserved via `.deref()`. Writing
1273        // `t` to the buffer will allow all of the bytes of `t` to be accessed
1274        // as a `[u8]`, but because `T: IntoBytes`, we know that this is sound.
1275        unsafe { ptr::write(b.deref_mut().as_mut_ptr().cast::<T>(), t) }
1276    }
1277}
1278
1279impl<B, T> Deref for Ref<B, T>
1280where
1281    B: ByteSlice,
1282    T: FromBytes + KnownLayout + Immutable + ?Sized,
1283{
1284    type Target = T;
1285
1286    /// Dereferences the value.
1287    ///
1288    #[doc = codegen_section!(
1289        header = "h5",
1290        bench = "ref_type_deref",
1291        format = "coco",
1292        arity = 3,
1293        [
1294            open
1295            @index 1
1296            @title "Sized"
1297            @variant "static_size"
1298        ],
1299        [
1300            @index 2
1301            @title "Unsized"
1302            @variant "dynamic_size"
1303        ],
1304        [
1305            @index 3
1306            @title "Dynamically Padded"
1307            @variant "dynamic_padding"
1308        ]
1309    )]
1310    #[inline]
1311    fn deref(&self) -> &T {
1312        // Presumably unreachable, since we've guarded each constructor of `Ref`.
1313        static_assert_dst_is_not_zst!(T);
1314
1315        let metadata = self.pointer_metadata();
1316
1317        // SAFETY: We don't call any methods on `b` other than those provided by
1318        // `ByteSlice`.
1319        let b = unsafe { self.as_byte_slice() };
1320        let b = b.deref();
1321
1322        if let crate::layout::SizeInfo::Sized { .. } = T::LAYOUT.size_info {
1323            let ptr = Ptr::from_ref(b);
1324            // SAFETY: We just checked that `T: Sized`. By invariant on `r`,
1325            // `b`'s size is equal to `size_of::<T>()`.
1326            let ptr = unsafe { cast_for_sized::<T, _, _, _>(ptr) };
1327
1328            // SAFETY: None of the preceding transformations modifies the
1329            // address of the pointer, and by invariant on `r`, we know that it
1330            // is validly-aligned.
1331            let ptr = unsafe { ptr.assume_alignment::<Aligned>() };
1332            return ptr.as_ref();
1333        }
1334
1335        // PANICS: By postcondition on `as_byte_slice`, `b` is aligned for `T`,
1336        // and its size is exactly the size encoded by `metadata`. By invariant
1337        // on `ByteSlice`, these are preserved through `.deref()`, so this
1338        // `unwrap` will not panic.
1339        let ptr = Ptr::from_ref(b)
1340            .try_cast_into_no_leftover::<T, BecauseImmutable>(Some(metadata))
1341            .expect("zerocopy internal error: Deref::deref should be infallible");
1342        let ptr = ptr.recall_validity();
1343        ptr.as_ref()
1344    }
1345}
1346
1347impl<B, T> DerefMut for Ref<B, T>
1348where
1349    B: ByteSliceMut,
1350    // FIXME(#251): We can't remove `Immutable` here because it's required by
1351    // the impl of `Deref`, which is a super-trait of `DerefMut`. Maybe we can
1352    // add a separate inherent method for this?
1353    T: FromBytes + IntoBytes + KnownLayout + Immutable + ?Sized,
1354{
1355    /// Mutably dereferences the value.
1356    ///
1357    #[doc = codegen_section!(
1358        header = "h5",
1359        bench = "ref_type_deref_mut",
1360        format = "coco",
1361        arity = 2,
1362        [
1363            open
1364            @index 1
1365            @title "Sized"
1366            @variant "static_size"
1367        ],
1368        [
1369            @index 2
1370            @title "Unsized"
1371            @variant "dynamic_size"
1372        ]
1373    )]
1374    #[inline]
1375    fn deref_mut(&mut self) -> &mut T {
1376        // Presumably unreachable, since we've guarded each constructor of `Ref`.
1377        static_assert_dst_is_not_zst!(T);
1378
1379        let metadata = self.pointer_metadata();
1380
1381        // SAFETY: We don't call any methods on `b` other than those provided by
1382        // `ByteSliceMut`.
1383        let b = unsafe { self.as_byte_slice_mut() };
1384        let b = b.deref_mut();
1385
1386        if let crate::layout::SizeInfo::Sized { .. } = T::LAYOUT.size_info {
1387            let ptr = Ptr::from_mut(b);
1388            // SAFETY: We just checked that `T: Sized`. By invariant on `r`,
1389            // `b`'s size is equal to `size_of::<T>()`.
1390            let ptr = unsafe {
1391                cast_for_sized::<
1392                    T,
1393                    _,
1394                    (BecauseRead, BecauseExclusive),
1395                    (BecauseMutationCompatible, BecauseSharedCompatible),
1396                >(ptr)
1397            };
1398
1399            // SAFETY: None of the preceding transformations modifies the
1400            // address of the pointer, and by invariant on `r`, we know that it
1401            // is validly-aligned.
1402            let ptr = unsafe { ptr.assume_alignment::<Aligned>() };
1403            return ptr.as_mut();
1404        }
1405
1406        // PANICS: By postcondition on `as_byte_slice_mut`, `b` is aligned for
1407        // `T`, and its size is exactly the size encoded by `metadata`. By
1408        // invariant on `ByteSlice`, these are preserved through `.deref_mut()`,
1409        // so this `unwrap` will not panic.
1410        let ptr = Ptr::from_mut(b)
1411            .try_cast_into_no_leftover::<T, BecauseExclusive>(Some(metadata))
1412            .expect("zerocopy internal error: DerefMut::deref_mut should be infallible");
1413        let ptr = ptr.recall_validity::<_, (_, (_, BecauseExclusive))>();
1414        ptr.as_mut()
1415    }
1416}
1417
1418impl<T, B> Display for Ref<B, T>
1419where
1420    B: ByteSlice,
1421    T: FromBytes + Display + KnownLayout + Immutable + ?Sized,
1422{
1423    #[inline]
1424    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1425        let inner: &T = self;
1426        inner.fmt(fmt)
1427    }
1428}
1429
1430impl<T, B> Debug for Ref<B, T>
1431where
1432    B: ByteSlice,
1433    T: FromBytes + Debug + KnownLayout + Immutable + ?Sized,
1434{
1435    #[inline]
1436    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1437        let inner: &T = self;
1438        fmt.debug_tuple("Ref").field(&inner).finish()
1439    }
1440}
1441
1442impl<T, B> Eq for Ref<B, T>
1443where
1444    B: ByteSlice,
1445    T: FromBytes + Eq + KnownLayout + Immutable + ?Sized,
1446{
1447}
1448
1449impl<T, B> PartialEq for Ref<B, T>
1450where
1451    B: ByteSlice,
1452    T: FromBytes + PartialEq + KnownLayout + Immutable + ?Sized,
1453{
1454    #[inline]
1455    fn eq(&self, other: &Self) -> bool {
1456        self.deref().eq(other.deref())
1457    }
1458}
1459
1460impl<T, B> Ord for Ref<B, T>
1461where
1462    B: ByteSlice,
1463    T: FromBytes + Ord + KnownLayout + Immutable + ?Sized,
1464{
1465    #[inline]
1466    fn cmp(&self, other: &Self) -> Ordering {
1467        let inner: &T = self;
1468        let other_inner: &T = other;
1469        inner.cmp(other_inner)
1470    }
1471}
1472
1473impl<T, B> PartialOrd for Ref<B, T>
1474where
1475    B: ByteSlice,
1476    T: FromBytes + PartialOrd + KnownLayout + Immutable + ?Sized,
1477{
1478    #[inline]
1479    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1480        let inner: &T = self;
1481        let other_inner: &T = other;
1482        inner.partial_cmp(other_inner)
1483    }
1484}
1485
1486/// # Safety
1487///
1488/// `T: Sized` and `ptr`'s referent must have size `size_of::<T>()`.
1489#[inline(always)]
1490unsafe fn cast_for_sized<'a, T, A, R, S>(
1491    ptr: Ptr<'a, [u8], (A, Aligned, Safe)>,
1492) -> Ptr<'a, T, (A, Unaligned, Safe)>
1493where
1494    T: FromBytes + KnownLayout + ?Sized,
1495    A: crate::invariant::Aliasing,
1496    [u8]: MutationCompatible<T, A, Initialized, Initialized, R>,
1497    T: TransmuteFromPtr<T, A, Initialized, Safe, crate::pointer::cast::IdCast, S>,
1498{
1499    use crate::pointer::cast::{Cast, Project};
1500
1501    enum CastForSized {}
1502
1503    // SAFETY: `CastForSized` is only used below with the input `ptr`, which the
1504    // caller promises has size `size_of::<T>()`. Thus, the referent produced in
1505    // this cast has the same size as `ptr`'s referent. All operations preserve
1506    // provenance.
1507    unsafe impl<T: ?Sized + KnownLayout> Project<[u8], T> for CastForSized {
1508        #[inline(always)]
1509        fn project(src: PtrInner<'_, [u8]>) -> *mut T {
1510            T::raw_from_ptr_len(
1511                src.as_non_null().cast(),
1512                <T::PointerMetadata as crate::PointerMetadata>::from_elem_count(0),
1513            )
1514            .as_ptr()
1515        }
1516    }
1517
1518    // SAFETY: The `Project::project` impl preserves referent address.
1519    unsafe impl<T: ?Sized + KnownLayout> Cast<[u8], T> for CastForSized {}
1520
1521    ptr.recall_validity::<Initialized, (_, (_, _))>()
1522        .cast::<_, CastForSized, _>()
1523        .recall_validity::<Safe, _>()
1524}
1525
1526#[cfg(test)]
1527#[allow(clippy::assertions_on_result_states)]
1528mod tests {
1529    use core::convert::TryInto as _;
1530
1531    use super::*;
1532    use crate::util::testutil::*;
1533
1534    #[test]
1535    fn test_mut_slice_into_ref() {
1536        // Prior to #1260/#1299, calling `into_ref` on a `&mut [u8]`-backed
1537        // `Ref` was not supported.
1538        let mut buf = [0u8];
1539        let r = Ref::<&mut [u8], u8>::from_bytes(&mut buf).unwrap();
1540        assert_eq!(Ref::into_ref(r), &0);
1541    }
1542
1543    #[test]
1544    fn test_address() {
1545        // Test that the `Deref` and `DerefMut` implementations return a
1546        // reference which points to the right region of memory.
1547
1548        let buf = [0];
1549        let r = Ref::<_, u8>::from_bytes(&buf[..]).unwrap();
1550        let buf_ptr = buf.as_ptr();
1551        let deref_ptr: *const u8 = r.deref();
1552        assert_eq!(buf_ptr, deref_ptr);
1553
1554        let buf = [0];
1555        let r = Ref::<_, [u8]>::from_bytes(&buf[..]).unwrap();
1556        let buf_ptr = buf.as_ptr();
1557        let deref_ptr = r.deref().as_ptr();
1558        assert_eq!(buf_ptr, deref_ptr);
1559    }
1560
1561    #[test]
1562    #[allow(clippy::clone_on_copy)] // Exercise `Ref`'s manual `Clone` impl.
1563    fn test_with_elems_preserves_ambiguous_metadata() {
1564        #[derive(FromBytes, Immutable, KnownLayout)]
1565        #[repr(C, align(8))]
1566        struct Frame {
1567            header: [u8; 8],
1568            body: [u8],
1569        }
1570
1571        #[derive(FromBytes, Immutable, KnownLayout)]
1572        #[repr(C, align(8))]
1573        struct OddHeader {
1574            header: [u8; 7],
1575            body: [u8],
1576        }
1577
1578        // Dynamic trailing padding makes these pairs of distinct element
1579        // counts produce the same total byte size. Thus, the byte length alone
1580        // cannot recover the count supplied to a `*_with_elems` constructor.
1581        assert_eq!(Frame::size_for_metadata(1), Some(16));
1582        assert_eq!(Frame::size_for_metadata(8), Some(16));
1583        assert_eq!(OddHeader::size_for_metadata(0), Some(8));
1584        assert_eq!(OddHeader::size_for_metadata(1), Some(8));
1585
1586        let bytes = Align::<[u8; 32], AU64>::default();
1587
1588        let whole = Ref::<_, Frame>::from_bytes_with_elems(&bytes.t[..16], 1).unwrap();
1589        assert_eq!(whole.body.len(), 1);
1590        assert_eq!(Ref::bytes(&whole).len(), 16);
1591        assert_eq!(whole.clone().body.len(), 1);
1592        let copied = whole;
1593        assert_eq!(copied.body.len(), 1);
1594        assert_eq!(Ref::into_ref(whole).body.len(), 1);
1595
1596        let (prefix, rest) = Ref::<_, Frame>::from_prefix_with_elems(&bytes.t[..], 1).unwrap();
1597        assert_eq!(prefix.body.len(), 1);
1598        assert_eq!(rest.len(), 16);
1599
1600        let (before, suffix) = Ref::<_, Frame>::from_suffix_with_elems(&bytes.t[..24], 1).unwrap();
1601        assert_eq!(before.len(), 8);
1602        assert_eq!(suffix.body.len(), 1);
1603
1604        // Zero is real metadata, not a sentinel for "infer from the bytes".
1605        let empty = Ref::<_, OddHeader>::from_bytes_with_elems(&bytes.t[..8], 0).unwrap();
1606        assert!(empty.body.is_empty());
1607        assert!(Ref::into_ref(empty).body.is_empty());
1608
1609        // The implicit constructors still choose the largest fitting count,
1610        // and retain the metadata selected during their validating cast.
1611        let inferred = Ref::<_, Frame>::from_bytes(&bytes.t[..16]).unwrap();
1612        assert_eq!(inferred.body.len(), 8);
1613        let (inferred, rest) = Ref::<_, Frame>::from_prefix(&bytes.t[..16]).unwrap();
1614        assert_eq!(inferred.body.len(), 8);
1615        assert!(rest.is_empty());
1616        let (before, inferred) = Ref::<_, Frame>::from_suffix(&bytes.t[..16]).unwrap();
1617        assert!(before.is_empty());
1618        assert_eq!(inferred.body.len(), 8);
1619    }
1620
1621    // Verify that values written to a `Ref` are properly shared between the
1622    // typed and untyped representations, that reads via `deref` and `read`
1623    // behave the same, and that writes via `deref_mut` and `write` behave the
1624    // same.
1625    fn test_new_helper(mut r: Ref<&mut [u8], AU64>) {
1626        // assert that the value starts at 0
1627        assert_eq!(*r, AU64(0));
1628        assert_eq!(Ref::read(&r), AU64(0));
1629
1630        // Assert that values written to the typed value are reflected in the
1631        // byte slice.
1632        const VAL1: AU64 = AU64(0xFF00FF00FF00FF00);
1633        *r = VAL1;
1634        assert_eq!(Ref::bytes(&r), &VAL1.to_bytes());
1635        *r = AU64(0);
1636        Ref::write(&mut r, VAL1);
1637        assert_eq!(Ref::bytes(&r), &VAL1.to_bytes());
1638
1639        // Assert that values written to the byte slice are reflected in the
1640        // typed value.
1641        const VAL2: AU64 = AU64(!VAL1.0); // different from `VAL1`
1642        Ref::bytes_mut(&mut r).copy_from_slice(&VAL2.to_bytes()[..]);
1643        assert_eq!(*r, VAL2);
1644        assert_eq!(Ref::read(&r), VAL2);
1645    }
1646
1647    // Verify that values written to a `Ref` are properly shared between the
1648    // typed and untyped representations; pass a value with `typed_len` `AU64`s
1649    // backed by an array of `typed_len * 8` bytes.
1650    fn test_new_helper_slice(mut r: Ref<&mut [u8], [AU64]>, typed_len: usize) {
1651        // Assert that the value starts out zeroed.
1652        assert_eq!(&*r, vec![AU64(0); typed_len].as_slice());
1653
1654        // Check the backing storage is the exact same slice.
1655        let untyped_len = typed_len * 8;
1656        assert_eq!(Ref::bytes(&r).len(), untyped_len);
1657        assert_eq!(Ref::bytes(&r).as_ptr(), r.as_ptr().cast::<u8>());
1658
1659        // Assert that values written to the typed value are reflected in the
1660        // byte slice.
1661        const VAL1: AU64 = AU64(0xFF00FF00FF00FF00);
1662        for typed in &mut *r {
1663            *typed = VAL1;
1664        }
1665        assert_eq!(Ref::bytes(&r), VAL1.0.to_ne_bytes().repeat(typed_len).as_slice());
1666
1667        // Assert that values written to the byte slice are reflected in the
1668        // typed value.
1669        const VAL2: AU64 = AU64(!VAL1.0); // different from VAL1
1670        Ref::bytes_mut(&mut r).copy_from_slice(&VAL2.0.to_ne_bytes().repeat(typed_len));
1671        assert!(r.iter().copied().all(|x| x == VAL2));
1672    }
1673
1674    #[test]
1675    fn test_new_aligned_sized() {
1676        // Test that a properly-aligned, properly-sized buffer works for new,
1677        // new_from_prefix, and new_from_suffix, and that new_from_prefix and
1678        // new_from_suffix return empty slices. Test that a properly-aligned
1679        // buffer whose length is a multiple of the element size works for
1680        // new_slice.
1681
1682        // A buffer with an alignment of 8.
1683        let mut buf = Align::<[u8; 8], AU64>::default();
1684        // `buf.t` should be aligned to 8, so this should always succeed.
1685        test_new_helper(Ref::<_, AU64>::from_bytes(&mut buf.t[..]).unwrap());
1686        {
1687            // In a block so that `r` and `suffix` don't live too long.
1688            buf.set_default();
1689            let (r, suffix) = Ref::<_, AU64>::from_prefix(&mut buf.t[..]).unwrap();
1690            assert!(suffix.is_empty());
1691            test_new_helper(r);
1692        }
1693        {
1694            buf.set_default();
1695            let (prefix, r) = Ref::<_, AU64>::from_suffix(&mut buf.t[..]).unwrap();
1696            assert!(prefix.is_empty());
1697            test_new_helper(r);
1698        }
1699
1700        // A buffer with alignment 8 and length 24. We choose this length very
1701        // intentionally: if we instead used length 16, then the prefix and
1702        // suffix lengths would be identical. In the past, we used length 16,
1703        // which resulted in this test failing to discover the bug uncovered in
1704        // #506.
1705        let mut buf = Align::<[u8; 24], AU64>::default();
1706        // `buf.t` should be aligned to 8 and have a length which is a multiple
1707        // of `size_of::<AU64>()`, so this should always succeed.
1708        test_new_helper_slice(Ref::<_, [AU64]>::from_bytes(&mut buf.t[..]).unwrap(), 3);
1709        buf.set_default();
1710        let r = Ref::<_, [AU64]>::from_bytes_with_elems(&mut buf.t[..], 3).unwrap();
1711        test_new_helper_slice(r, 3);
1712
1713        let ascending: [u8; 24] = (0..24).collect::<Vec<_>>().try_into().unwrap();
1714        // 16 ascending bytes followed by 8 zeros.
1715        let mut ascending_prefix = ascending;
1716        ascending_prefix[16..].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
1717        // 8 zeros followed by 16 ascending bytes.
1718        let mut ascending_suffix = ascending;
1719        ascending_suffix[..8].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
1720        {
1721            buf.t = ascending_suffix;
1722            let (r, suffix) = Ref::<_, [AU64]>::from_prefix_with_elems(&mut buf.t[..], 1).unwrap();
1723            assert_eq!(suffix, &ascending[8..]);
1724            test_new_helper_slice(r, 1);
1725        }
1726        {
1727            buf.t = ascending_prefix;
1728            let (prefix, r) = Ref::<_, [AU64]>::from_suffix_with_elems(&mut buf.t[..], 1).unwrap();
1729            assert_eq!(prefix, &ascending[..16]);
1730            test_new_helper_slice(r, 1);
1731        }
1732    }
1733
1734    #[test]
1735    fn test_new_oversized() {
1736        // Test that a properly-aligned, overly-sized buffer works for
1737        // `new_from_prefix` and `new_from_suffix`, and that they return the
1738        // remainder and prefix of the slice respectively.
1739
1740        let mut buf = Align::<[u8; 16], AU64>::default();
1741        {
1742            // In a block so that `r` and `suffix` don't live too long. `buf.t`
1743            // should be aligned to 8, so this should always succeed.
1744            let (r, suffix) = Ref::<_, AU64>::from_prefix(&mut buf.t[..]).unwrap();
1745            assert_eq!(suffix.len(), 8);
1746            test_new_helper(r);
1747        }
1748        {
1749            buf.set_default();
1750            // `buf.t` should be aligned to 8, so this should always succeed.
1751            let (prefix, r) = Ref::<_, AU64>::from_suffix(&mut buf.t[..]).unwrap();
1752            assert_eq!(prefix.len(), 8);
1753            test_new_helper(r);
1754        }
1755    }
1756
1757    #[test]
1758    #[allow(clippy::cognitive_complexity)]
1759    fn test_new_error() {
1760        // Fail because the buffer is too large.
1761
1762        // A buffer with an alignment of 8.
1763        let buf = Align::<[u8; 16], AU64>::default();
1764        // `buf.t` should be aligned to 8, so only the length check should fail.
1765        assert!(Ref::<_, AU64>::from_bytes(&buf.t[..]).is_err());
1766
1767        // Fail because the buffer is too small.
1768
1769        // A buffer with an alignment of 8.
1770        let buf = Align::<[u8; 4], AU64>::default();
1771        // `buf.t` should be aligned to 8, so only the length check should fail.
1772        assert!(Ref::<_, AU64>::from_bytes(&buf.t[..]).is_err());
1773        assert!(Ref::<_, AU64>::from_prefix(&buf.t[..]).is_err());
1774        assert!(Ref::<_, AU64>::from_suffix(&buf.t[..]).is_err());
1775
1776        // Fail because the length is not a multiple of the element size.
1777
1778        let buf = Align::<[u8; 12], AU64>::default();
1779        // `buf.t` has length 12, but element size is 8.
1780        assert!(Ref::<_, [AU64]>::from_bytes(&buf.t[..]).is_err());
1781
1782        // Fail because the buffer is too short.
1783        let buf = Align::<[u8; 12], AU64>::default();
1784        // `buf.t` has length 12, but the element size is 8 (and we're expecting
1785        // two of them). For each function, we test with a length that would
1786        // cause the size to overflow `usize`, and with a normal length that
1787        // will fail thanks to the buffer being too short; these are different
1788        // error paths, and while the error types are the same, the distinction
1789        // shows up in code coverage metrics.
1790        let n = (usize::MAX / mem::size_of::<AU64>()) + 1;
1791        assert!(Ref::<_, [AU64]>::from_bytes_with_elems(&buf.t[..], n).is_err());
1792        assert!(Ref::<_, [AU64]>::from_bytes_with_elems(&buf.t[..], 2).is_err());
1793        assert!(Ref::<_, [AU64]>::from_prefix_with_elems(&buf.t[..], n).is_err());
1794        assert!(Ref::<_, [AU64]>::from_prefix_with_elems(&buf.t[..], 2).is_err());
1795        assert!(Ref::<_, [AU64]>::from_suffix_with_elems(&buf.t[..], n).is_err());
1796        assert!(Ref::<_, [AU64]>::from_suffix_with_elems(&buf.t[..], 2).is_err());
1797
1798        // Fail because the alignment is insufficient.
1799
1800        // A buffer with an alignment of 8. An odd buffer size is chosen so that
1801        // the last byte of the buffer has odd alignment.
1802        let buf = Align::<[u8; 13], AU64>::default();
1803        // Slicing from 1, we get a buffer with size 12 (so the length check
1804        // should succeed) but an alignment of only 1, which is insufficient.
1805        assert!(Ref::<_, AU64>::from_bytes(&buf.t[1..]).is_err());
1806        assert!(Ref::<_, AU64>::from_prefix(&buf.t[1..]).is_err());
1807        assert!(Ref::<_, [AU64]>::from_bytes(&buf.t[1..]).is_err());
1808        assert!(Ref::<_, [AU64]>::from_bytes_with_elems(&buf.t[1..], 1).is_err());
1809        assert!(Ref::<_, [AU64]>::from_prefix_with_elems(&buf.t[1..], 1).is_err());
1810        assert!(Ref::<_, [AU64]>::from_suffix_with_elems(&buf.t[1..], 1).is_err());
1811        // Slicing is unnecessary here because `new_from_suffix` uses the suffix
1812        // of the slice, which has odd alignment.
1813        assert!(Ref::<_, AU64>::from_suffix(&buf.t[..]).is_err());
1814
1815        // Fail due to arithmetic overflow.
1816
1817        let buf = Align::<[u8; 16], AU64>::default();
1818        let unreasonable_len = usize::MAX / mem::size_of::<AU64>() + 1;
1819        assert!(Ref::<_, [AU64]>::from_prefix_with_elems(&buf.t[..], unreasonable_len).is_err());
1820        assert!(Ref::<_, [AU64]>::from_suffix_with_elems(&buf.t[..], unreasonable_len).is_err());
1821    }
1822
1823    #[test]
1824    fn test_with_elems_alignment_error_returns_whole_source() {
1825        // An alignment error from `from_prefix_with_elems` or
1826        // `from_suffix_with_elems` must carry all of `source`, not only the
1827        // prefix or suffix that was going to be cast.
1828
1829        // A buffer with an alignment of 8 and an odd size.
1830        let mut buf = Align::<[u8; 13], AU64>::default();
1831
1832        // `buf.t[1..]` has 12 bytes, enough for one `AU64`, but its start (and
1833        // thus its 8-byte prefix) is misaligned.
1834        let src = &buf.t[1..];
1835        let err = Ref::<_, [AU64]>::from_prefix_with_elems(src, 1).unwrap_err();
1836        assert!(matches!(err, ConvertError::Alignment(_)));
1837        let err_src = err.into_src();
1838        assert_eq!((err_src.as_ptr(), err_src.len()), (src.as_ptr(), src.len()));
1839
1840        let src = &mut buf.t[1..];
1841        let (addr, len) = (src.as_ptr(), src.len());
1842        let err = Ref::<_, [AU64]>::from_prefix_with_elems(src, 1).unwrap_err();
1843        assert!(matches!(err, ConvertError::Alignment(_)));
1844        let err_src = err.into_src();
1845        assert_eq!((err_src.as_ptr(), err_src.len()), (addr, len));
1846
1847        // `buf.t[..]` is aligned, but its 8-byte suffix starts at offset 5 and
1848        // is misaligned.
1849        let src = &buf.t[..];
1850        let err = Ref::<_, [AU64]>::from_suffix_with_elems(src, 1).unwrap_err();
1851        assert!(matches!(err, ConvertError::Alignment(_)));
1852        let err_src = err.into_src();
1853        assert_eq!((err_src.as_ptr(), err_src.len()), (src.as_ptr(), src.len()));
1854
1855        let src = &mut buf.t[..];
1856        let (addr, len) = (src.as_ptr(), src.len());
1857        let err = Ref::<_, [AU64]>::from_suffix_with_elems(src, 1).unwrap_err();
1858        assert!(matches!(err, ConvertError::Alignment(_)));
1859        let err_src = err.into_src();
1860        assert_eq!((err_src.as_ptr(), err_src.len()), (addr, len));
1861
1862        // Even a zero-element suffix at odd end-offset 13 is misaligned for
1863        // `[AU64]` and must return the whole `source`, whereas an aligned end
1864        // offset succeeds.
1865        let src = &mut buf.t[..];
1866        let (addr, len) = (src.as_ptr(), src.len());
1867        let err = Ref::<_, [AU64]>::from_suffix_with_elems(src, 0).unwrap_err();
1868        assert!(matches!(err, ConvertError::Alignment(_)));
1869        let err_src = err.into_src();
1870        assert_eq!((err_src.as_ptr(), err_src.len()), (addr, len));
1871
1872        let (prefix, r) = Ref::<_, [AU64]>::from_suffix_with_elems(&buf.t[..8], 0).unwrap();
1873        assert_eq!(prefix.len(), 8);
1874        assert_eq!(r.len(), 0);
1875    }
1876
1877    #[test]
1878    #[allow(unstable_name_collisions)]
1879    #[allow(clippy::as_conversions)]
1880    fn test_into_ref_mut() {
1881        #[allow(unused)]
1882        use crate::util::AsAddress as _;
1883
1884        let mut buf = Align::<[u8; 8], u64>::default();
1885        let r = Ref::<_, u64>::from_bytes(&buf.t[..]).unwrap();
1886        let rf = Ref::into_ref(r);
1887        assert_eq!(rf, &0u64);
1888        let buf_addr = (&buf.t as *const [u8; 8]).addr();
1889        assert_eq!((rf as *const u64).addr(), buf_addr);
1890
1891        let r = Ref::<_, u64>::from_bytes(&mut buf.t[..]).unwrap();
1892        let rf = Ref::into_mut(r);
1893        assert_eq!(rf, &mut 0u64);
1894        assert_eq!((rf as *mut u64).addr(), buf_addr);
1895
1896        *rf = u64::MAX;
1897        assert_eq!(buf.t, [0xFF; 8]);
1898
1899        // Exercise the unsized `into_mut` route, which must use the metadata
1900        // retained by the constructor rather than infer fresh metadata.
1901        let mut buf = Align::<[u8; 8], u16>::default();
1902        let r = Ref::<_, [u16]>::from_bytes_with_elems(&mut buf.t[..], 4).unwrap();
1903        let rf = Ref::into_mut(r);
1904        assert_eq!(rf.len(), 4);
1905    }
1906
1907    #[test]
1908    fn test_display_debug() {
1909        let buf = Align::<[u8; 8], u64>::default();
1910        let r = Ref::<_, u64>::from_bytes(&buf.t[..]).unwrap();
1911        assert_eq!(format!("{}", r), "0");
1912        assert_eq!(format!("{:?}", r), "Ref(0)");
1913
1914        let buf = Align::<[u8; 8], u64>::default();
1915        let r = Ref::<_, [u64]>::from_bytes(&buf.t[..]).unwrap();
1916        assert_eq!(format!("{:?}", r), "Ref([0])");
1917    }
1918
1919    #[test]
1920    fn test_eq() {
1921        let buf1 = 0_u64;
1922        let r1 = Ref::<_, u64>::from_bytes(buf1.as_bytes()).unwrap();
1923        let buf2 = 0_u64;
1924        let r2 = Ref::<_, u64>::from_bytes(buf2.as_bytes()).unwrap();
1925        assert_eq!(r1, r2);
1926    }
1927
1928    #[test]
1929    fn test_ne() {
1930        let buf1 = 0_u64;
1931        let r1 = Ref::<_, u64>::from_bytes(buf1.as_bytes()).unwrap();
1932        let buf2 = 1_u64;
1933        let r2 = Ref::<_, u64>::from_bytes(buf2.as_bytes()).unwrap();
1934        assert_ne!(r1, r2);
1935    }
1936
1937    #[test]
1938    fn test_ord() {
1939        let buf1 = 0_u64;
1940        let r1 = Ref::<_, u64>::from_bytes(buf1.as_bytes()).unwrap();
1941        let buf2 = 1_u64;
1942        let r2 = Ref::<_, u64>::from_bytes(buf2.as_bytes()).unwrap();
1943        assert!(r1 < r2);
1944        assert_eq!(PartialOrd::partial_cmp(&r1, &r2), Some(Ordering::Less));
1945        assert_eq!(Ord::cmp(&r1, &r2), Ordering::Less);
1946    }
1947}
1948
1949#[cfg(all(test, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS))]
1950mod benches {
1951    use test::{self, Bencher};
1952
1953    use super::*;
1954    use crate::util::testutil::*;
1955
1956    #[bench]
1957    fn bench_from_bytes_sized(b: &mut Bencher) {
1958        let buf = Align::<[u8; 8], AU64>::default();
1959        // `buf.t` should be aligned to 8, so this should always succeed.
1960        let bytes = &buf.t[..];
1961        b.iter(|| test::black_box(Ref::<_, AU64>::from_bytes(test::black_box(bytes)).unwrap()));
1962    }
1963
1964    #[bench]
1965    fn bench_into_ref_sized(b: &mut Bencher) {
1966        let buf = Align::<[u8; 8], AU64>::default();
1967        let bytes = &buf.t[..];
1968        let r = Ref::<_, AU64>::from_bytes(bytes).unwrap();
1969        b.iter(|| test::black_box(Ref::into_ref(test::black_box(r))));
1970    }
1971
1972    #[bench]
1973    fn bench_into_mut_sized(b: &mut Bencher) {
1974        let mut buf = Align::<[u8; 8], AU64>::default();
1975        let buf = &mut buf.t[..];
1976        let _ = Ref::<_, AU64>::from_bytes(&mut *buf).unwrap();
1977        b.iter(move || {
1978            // SAFETY: The preceding `from_bytes` succeeded, and so we know that
1979            // `buf` is validly aligned and has the `size_of::<AU64>()` byte
1980            // length required by `new_sized_unchecked` [1].
1981            //
1982            // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of.html:
1983            //
1984            //     Returns the size of a type in bytes.
1985            let r = unsafe { Ref::<&mut [u8], AU64>::new_sized_unchecked(&mut *buf) };
1986            test::black_box(Ref::into_mut(test::black_box(r)));
1987        });
1988    }
1989
1990    #[bench]
1991    fn bench_deref_sized(b: &mut Bencher) {
1992        let buf = Align::<[u8; 8], AU64>::default();
1993        let bytes = &buf.t[..];
1994        let r = Ref::<_, AU64>::from_bytes(bytes).unwrap();
1995        b.iter(|| {
1996            let temp = test::black_box(r);
1997            test::black_box(temp.deref());
1998        });
1999    }
2000
2001    #[bench]
2002    fn bench_deref_mut_sized(b: &mut Bencher) {
2003        let mut buf = Align::<[u8; 8], AU64>::default();
2004        let buf = &mut buf.t[..];
2005        let _ = Ref::<_, AU64>::from_bytes(&mut *buf).unwrap();
2006        b.iter(|| {
2007            // SAFETY: The preceding `from_bytes` succeeded, and so we know that
2008            // `buf` is validly aligned and has the `size_of::<AU64>()` byte
2009            // length required by `new_sized_unchecked` [1].
2010            //
2011            // [1] Per https://doc.rust-lang.org/1.56.0/core/mem/fn.size_of.html:
2012            //
2013            //     Returns the size of a type in bytes.
2014            let r = unsafe { Ref::<&mut [u8], AU64>::new_sized_unchecked(&mut *buf) };
2015            let mut temp = test::black_box(r);
2016            test::black_box(temp.deref_mut());
2017        });
2018    }
2019}