Skip to main content

zerocopy/util/
mod.rs

1// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0 OR MIT
2//
3// Copyright 2023 The Fuchsia Authors
4//
5// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
6// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
7// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
8// This file may not be copied, modified, or distributed except according to
9// those terms.
10
11#[macro_use]
12pub(crate) mod macros;
13
14#[doc(hidden)]
15pub mod macro_util;
16
17use core::{
18    marker::PhantomData,
19    mem::{self, ManuallyDrop},
20    num::NonZeroUsize,
21    ptr::NonNull,
22};
23
24use super::*;
25use crate::pointer::{
26    invariant::{Exclusive, Safe, Shared},
27    SizeEq, TransmuteFromPtr,
28};
29
30/// Like [`PhantomData`], but [`Send`] and [`Sync`] regardless of whether the
31/// wrapped `T` is.
32pub(crate) struct SendSyncPhantomData<T: ?Sized>(PhantomData<T>);
33
34// SAFETY: `SendSyncPhantomData` does not enable any behavior which isn't sound
35// to be called from multiple threads.
36unsafe impl<T: ?Sized> Send for SendSyncPhantomData<T> {}
37// SAFETY: `SendSyncPhantomData` does not enable any behavior which isn't sound
38// to be called from multiple threads.
39unsafe impl<T: ?Sized> Sync for SendSyncPhantomData<T> {}
40
41impl<T: ?Sized> Default for SendSyncPhantomData<T> {
42    fn default() -> SendSyncPhantomData<T> {
43        SendSyncPhantomData(PhantomData)
44    }
45}
46
47impl<T: ?Sized> PartialEq for SendSyncPhantomData<T> {
48    fn eq(&self, _other: &Self) -> bool {
49        true
50    }
51}
52
53impl<T: ?Sized> Eq for SendSyncPhantomData<T> {}
54
55impl<T: ?Sized> Clone for SendSyncPhantomData<T> {
56    fn clone(&self) -> Self {
57        SendSyncPhantomData(PhantomData)
58    }
59}
60
61#[cfg(miri)]
62extern "Rust" {
63    /// Miri-provided intrinsic that marks the pointer `ptr` as aligned to
64    /// `align`.
65    ///
66    /// This intrinsic is used to inform Miri's symbolic alignment checker that
67    /// a pointer is aligned, even if Miri cannot statically deduce that fact.
68    /// This is often required when performing raw pointer arithmetic or casts
69    /// where the alignment is guaranteed by runtime checks or invariants that
70    /// Miri is not aware of.
71    pub(crate) fn miri_promise_symbolic_alignment(ptr: *const (), align: usize);
72}
73
74pub(crate) trait AsAddress {
75    fn addr(self) -> usize;
76}
77
78impl<T: ?Sized> AsAddress for &T {
79    #[inline(always)]
80    fn addr(self) -> usize {
81        let ptr: *const T = self;
82        AsAddress::addr(ptr)
83    }
84}
85
86impl<T: ?Sized> AsAddress for &mut T {
87    #[inline(always)]
88    fn addr(self) -> usize {
89        let ptr: *const T = self;
90        AsAddress::addr(ptr)
91    }
92}
93
94impl<T: ?Sized> AsAddress for NonNull<T> {
95    #[inline(always)]
96    fn addr(self) -> usize {
97        AsAddress::addr(self.as_ptr())
98    }
99}
100
101impl<T: ?Sized> AsAddress for *const T {
102    #[inline(always)]
103    fn addr(self) -> usize {
104        // FIXME(#181), FIXME(https://github.com/rust-lang/rust/issues/95228):
105        // Use `.addr()` instead of `as usize` once it's stable, and get rid of
106        // this `allow`. Currently, `as usize` is the only way to accomplish
107        // this.
108        #[allow(clippy::as_conversions)]
109        #[cfg_attr(
110            __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS,
111            allow(implicit_provenance_casts)
112        )]
113        return self.cast::<()>() as usize;
114    }
115}
116
117impl<T: ?Sized> AsAddress for *mut T {
118    #[inline(always)]
119    fn addr(self) -> usize {
120        let ptr: *const T = self;
121        AsAddress::addr(ptr)
122    }
123}
124
125/// Validates that `t` is aligned to `align_of::<U>()`.
126#[inline(always)]
127pub(crate) fn validate_aligned_to<T: AsAddress, U>(t: T) -> Result<(), AlignmentError<(), U>> {
128    // `mem::align_of::<U>()` is guaranteed to return a non-zero value, which in
129    // turn guarantees that this mod operation will not panic.
130    #[allow(clippy::arithmetic_side_effects)]
131    let remainder = t.addr() % mem::align_of::<U>();
132    if remainder == 0 {
133        Ok(())
134    } else {
135        // SAFETY: We just confirmed that `t.addr() % align_of::<U>() != 0`.
136        // That's only possible if `align_of::<U>() > 1`.
137        Err(unsafe { AlignmentError::new_unchecked(()) })
138    }
139}
140
141/// Returns the bytes needed to pad `len` to the next multiple of `align`.
142///
143/// This function assumes that align is a power of two; there are no guarantees
144/// on the answer it gives if this is not the case.
145#[cfg_attr(
146    kani,
147    kani::requires(align.is_power_of_two()),
148    // A power-of-two alignment divides the `usize` modulus, so wrapping
149    // preserves congruence even when the next aligned value exceeds `usize`.
150    kani::ensures(|&p| len.wrapping_add(p) % align.get() == 0),
151    // Ensures that we add the minimum required padding.
152    kani::ensures(|&p| p < align.get()),
153)]
154#[cfg_attr(not(zerocopy_inline_always), inline)]
155#[cfg_attr(zerocopy_inline_always, inline(always))]
156pub(crate) const fn padding_needed_for(len: usize, align: NonZeroUsize) -> usize {
157    #[cfg(kani)]
158    #[kani::proof_for_contract(padding_needed_for)]
159    fn proof() {
160        padding_needed_for(kani::any(), kani::any());
161    }
162
163    // Abstractly, we want to compute:
164    //   align - (len % align).
165    // Handling the case where len%align is 0.
166    // Because align is a power of two, len % align = len & (align-1).
167    // Guaranteed not to underflow as align is nonzero.
168    #[allow(clippy::arithmetic_side_effects)]
169    let mask = align.get() - 1;
170
171    // To efficiently subtract this value from align, we can use the bitwise
172    // complement.
173    // Note that ((!len) & (align-1)) gives us a number that with (len &
174    // (align-1)) sums to align-1. So subtracting 1 from x before taking the
175    // complement subtracts `len` from `align`. Some quick inspection of
176    // cases shows that this also handles the case where `len % align = 0`
177    // correctly too: len-1 % align then equals align-1, so the complement mod
178    // align will be 0, as desired.
179    //
180    // The following reasoning can be verified quickly by an SMT solver
181    // supporting the theory of bitvectors:
182    // ```smtlib
183    // ; Naive implementation of padding
184    // (define-fun padding1 (
185    //     (len (_ BitVec 32))
186    //     (align (_ BitVec 32))) (_ BitVec 32)
187    //    (ite
188    //      (= (_ bv0 32) (bvand len (bvsub align (_ bv1 32))))
189    //      (_ bv0 32)
190    //      (bvsub align (bvand len (bvsub align (_ bv1 32))))))
191    //
192    // ; The implementation below
193    // (define-fun padding2 (
194    //     (len (_ BitVec 32))
195    //     (align (_ BitVec 32))) (_ BitVec 32)
196    // (bvand (bvnot (bvsub len (_ bv1 32))) (bvsub align (_ bv1 32))))
197    //
198    // (define-fun is-power-of-two ((x (_ BitVec 32))) Bool
199    //   (= (_ bv0 32) (bvand x (bvsub x (_ bv1 32)))))
200    //
201    // (declare-const len (_ BitVec 32))
202    // (declare-const align (_ BitVec 32))
203    // ; Search for a case where align is a power of two and padding2 disagrees
204    // ; with padding1
205    // (assert (and (is-power-of-two align)
206    //              (not (= (padding1 len align) (padding2 len align)))))
207    // (simplify (padding1 (_ bv300 32) (_ bv32 32))) ; 20
208    // (simplify (padding2 (_ bv300 32) (_ bv32 32))) ; 20
209    // (simplify (padding1 (_ bv322 32) (_ bv32 32))) ; 30
210    // (simplify (padding2 (_ bv322 32) (_ bv32 32))) ; 30
211    // (simplify (padding1 (_ bv8 32) (_ bv8 32)))    ; 0
212    // (simplify (padding2 (_ bv8 32) (_ bv8 32)))    ; 0
213    // (check-sat) ; unsat, also works for 64-bit bitvectors
214    // ```
215    !(len.wrapping_sub(1)) & mask
216}
217
218/// Rounds `n` down to the largest value `m` such that `m <= n` and `m % align
219/// == 0`.
220///
221/// # Panics
222///
223/// May panic if `align` is not a power of two. Even if it doesn't panic in this
224/// case, it will produce nonsense results.
225#[inline(always)]
226#[cfg_attr(
227    kani,
228    kani::requires(align.is_power_of_two()),
229    kani::ensures(|&m| m <= n && m % align.get() == 0),
230    // Guarantees that `m` is the *largest* value such that `m % align == 0`.
231    kani::ensures(|&m| {
232        // If this `checked_add` fails, then the next multiple would wrap
233        // around, which trivially satisfies the "largest value" requirement.
234        m.checked_add(align.get()).map(|next_mul| next_mul > n).unwrap_or(true)
235    })
236)]
237pub(crate) const fn round_down_to_next_multiple_of_alignment(
238    n: usize,
239    align: NonZeroUsize,
240) -> usize {
241    #[cfg(kani)]
242    #[kani::proof_for_contract(round_down_to_next_multiple_of_alignment)]
243    fn proof() {
244        round_down_to_next_multiple_of_alignment(kani::any(), kani::any());
245    }
246
247    let align = align.get();
248    #[cfg(not(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0))]
249    debug_assert!(align.is_power_of_two());
250
251    // Subtraction can't underflow because `align.get() >= 1`.
252    #[allow(clippy::arithmetic_side_effects)]
253    let mask = !(align - 1);
254    n & mask
255}
256
257#[cfg_attr(not(zerocopy_inline_always), inline)]
258#[cfg_attr(zerocopy_inline_always, inline(always))]
259pub(crate) const fn max(a: NonZeroUsize, b: NonZeroUsize) -> NonZeroUsize {
260    if a.get() < b.get() {
261        b
262    } else {
263        a
264    }
265}
266
267#[cfg_attr(not(zerocopy_inline_always), inline)]
268#[cfg_attr(zerocopy_inline_always, inline(always))]
269pub(crate) const fn min(a: NonZeroUsize, b: NonZeroUsize) -> NonZeroUsize {
270    if a.get() > b.get() {
271        b
272    } else {
273        a
274    }
275}
276
277/// Copies `src` into the prefix of `dst`.
278///
279/// # Safety
280///
281/// The caller guarantees that `src.len() <= dst.len()`.
282#[inline(always)]
283pub(crate) unsafe fn copy_unchecked(src: &[u8], dst: &mut [u8]) {
284    debug_assert!(src.len() <= dst.len());
285    // SAFETY: This invocation satisfies the safety contract of
286    // copy_nonoverlapping [1]:
287    // - `src.as_ptr()` is trivially valid for reads of `src.len()` bytes
288    // - `dst.as_ptr()` is valid for writes of `src.len()` bytes, because the
289    //   caller has promised that `src.len() <= dst.len()`
290    // - `src` and `dst` are, trivially, properly aligned
291    // - the region of memory beginning at `src` with a size of `src.len()`
292    //   bytes does not overlap with the region of memory beginning at `dst`
293    //   with the same size, because `dst` is derived from an exclusive
294    //   reference.
295    unsafe {
296        core::ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len());
297    };
298}
299
300/// Unsafely transmutes the given `src` into a type `Dst`.
301///
302/// # Safety
303///
304/// The value `src` must be a valid instance of `Dst`.
305#[inline(always)]
306pub(crate) const unsafe fn transmute_unchecked<Src, Dst>(src: Src) -> Dst {
307    static_assert!(Src, Dst => core::mem::size_of::<Src>() == core::mem::size_of::<Dst>());
308
309    #[repr(C)]
310    union Transmute<Src, Dst> {
311        src: ManuallyDrop<Src>,
312        dst: ManuallyDrop<Dst>,
313    }
314
315    // SAFETY: Since `Transmute<Src, Dst>` is `#[repr(C)]`, its `src` and `dst`
316    // fields both start at the same offset and the types of those fields are
317    // transparent wrappers around `Src` and `Dst` [1]. Consequently,
318    // initializing `Transmute` with with `src` and then reading out `dst` is
319    // equivalent to transmuting from `Src` to `Dst` [2]. Transmuting from `src`
320    // to `Dst` is valid because — by contract on the caller — `src` is a valid
321    // instance of `Dst`.
322    //
323    // [1] Per https://doc.rust-lang.org/1.82.0/std/mem/struct.ManuallyDrop.html:
324    //
325    //     `ManuallyDrop<T>` is guaranteed to have the same layout and bit
326    //     validity as `T`, and is subject to the same layout optimizations as
327    //     `T`.
328    //
329    // [2] Per https://doc.rust-lang.org/1.82.0/reference/items/unions.html#reading-and-writing-union-fields:
330    //
331    //     Effectively, writing to and then reading from a union with the C
332    //     representation is analogous to a transmute from the type used for
333    //     writing to the type used for reading.
334    unsafe { ManuallyDrop::into_inner(Transmute { src: ManuallyDrop::new(src) }.dst) }
335}
336
337/// # Safety
338///
339/// `Src` must have a greater or equal alignment to `Dst`.
340pub(crate) unsafe fn transmute_ref<Src, Dst, R>(src: &Src) -> &Dst
341where
342    Src: ?Sized,
343    Dst: SizeEq<Src>
344        + TransmuteFromPtr<Src, Shared, Safe, Safe, <Dst as SizeEq<Src>>::CastFrom, R>
345        + ?Sized,
346{
347    let dst = Ptr::from_ref(src).transmute();
348    // SAFETY: The caller promises that `Src`'s alignment is at least as large
349    // as `Dst`'s alignment.
350    let dst = unsafe { dst.assume_alignment() };
351    dst.as_ref()
352}
353
354/// # Safety
355///
356/// `Src` must have a greater or equal alignment to `Dst`.
357pub(crate) unsafe fn transmute_mut<Src, Dst, R>(src: &mut Src) -> &mut Dst
358where
359    Src: ?Sized,
360    Dst: SizeEq<Src>
361        + TransmuteFromPtr<Src, Exclusive, Safe, Safe, <Dst as SizeEq<Src>>::CastFrom, R>
362        + ?Sized,
363{
364    let dst = Ptr::from_mut(src).transmute();
365    // SAFETY: The caller promises that `Src`'s alignment is at least as large
366    // as `Dst`'s alignment.
367    let dst = unsafe { dst.assume_alignment() };
368    dst.as_mut()
369}
370
371/// An allocator that can allocate zeroed memory and construct a boxed `T` from
372/// a raw pointer.
373///
374/// # Safety
375///
376/// Implementations must ensure that whenever `self.allocate_zeroed(layout)`
377/// returns a non-null pointer `ptr`, `ptr` points to a fresh, wholly disjoint
378/// block of memory currently allocated by `self` meeting the size and alignment
379/// of `layout`, with all `layout.size()` bytes initialized to zero.
380#[cfg(any(feature = "alloc", test))]
381pub(crate) unsafe trait BoxAllocator<T: ?Sized>: Sized {
382    type Boxed;
383
384    /// Allocates zero-initialized memory fitting `layout`, returning a null
385    /// pointer on allocation failure.
386    ///
387    /// # Safety
388    ///
389    /// `layout` must have non-zero size (`layout.size() != 0`).
390    unsafe fn allocate_zeroed(&self, layout: core::alloc::Layout) -> *mut u8;
391
392    /// Constructs a `Self::Boxed` from `raw` and `alloc`.
393    ///
394    /// # Safety
395    ///
396    /// The caller must ensure that:
397    /// - `raw` points to a valid instance of `T`.
398    /// - If the size of `*raw` is `0`, `raw` is non-null and aligned to the
399    ///   alignment of `T`.
400    /// - If the size of `*raw` is non-zero, `raw` points to a fresh, wholly
401    ///   disjoint block of memory currently allocated by `alloc` (via
402    ///   [`Self::allocate_zeroed`] or `GlobalAlloc::allocate`) with a layout
403    ///   whose size and alignment equal those of `*raw`
404    ///   (`Layout::for_value(&*raw)`), and `raw` is not used again after being
405    ///   passed to `box_from_raw_in`.
406    unsafe fn box_from_raw_in(raw: *mut T, alloc: Self) -> Self::Boxed;
407}
408
409/// Marker for the global allocator (`alloc::alloc::alloc` /
410/// `alloc::alloc::alloc_zeroed` / `Box::from_raw`).
411#[cfg(any(feature = "alloc", test))]
412pub(crate) struct GlobalAlloc;
413
414#[cfg(feature = "alloc")]
415impl GlobalAlloc {
416    /// Allocates uninitialized memory fitting `layout` from the global
417    /// allocator, returning a null pointer on allocation failure.
418    ///
419    /// # Safety
420    ///
421    /// `layout` must have non-zero size (`layout.size() != 0`).
422    #[inline(always)]
423    pub(crate) unsafe fn allocate(&self, layout: core::alloc::Layout) -> *mut u8 {
424        // SAFETY: The caller guarantees that `layout` has non-zero size [1].
425        //
426        // [1] Per https://doc.rust-lang.org/1.81.0/std/alloc/trait.GlobalAlloc.html#tymethod.alloc:
427        //
428        //   This function is unsafe because undefined behavior can result if
429        //   the caller does not ensure that layout has non-zero size.
430        unsafe { alloc::alloc::alloc(layout) }
431    }
432}
433
434// SAFETY: `allocate_zeroed` delegates to `alloc::alloc::alloc_zeroed(layout)`,
435// which returns either null or a fresh, wholly disjoint block of memory
436// currently allocated by the global allocator meeting the size and alignment of
437// `layout` with all bytes initialized to zero [1][2].
438//
439// [1] Per https://doc.rust-lang.org/1.81.0/std/alloc/trait.GlobalAlloc.html#tymethod.alloc:
440//
441//   Returns a pointer to newly-allocated memory, or null to indicate allocation
442//   failure.
443//
444// [2] Per https://doc.rust-lang.org/1.81.0/std/alloc/trait.GlobalAlloc.html#method.alloc_zeroed:
445//
446//   Behaves like `alloc`, but also ensures that the contents are set to zero
447//   before being returned.
448#[cfg(any(feature = "alloc", test))]
449unsafe impl<T: ?Sized> BoxAllocator<T> for GlobalAlloc {
450    type Boxed = alloc::boxed::Box<T>;
451
452    #[inline(always)]
453    unsafe fn allocate_zeroed(&self, layout: core::alloc::Layout) -> *mut u8 {
454        // SAFETY: The caller guarantees that `layout` has non-zero size [1].
455        //
456        // [1] Per https://doc.rust-lang.org/1.81.0/std/alloc/trait.GlobalAlloc.html#tymethod.alloc:
457        //
458        //   This function is unsafe because undefined behavior can result if
459        //   the caller does not ensure that layout has non-zero size.
460        unsafe { alloc::alloc::alloc_zeroed(layout) }
461    }
462
463    #[inline(always)]
464    unsafe fn box_from_raw_in(raw: *mut T, _alloc: GlobalAlloc) -> Self::Boxed {
465        // SAFETY: By caller precondition on `box_from_raw_in`:
466        // - `raw` points to a valid instance of `T` [1].
467        // - If `*raw` is zero-sized, `raw` is non-null and aligned for `T` [1],
468        //   and because `*raw` occupies zero bytes of memory, `Box` asserts
469        //   uniqueness over zero bytes [2].
470        // - If `*raw` is non-zero-sized, `raw` points to a fresh, wholly
471        //   disjoint block of memory currently allocated by the global
472        //   allocator with `Layout::for_value(&*raw)` and is not used again
473        //   after being passed to `Box::from_raw`, satisfying `Box`'s layout
474        //   and uniqueness requirements [1][2].
475        //
476        // [1] Per https://doc.rust-lang.org/1.81.0/std/boxed/index.html#memory-layout:
477        //
478        //   For zero-sized values, the `Box` pointer has to be non-null and
479        //   sufficiently aligned.
480        //
481        //   More precisely, a `value: *mut T` that has been allocated with the
482        //   `Global` allocator with `Layout::for_value(&*value)` may be
483        //   converted into a box using `Box::<T>::from_raw(value)`.
484        //
485        //   On top of these basic layout requirements, a `Box<T>` must point to
486        //   a valid value of `T`.
487        //
488        // [2] Per https://doc.rust-lang.org/1.81.0/std/boxed/index.html#considerations-for-unsafe-code:
489        //
490        //   The aliasing rules for `Box<T>` are the same as for `&mut T`.
491        //   `Box<T>` asserts uniqueness over its content.
492        unsafe { alloc::boxed::Box::from_raw(raw) }
493    }
494}
495
496// SAFETY: `allocate_zeroed` delegates to
497// `core::alloc::Allocator::allocate_zeroed`, which on `Ok(ptr)` returns a
498// `NonNull<[u8]>` denoting a fresh, wholly disjoint block of memory currently
499// allocated by `self` meeting the size and alignment guarantees of `layout`
500// with all bytes initialized to zero [1][2][3].
501//
502// [1] Per https://doc.rust-lang.org/1.100.0/core/alloc/trait.Allocator.html#tymethod.allocate:
503//
504//   On success, returns a `NonNull<[u8]>` meeting the size and alignment
505//   guarantees of `layout`.
506//
507//   Note that the returned block of memory is considered currently allocated
508//   with this allocator (and equivalent allocators).
509//
510// [2] Per https://doc.rust-lang.org/1.100.0/core/alloc/trait.Allocator.html#method.allocate_zeroed:
511//
512//   Behaves like `allocate`, but also ensures that the returned memory is
513//   zero-initialized.
514//
515// [3] Per https://doc.rust-lang.org/1.100.0/core/alloc/trait.Allocator.html#safety:
516//
517//   Additionally, any memory block returned by the allocator must satisfy the
518//   allocation invariants described in `core::ptr`. In particular, if a block
519//   has base address `p` and size `n`, then `p as usize + n <= usize::MAX`
520//   must hold. These blocks must also be wholly disjoint.
521#[cfg(all(not(no_zerocopy_allocator_api_1_100_0), feature = "alloc"))]
522unsafe impl<T: ?Sized, A: core::alloc::Allocator> BoxAllocator<T> for A {
523    type Boxed = alloc::boxed::Box<T, A>;
524
525    #[inline(always)]
526    unsafe fn allocate_zeroed(&self, layout: core::alloc::Layout) -> *mut u8 {
527        match core::alloc::Allocator::allocate_zeroed(self, layout) {
528            Ok(ptr) => ptr.cast::<u8>().as_ptr(),
529            Err(_) => core::ptr::null_mut(),
530        }
531    }
532
533    #[inline(always)]
534    unsafe fn box_from_raw_in(raw: *mut T, alloc: A) -> Self::Boxed {
535        // SAFETY: By caller precondition on `box_from_raw_in`:
536        // - `raw` points to a valid instance of `T` [1][2].
537        // - If `*raw` is zero-sized, `raw` is non-null and aligned for `T` [2],
538        //   and because `*raw` occupies zero bytes of memory, `Box` asserts
539        //   uniqueness over zero bytes [3].
540        // - If `*raw` is non-zero-sized, `raw` points to a fresh, wholly
541        //   disjoint block of memory currently allocated by `alloc` with
542        //   `Layout::for_value(&*raw)` and is not used again after being passed
543        //   to `Box::from_raw_in`. Per [4], moving `alloc` into
544        //   `Box::from_raw_in` preserves allocator equivalence, so the layout
545        //   fits [5] the block owned by `Box`'s allocator, satisfying `Box`'s
546        //   layout and uniqueness requirements [1][2][3].
547        //
548        // [1] Per https://doc.rust-lang.org/1.100.0/std/boxed/struct.Box.html#method.from_raw_in:
549        //
550        //   The raw pointer must point to a block of memory allocated by
551        //   `alloc`.
552        //
553        //   The safety conditions are described in the memory layout section.
554        //   Note that the considerations for unsafe code apply to all
555        //   `Box<T, A>` values.
556        //
557        // [2] Per https://doc.rust-lang.org/1.100.0/std/boxed/index.html#memory-layout:
558        //
559        //   For zero-sized values, the `Box` pointer has to be non-null and
560        //   sufficiently aligned.
561        //
562        //   More precisely, a `value: *mut T` that has been allocated with the
563        //   `Global` allocator with `Layout::for_value(&*value)` may be
564        //   converted into a box using `Box::<T>::from_raw(value)`.
565        //
566        //   On top of these basic layout requirements, a `Box<T>` must point to
567        //   a valid value of `T`.
568        //
569        // [3] Per https://doc.rust-lang.org/1.100.0/std/boxed/index.html#considerations-for-unsafe-code:
570        //
571        //   The aliasing rules for `Box<T>` are the same as for `&mut T`.
572        //   `Box<T>` asserts uniqueness over its content.
573        //
574        // [4] Per https://doc.rust-lang.org/1.100.0/core/alloc/trait.Allocator.html#equivalent-allocators:
575        //
576        //   Moving, subtyping, unsize-coercing, or trait-upcasting an allocator
577        //   does not change what the allocator is equivalent to.
578        //
579        // [5] Per https://doc.rust-lang.org/1.100.0/core/alloc/trait.Allocator.html#memory-fitting:
580        //
581        //   Some of the methods require that a `layout` fits a memory block or
582        //   vice versa. This means that the following conditions must hold:
583        //   * the memory block must be currently allocated by the allocator,
584        //   * `layout.align()` must be the same as the alignment of the layout
585        //     used to allocate the block, and
586        //   * `layout.size()` must fall in the range `min ..= max`, where:
587        //     - `min` is the size of the layout used to allocate the block, and
588        //     - `max` is the actual size returned from `allocate`,
589        //       `allocate_zeroed`, `grow`, `grow_zeroed`, or `shrink`.
590        unsafe { alloc::boxed::Box::from_raw_in(raw, alloc) }
591    }
592}
593
594/// Adapter that implements [`BoxAllocator<Wrapping<T>>`] by unwrapping one
595/// layer of [`Wrapping<T>`] before delegating to `A: BoxAllocator<T>`.
596///
597/// Because [`Wrapping<T>`] implements [`KnownLayout`] for all `T: Sized`, this
598/// allows [`new_box`] to allocate a `Box<T>` or `Box<T, A>` even when `T` does
599/// not implement `KnownLayout`.
600#[cfg(any(feature = "alloc", test))]
601pub(crate) struct UnwrapWrapping<A>(pub(crate) A);
602
603// SAFETY: `allocate_zeroed` delegates directly to
604// `self.0.allocate_zeroed(layout)`.
605#[cfg(any(feature = "alloc", test))]
606unsafe impl<T, A: BoxAllocator<T>> BoxAllocator<Wrapping<T>> for UnwrapWrapping<A> {
607    type Boxed = A::Boxed;
608
609    #[inline(always)]
610    unsafe fn allocate_zeroed(&self, layout: core::alloc::Layout) -> *mut u8 {
611        // SAFETY: The caller guarantees that `layout` has non-zero size.
612        unsafe { self.0.allocate_zeroed(layout) }
613    }
614
615    #[inline(always)]
616    unsafe fn box_from_raw_in(raw: *mut Wrapping<T>, alloc: Self) -> Self::Boxed {
617        // SAFETY: `Wrapping<T>` is `#[repr(transparent)]` with a single field
618        // of type `T`, and is guaranteed to have the same layout as `T` [1], so
619        // `Wrapping<T>` and `T` have identical size, alignment, and
620        // bit-validity. Since `raw` satisfies `box_from_raw_in`'s preconditions
621        // for `Wrapping<T>` and was allocated by `alloc.0`, `raw.cast::<T>()`
622        // satisfies `A::box_from_raw_in`'s preconditions for `T`.
623        //
624        // [1] Per https://doc.rust-lang.org/1.81.0/std/num/struct.Wrapping.html#layout-1:
625        //
626        //   `Wrapping<T>` is guaranteed to have the same layout and ABI as `T`
627        unsafe { A::box_from_raw_in(raw.cast::<T>(), alloc.0) }
628    }
629}
630
631/// Uses `allocate` and `alloc` to create a boxed `T`.
632///
633/// # Errors
634///
635/// Returns an error on allocation failure. If `allocate` does not panic or
636/// abort (and dropping `alloc` on error does not panic or abort), allocation
637/// failure is guaranteed never to cause a panic or an abort.
638///
639/// # Safety
640///
641/// - `allocate` must be either [`BoxAllocator::allocate_zeroed`] or (when
642///   `A = GlobalAlloc`) `GlobalAlloc::allocate`.
643/// - The referent of the box returned by `new_box` has the same bit-validity as
644///   the referent of the pointer returned by the given `allocate` (or a
645///   zero-byte sequence when `T` with `meta` has size `0`), which must be a
646///   valid instance of `T` with `meta`.
647#[must_use = "has no side effects (other than allocation)"]
648#[cfg(any(feature = "alloc", test))]
649#[inline]
650pub(crate) unsafe fn new_box<T, A>(
651    meta: T::PointerMetadata,
652    alloc: A,
653    allocate: unsafe fn(&A, core::alloc::Layout) -> *mut u8,
654) -> Result<A::Boxed, AllocError>
655where
656    T: ?Sized + crate::KnownLayout,
657    A: BoxAllocator<T>,
658{
659    let align = T::LAYOUT.align.get();
660    if !T::is_valid_metadata(meta) {
661        return Err(AllocError);
662    }
663    let size = match T::size_for_metadata(meta) {
664        Some(size) => size,
665        // Thanks to the `!T::is_valid_metadata(meta)` check
666        // above, this branch is unreachable. Fortunately, the
667        // optimizer recognizes this, so replacing this branch
668        // with `unreachable_unchecked` produces no codegen
669        // improvements.
670        None => return Err(AllocError),
671    };
672    let ptr = if size != 0 {
673        // SAFETY:
674        // - `align` is derived from a `NonZeroUsize` and is thus non-zero.
675        // - `align` is a power of two because, by invariant on
676        //   `KnownLayout::LAYOUT` `<T as KnownLayout>::LAYOUT` accurately
677        //   reflects the layout of `T`.
678        // - `size`, by invariant on `size_for_metadata` is well-aligned for
679        //   `align` and, by the check on `T::is_valid_metadata(meta)`, is less
680        //   than `isize::MAX`.
681        let layout: Layout = unsafe { Layout::from_size_align_unchecked(size, align) };
682        // SAFETY: By contract on the caller, `allocate` is either
683        // `BoxAllocator::allocate_zeroed` or `GlobalAlloc::allocate`. The above
684        // check ensures their shared safety precondition: that `layout` has
685        // non-zero size.
686        let ptr = unsafe { allocate(&alloc, layout) };
687        match NonNull::new(ptr) {
688            Some(ptr) => ptr,
689            None => return Err(AllocError),
690        }
691    } else {
692        // We use `transmute` instead of an `as` cast since Miri (with strict
693        // provenance enabled) notices and complains that an `as` cast creates a
694        // pointer with no provenance. Miri isn't smart enough to realize that
695        // we're only executing this branch when we're constructing a zero-sized
696        // `Box`, which doesn't require provenance.
697        //
698        // SAFETY: any initialized bit sequence is a bit-valid `*mut u8`. All
699        // bits of a `usize` are initialized.
700        //
701        // `#[allow(unknown_lints)]` is for `integer_to_ptr_transmutes`
702        #[allow(unknown_lints)]
703        #[allow(clippy::useless_transmute, integer_to_ptr_transmutes)]
704        let dangling = unsafe { mem::transmute::<usize, *mut u8>(align) };
705        // SAFETY: `dangling` is constructed from `align`, which is derived from
706        // a `NonZeroUsize`, which is guaranteed to be non-zero.
707        //
708        // `Box<[T]>` does not allocate when `T` is zero-sized or when `len` is
709        // zero, but it does require a non-null dangling pointer for its
710        // allocation.
711        //
712        // FIXME(https://github.com/rust-lang/rust/issues/95228): Use
713        // `std::ptr::without_provenance` once it's stable. That may optimize
714        // better. As written, Rust may assume that this consumes "exposed"
715        // provenance, and thus Rust may have to assume that this may consume
716        // provenance from any pointer whose provenance has been exposed.
717        unsafe { NonNull::new_unchecked(dangling) }
718    };
719
720    let ptr = T::raw_from_ptr_len(ptr, meta);
721
722    // SAFETY:
723    // - By contract on the caller, the referent of `ptr` (with metadata `meta`)
724    //   is a valid instance of `T`.
725    // - By invariant on `T: KnownLayout`, the size and alignment of `*ptr` are
726    //   `size` and `align` respectively.
727    // - If `size == 0`, `ptr` was constructed from `dangling` with address
728    //   `align > 0`, so `ptr.as_ptr()` is non-null and aligned to `align`.
729    // - If `size != 0`, `ptr` was allocated by `allocate(&alloc, layout)` (with
730    //   `layout` having size `size` and alignment `align`), which by contract
731    //   on `allocate` and `A: BoxAllocator<T>` returns a fresh, wholly disjoint
732    //   block of memory currently allocated by `alloc` fitting `layout`, and
733    //   `ptr` is not used again after being passed to `box_from_raw_in`.
734    Ok(unsafe { A::box_from_raw_in(ptr.as_ptr(), alloc) })
735}
736
737mod len_of {
738    use super::*;
739
740    /// A witness type for metadata of a valid instance of `&T`.
741    pub struct MetadataOf<T: ?Sized + KnownLayout> {
742        /// # Safety
743        ///
744        /// The size of an instance of `&T` with the given metadata is not
745        /// larger than `isize::MAX`.
746        meta: T::PointerMetadata,
747        _p: PhantomData<T>,
748    }
749
750    impl<T: ?Sized + KnownLayout> Copy for MetadataOf<T> {}
751    impl<T: ?Sized + KnownLayout> Clone for MetadataOf<T> {
752        #[inline]
753        fn clone(&self) -> Self {
754            *self
755        }
756    }
757
758    impl<T: ?Sized + KnownLayout> core::fmt::Debug for MetadataOf<T>
759    where
760        T::PointerMetadata: core::fmt::Debug,
761    {
762        #[inline]
763        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
764            f.debug_struct("MetadataOf").field("meta", &self.meta).finish()
765        }
766    }
767
768    impl<T: ?Sized> MetadataOf<T>
769    where
770        T: KnownLayout,
771    {
772        /// Returns `None` if `meta` is greater than `t`'s metadata.
773        #[inline(always)]
774        pub(crate) fn new_in_bounds(t: &T, meta: usize) -> Option<Self>
775        where
776            T: KnownLayout<PointerMetadata = usize>,
777        {
778            if meta <= Ptr::from_ref(t).len() {
779                // SAFETY: We have checked that `meta` is not greater than `t`'s
780                // metadata, which, by invariant on `&T`, addresses no more than
781                // `isize::MAX` bytes [1][2].
782                //
783                // [1] Per https://doc.rust-lang.org/1.85.0/std/primitive.reference.html#safety:
784                //
785                //    For all types, `T: ?Sized`, and for all `t: &T` or `t:
786                //    &mut T`, when such values cross an API boundary, the
787                //    following invariants must generally be upheld:
788                //
789                //    * `t` is non-null
790                //    * `t` is aligned to `align_of_val(t)`
791                //    * if `size_of_val(t) > 0`, then `t` is dereferenceable for
792                //      `size_of_val(t)` many bytes
793                //
794                //    If `t` points at address `a`, being "dereferenceable" for
795                //    N bytes means that the memory range `[a, a + N)` is all
796                //    contained within a single allocated object.
797                //
798                // [2] Per https://doc.rust-lang.org/1.85.0/std/ptr/index.html#allocated-object:
799                //
800                //    For any allocated object with `base` address, `size`, and
801                //    a set of `addresses`, the following are guaranteed:
802                //    - For all addresses `a` in `addresses`, `a` is in the
803                //      range `base .. (base + size)` (note that this requires
804                //      `a < base + size`, not `a <= base + size`)
805                //    - `base` is not equal to [`null()`] (i.e., the address
806                //      with the numerical value 0)
807                //    - `base + size <= usize::MAX`
808                //    - `size <= isize::MAX`
809                Some(unsafe { Self::new_unchecked(meta) })
810            } else {
811                None
812            }
813        }
814
815        /// # Safety
816        ///
817        /// The size of an instance of `&T` with the given metadata is not
818        /// larger than `isize::MAX`.
819        pub(crate) unsafe fn new_unchecked(meta: T::PointerMetadata) -> Self {
820            // SAFETY: The caller has promised that the size of an instance of
821            // `&T` with the given metadata is not larger than `isize::MAX`.
822            Self { meta, _p: PhantomData }
823        }
824
825        pub(crate) fn get(&self) -> T::PointerMetadata
826        where
827            T::PointerMetadata: Copy,
828        {
829            self.meta
830        }
831
832        #[inline(always)]
833        pub(crate) fn validate_cast_and_convert_metadata(
834            addr: usize,
835            bytes_len: MetadataOf<[u8]>,
836            cast_type: CastType,
837            meta: Option<T::PointerMetadata>,
838        ) -> Result<(MetadataOf<T>, MetadataOf<[u8]>), MetadataCastError> {
839            let layout = match meta {
840                None => T::LAYOUT,
841                // This can return `Err(MetadataCastError::Size)` if the
842                // metadata describes an object which can't fit in an `isize`.
843                Some(meta) => {
844                    if !T::is_valid_metadata(meta) {
845                        return Err(MetadataCastError::Size);
846                    }
847                    let size = match T::size_for_metadata(meta) {
848                        Some(size) => size,
849                        // Thanks to the `!T::is_valid_metadata(meta)` check
850                        // above, this branch is unreachable. Fortunately, the
851                        // optimizer recognizes this, so replacing this branch
852                        // with `unreachable_unchecked` produces no codegen
853                        // improvements.
854                        None => return Err(MetadataCastError::Size),
855                    };
856                    DstLayout {
857                        align: T::LAYOUT.align,
858                        size_info: crate::SizeInfo::Sized { size },
859                        statically_shallow_unpadded: false,
860                    }
861                }
862            };
863            // Lemma 0: By contract on `validate_cast_and_convert_metadata`, if
864            // the result is `Ok(..)`, then a `&T` with `elems` trailing slice
865            // elements is no larger in size than `bytes_len.get()`.
866            let (elems, split_at) =
867                layout.validate_cast_and_convert_metadata(addr, bytes_len.get(), cast_type)?;
868            let elems = T::PointerMetadata::from_elem_count(elems);
869
870            // For a slice DST type, if `meta` is `Some(elems)`, then we
871            // synthesize `layout` to describe a sized type whose size is equal
872            // to the size of the instance that we are asked to cast. For sized
873            // types, `validate_cast_and_convert_metadata` returns `elems == 0`.
874            // Thus, in this case, we need to use the `elems` passed by the
875            // caller, not the one returned by
876            // `validate_cast_and_convert_metadata`.
877            //
878            // Lemma 1: A `&T` with `elems` trailing slice elements is no larger
879            // in size than `bytes_len.get()`. Proof:
880            // - If `meta` is `None`, then `elems` satisfies this condition by
881            //   Lemma 0.
882            // - If `meta` is `Some(meta)`, then `layout` describes an object
883            //   whose size is equal to the size of an `&T` with `meta`
884            //   metadata. By Lemma 0, that size is not larger than
885            //   `bytes_len.get()`.
886            //
887            // Lemma 2: A `&T` with `elems` trailing slice elements is no larger
888            // than `isize::MAX` bytes. Proof: By Lemma 1, a `&T` with metadata
889            // `elems` is not larger in size than `bytes_len.get()`. By
890            // invariant on `MetadataOf<[u8]>`, a `&[u8]` with metadata
891            // `bytes_len` is not larger than `isize::MAX`. Because
892            // `size_of::<u8>()` is `1`, a `&[u8]` with metadata `bytes_len` has
893            // size `bytes_len.get()` bytes. Therefore, a `&T` with metadata
894            // `elems` has size not larger than `isize::MAX`.
895            let elems = meta.unwrap_or(elems);
896
897            // SAFETY: See Lemma 2.
898            let elems = unsafe { MetadataOf::new_unchecked(elems) };
899
900            // SAFETY: Let `size` be the size of a `&T` with metadata `elems`.
901            // By post-condition on `validate_cast_and_convert_metadata`, one of
902            // the following conditions holds:
903            // - `split_at == size`, in which case, by Lemma 2, `split_at <=
904            //   isize::MAX`. Since `size_of::<u8>() == 1`, a `[u8]` with
905            //   `split_at` elems has size not larger than `isize::MAX`.
906            // - `split_at == bytes_len - size`. Since `bytes_len:
907            //   MetadataOf<u8>`, and since `size` is non-negative, `split_at`
908            //   addresses no more bytes than `bytes_len` does. Since
909            //   `bytes_len: MetadataOf<u8>`, `bytes_len` describes a `[u8]`
910            //   which has no more than `isize::MAX` bytes, and thus so does
911            //   `split_at`.
912            let split_at = unsafe { MetadataOf::<[u8]>::new_unchecked(split_at) };
913            Ok((elems, split_at))
914        }
915    }
916}
917
918pub use len_of::MetadataOf;
919
920/// Since we support multiple versions of Rust, there are often features which
921/// have been stabilized in the most recent stable release which do not yet
922/// exist (stably) on our MSRV. This module provides polyfills for those
923/// features so that we can write more "modern" code, and just remove the
924/// polyfill once our MSRV supports the corresponding feature. Without this,
925/// we'd have to write worse/more verbose code and leave FIXME comments
926/// sprinkled throughout the codebase to update to the new pattern once it's
927/// stabilized.
928///
929/// Each trait is imported as `_` at the crate root; each polyfill should "just
930/// work" at usage sites.
931pub(crate) mod polyfills {
932    use core::ptr::{self, NonNull};
933
934    // A polyfill for `NonNull::slice_from_raw_parts` that we can use before our
935    // MSRV is 1.70, when that function was stabilized.
936    //
937    // The `#[allow(unused)]` is necessary because, on sufficiently recent
938    // toolchain versions, `ptr.slice_from_raw_parts()` resolves to the inherent
939    // method rather than to this trait, and so this trait is considered unused.
940    //
941    // FIXME(#67): Once our MSRV is 1.70, remove this.
942    #[allow(unused)]
943    pub(crate) trait NonNullExt<T> {
944        fn slice_from_raw_parts(data: Self, len: usize) -> NonNull<[T]>;
945    }
946
947    impl<T> NonNullExt<T> for NonNull<T> {
948        // NOTE on coverage: this will never be tested in nightly since it's a
949        // polyfill for a feature which has been stabilized on our nightly
950        // toolchain.
951        #[cfg_attr(
952            all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
953            coverage(off)
954        )]
955        #[inline(always)]
956        fn slice_from_raw_parts(data: Self, len: usize) -> NonNull<[T]> {
957            let ptr = ptr::slice_from_raw_parts_mut(data.as_ptr(), len);
958            // SAFETY: `ptr` is converted from `data`, which is non-null.
959            unsafe { NonNull::new_unchecked(ptr) }
960        }
961    }
962
963    // A polyfill for `Self::unchecked_sub` that we can use until methods like
964    // `usize::unchecked_sub` is stabilized.
965    //
966    // The `#[allow(unused)]` is necessary because, on sufficiently recent
967    // toolchain versions, `ptr.slice_from_raw_parts()` resolves to the inherent
968    // method rather than to this trait, and so this trait is considered unused.
969    //
970    // FIXME(#67): Once our MSRV is high enough, remove this.
971    #[allow(unused)]
972    pub(crate) trait NumExt {
973        /// Add without checking for overflow.
974        ///
975        /// # Safety
976        ///
977        /// The caller promises that the addition will not overflow.
978        unsafe fn unchecked_add(self, rhs: Self) -> Self;
979
980        /// Subtract without checking for underflow.
981        ///
982        /// # Safety
983        ///
984        /// The caller promises that the subtraction will not underflow.
985        unsafe fn unchecked_sub(self, rhs: Self) -> Self;
986
987        /// Multiply without checking for overflow.
988        ///
989        /// # Safety
990        ///
991        /// The caller promises that the multiplication will not overflow.
992        unsafe fn unchecked_mul(self, rhs: Self) -> Self;
993    }
994
995    // NOTE on coverage: these will never be tested in nightly since they're
996    // polyfills for a feature which has been stabilized on our nightly
997    // toolchain.
998    impl NumExt for usize {
999        #[cfg_attr(
1000            all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
1001            coverage(off)
1002        )]
1003        #[inline(always)]
1004        unsafe fn unchecked_add(self, rhs: usize) -> usize {
1005            match self.checked_add(rhs) {
1006                Some(x) => x,
1007                None => {
1008                    // SAFETY: The caller promises that the addition will not
1009                    // underflow.
1010                    unsafe { core::hint::unreachable_unchecked() }
1011                }
1012            }
1013        }
1014
1015        #[cfg_attr(
1016            all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
1017            coverage(off)
1018        )]
1019        #[inline(always)]
1020        unsafe fn unchecked_sub(self, rhs: usize) -> usize {
1021            match self.checked_sub(rhs) {
1022                Some(x) => x,
1023                None => {
1024                    // SAFETY: The caller promises that the subtraction will not
1025                    // underflow.
1026                    unsafe { core::hint::unreachable_unchecked() }
1027                }
1028            }
1029        }
1030
1031        #[cfg_attr(
1032            all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
1033            coverage(off)
1034        )]
1035        #[inline(always)]
1036        unsafe fn unchecked_mul(self, rhs: usize) -> usize {
1037            match self.checked_mul(rhs) {
1038                Some(x) => x,
1039                None => {
1040                    // SAFETY: The caller promises that the multiplication will
1041                    // not overflow.
1042                    unsafe { core::hint::unreachable_unchecked() }
1043                }
1044            }
1045        }
1046    }
1047}
1048
1049#[cfg(test)]
1050pub(crate) mod testutil {
1051    use crate::*;
1052
1053    /// A `T` which is aligned to at least `align_of::<A>()`.
1054    #[derive(Default)]
1055    pub(crate) struct Align<T, A> {
1056        pub(crate) t: T,
1057        _a: [A; 0],
1058    }
1059
1060    impl<T: Default, A> Align<T, A> {
1061        pub(crate) fn set_default(&mut self) {
1062            self.t = T::default();
1063        }
1064    }
1065
1066    impl<T, A> Align<T, A> {
1067        pub(crate) const fn new(t: T) -> Align<T, A> {
1068            Align { t, _a: [] }
1069        }
1070    }
1071
1072    /// A `T` which is guaranteed not to satisfy `align_of::<A>()`.
1073    ///
1074    /// It must be the case that `align_of::<T>() < align_of::<A>()` in order
1075    /// for this type to work properly.
1076    #[repr(C)]
1077    pub(crate) struct ForceUnalign<T: Unaligned, A> {
1078        // The outer struct is aligned to `A`, and, thanks to `repr(C)`, `t` is
1079        // placed at the minimum offset that guarantees its alignment. If
1080        // `align_of::<T>() < align_of::<A>()`, then that offset will be
1081        // guaranteed *not* to satisfy `align_of::<A>()`.
1082        //
1083        // Note that we need `T: Unaligned` in order to guarantee that there is
1084        // no padding between `_u` and `t`.
1085        _u: u8,
1086        pub(crate) t: T,
1087        _a: [A; 0],
1088    }
1089
1090    impl<T: Unaligned, A> ForceUnalign<T, A> {
1091        pub(crate) fn new(t: T) -> ForceUnalign<T, A> {
1092            ForceUnalign { _u: 0, t, _a: [] }
1093        }
1094    }
1095    // A `u64` with alignment 8.
1096    //
1097    // Though `u64` has alignment 8 on some platforms, it's not guaranteed. By
1098    // contrast, `AU64` is guaranteed to have alignment 8 on all platforms.
1099    #[derive(
1100        KnownLayout,
1101        Immutable,
1102        FromBytes,
1103        IntoBytes,
1104        Eq,
1105        PartialEq,
1106        Ord,
1107        PartialOrd,
1108        Default,
1109        Debug,
1110        Copy,
1111        Clone,
1112    )]
1113    #[repr(C, align(8))]
1114    pub(crate) struct AU64(pub(crate) u64);
1115
1116    impl AU64 {
1117        // Converts this `AU64` to bytes using this platform's endianness.
1118        pub(crate) fn to_bytes(self) -> [u8; 8] {
1119            crate::transmute!(self)
1120        }
1121    }
1122
1123    impl Display for AU64 {
1124        #[cfg_attr(
1125            all(coverage_nightly, __ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
1126            coverage(off)
1127        )]
1128        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1129            Display::fmt(&self.0, f)
1130        }
1131    }
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136    use super::*;
1137
1138    #[test]
1139    fn test_round_down_to_next_multiple_of_alignment() {
1140        // Division by `NonZeroUsize` unsupported on our MSRV.
1141        #[allow(clippy::needless_nonzero_get)]
1142        fn alt_impl(n: usize, align: NonZeroUsize) -> usize {
1143            let mul = n / align.get();
1144            mul * align.get()
1145        }
1146
1147        for align in [1, 2, 4, 8, 16] {
1148            for n in 0..256 {
1149                let align = NonZeroUsize::new(align).unwrap();
1150                let want = alt_impl(n, align);
1151                let got = round_down_to_next_multiple_of_alignment(n, align);
1152                assert_eq!(got, want, "round_down_to_next_multiple_of_alignment({}, {})", n, align);
1153            }
1154        }
1155    }
1156
1157    #[rustversion::since(1.57.0)]
1158    #[test]
1159    #[should_panic]
1160    fn test_round_down_to_next_multiple_of_alignment_zerocopy_panic_in_const_and_vec_try_reserve() {
1161        round_down_to_next_multiple_of_alignment(0, NonZeroUsize::new(3).unwrap());
1162    }
1163    #[test]
1164    fn test_send_sync_phantom_data() {
1165        let x = SendSyncPhantomData::<u8>::default();
1166        let y = x.clone();
1167        assert!(x == y);
1168        assert!(x == SendSyncPhantomData::<u8>::default());
1169    }
1170
1171    #[test]
1172    #[allow(clippy::as_conversions)]
1173    fn test_as_address() {
1174        let x = 0u8;
1175        let r = &x;
1176        let mut x_mut = 0u8;
1177        let rm = &mut x_mut;
1178        let p = r as *const u8;
1179        let pm = rm as *mut u8;
1180        let nn = NonNull::new(p as *mut u8).unwrap();
1181
1182        assert_eq!(AsAddress::addr(r), p as usize);
1183        assert_eq!(AsAddress::addr(rm), pm as usize);
1184        assert_eq!(AsAddress::addr(p), p as usize);
1185        assert_eq!(AsAddress::addr(pm), pm as usize);
1186        assert_eq!(AsAddress::addr(nn), p as usize);
1187    }
1188}