zerocopy/
wrappers.rs

1// Copyright 2023 The Fuchsia Authors
2//
3// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6// This file may not be copied, modified, or distributed except according to
7// those terms.
8
9use core::{fmt, hash::Hash};
10
11use super::*;
12
13/// A type with no alignment requirement.
14///
15/// An `Unalign` wraps a `T`, removing any alignment requirement. `Unalign<T>`
16/// has the same size and bit validity as `T`, but not necessarily the same
17/// alignment [or ABI]. This is useful if a type with an alignment requirement
18/// needs to be read from a chunk of memory which provides no alignment
19/// guarantees.
20///
21/// Since `Unalign` has no alignment requirement, the inner `T` may not be
22/// properly aligned in memory. There are five ways to access the inner `T`:
23/// - by value, using [`get`] or [`into_inner`]
24/// - by reference inside of a callback, using [`update`]
25/// - fallibly by reference, using [`try_deref`] or [`try_deref_mut`]; these can
26///   fail if the `Unalign` does not satisfy `T`'s alignment requirement at
27///   runtime
28/// - unsafely by reference, using [`deref_unchecked`] or
29///   [`deref_mut_unchecked`]; it is the caller's responsibility to ensure that
30///   the `Unalign` satisfies `T`'s alignment requirement
31/// - (where `T: Unaligned`) infallibly by reference, using [`Deref::deref`] or
32///   [`DerefMut::deref_mut`]
33///
34/// [or ABI]: https://github.com/google/zerocopy/issues/164
35/// [`get`]: Unalign::get
36/// [`into_inner`]: Unalign::into_inner
37/// [`update`]: Unalign::update
38/// [`try_deref`]: Unalign::try_deref
39/// [`try_deref_mut`]: Unalign::try_deref_mut
40/// [`deref_unchecked`]: Unalign::deref_unchecked
41/// [`deref_mut_unchecked`]: Unalign::deref_mut_unchecked
42///
43/// # Example
44///
45/// In this example, we need `EthernetFrame` to have no alignment requirement -
46/// and thus implement [`Unaligned`]. `EtherType` is `#[repr(u16)]` and so
47/// cannot implement `Unaligned`. We use `Unalign` to relax `EtherType`'s
48/// alignment requirement so that `EthernetFrame` has no alignment requirement
49/// and can implement `Unaligned`.
50///
51/// ```rust
52/// use zerocopy::*;
53/// # use zerocopy_derive::*;
54/// # #[derive(FromBytes, KnownLayout, Immutable, Unaligned)] #[repr(C)] struct Mac([u8; 6]);
55///
56/// # #[derive(PartialEq, Copy, Clone, Debug)]
57/// #[derive(TryFromBytes, KnownLayout, Immutable)]
58/// #[repr(u16)]
59/// enum EtherType {
60///     Ipv4 = 0x0800u16.to_be(),
61///     Arp = 0x0806u16.to_be(),
62///     Ipv6 = 0x86DDu16.to_be(),
63///     # /*
64///     ...
65///     # */
66/// }
67///
68/// #[derive(TryFromBytes, KnownLayout, Immutable, Unaligned)]
69/// #[repr(C)]
70/// struct EthernetFrame {
71///     src: Mac,
72///     dst: Mac,
73///     ethertype: Unalign<EtherType>,
74///     payload: [u8],
75/// }
76///
77/// let bytes = &[
78///     # 0, 1, 2, 3, 4, 5,
79///     # 6, 7, 8, 9, 10, 11,
80///     # /*
81///     ...
82///     # */
83///     0x86, 0xDD,            // EtherType
84///     0xDE, 0xAD, 0xBE, 0xEF // Payload
85/// ][..];
86///
87/// // PANICS: Guaranteed not to panic because `bytes` is of the right
88/// // length, has the right contents, and `EthernetFrame` has no
89/// // alignment requirement.
90/// let packet = EthernetFrame::try_ref_from_bytes(&bytes).unwrap();
91///
92/// assert_eq!(packet.ethertype.get(), EtherType::Ipv6);
93/// assert_eq!(packet.payload, [0xDE, 0xAD, 0xBE, 0xEF]);
94/// ```
95///
96/// # Safety
97///
98/// `Unalign<T>` is guaranteed to have the same size and bit validity as `T`,
99/// and to have [`UnsafeCell`]s covering the same byte ranges as `T`.
100/// `Unalign<T>` is guaranteed to have alignment 1.
101// NOTE: This type is sound to use with types that need to be dropped. The
102// reason is that the compiler-generated drop code automatically moves all
103// values to aligned memory slots before dropping them in-place. This is not
104// well-documented, but it's hinted at in places like [1] and [2]. However, this
105// also means that `T` must be `Sized`; unless something changes, we can never
106// support unsized `T`. [3]
107//
108// [1] https://github.com/rust-lang/rust/issues/54148#issuecomment-420529646
109// [2] https://github.com/google/zerocopy/pull/126#discussion_r1018512323
110// [3] https://github.com/google/zerocopy/issues/209
111#[allow(missing_debug_implementations)]
112#[derive(Default, Copy)]
113#[cfg_attr(any(feature = "derive", test), derive(Immutable, FromBytes, IntoBytes, Unaligned))]
114#[repr(C, packed)]
115pub struct Unalign<T>(T);
116
117// We do not use `derive(KnownLayout)` on `Unalign`, because the derive is not
118// smart enough to realize that `Unalign<T>` is always sized and thus emits a
119// `KnownLayout` impl bounded on `T: KnownLayout.` This is overly restrictive.
120impl_known_layout!(T => Unalign<T>);
121
122// FIXME(https://github.com/rust-lang/rust-clippy/issues/16087): Move these
123// attributes below the comment once this Clippy bug is fixed.
124#[cfg_attr(
125    all(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS, any(feature = "derive", test)),
126    expect(unused_unsafe)
127)]
128#[cfg_attr(
129    all(
130        not(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
131        any(feature = "derive", test)
132    ),
133    allow(unused_unsafe)
134)]
135// SAFETY:
136// - `Unalign<T>` promises to have alignment 1, and so we don't require that `T:
137//   Unaligned`.
138// - `Unalign<T>` has the same bit validity as `T`, and so it is `FromZeros`,
139//   `FromBytes`, or `IntoBytes` exactly when `T` is as well.
140// - `Immutable`: `Unalign<T>` has the same fields as `T`, so it contains
141//   `UnsafeCell`s exactly when `T` does.
142// - `TryFromBytes`: `Unalign<T>` has the same the same bit validity as `T`, so
143//   `T::is_bit_valid` is a sound implementation of `is_bit_valid`.
144//
145#[allow(clippy::multiple_unsafe_ops_per_block)]
146const _: () = unsafe {
147    impl_or_verify!(T => Unaligned for Unalign<T>);
148    impl_or_verify!(T: Immutable => Immutable for Unalign<T>);
149    impl_or_verify!(
150        T: TryFromBytes => TryFromBytes for Unalign<T>;
151        |c| T::is_bit_valid(c.transmute())
152    );
153    impl_or_verify!(T: FromZeros => FromZeros for Unalign<T>);
154    impl_or_verify!(T: FromBytes => FromBytes for Unalign<T>);
155    impl_or_verify!(T: IntoBytes => IntoBytes for Unalign<T>);
156};
157
158// Note that `Unalign: Clone` only if `T: Copy`. Since the inner `T` may not be
159// aligned, there's no way to safely call `T::clone`, and so a `T: Clone` bound
160// is not sufficient to implement `Clone` for `Unalign`.
161impl<T: Copy> Clone for Unalign<T> {
162    #[inline(always)]
163    fn clone(&self) -> Unalign<T> {
164        *self
165    }
166}
167
168impl<T> Unalign<T> {
169    /// Constructs a new `Unalign`.
170    #[inline(always)]
171    pub const fn new(val: T) -> Unalign<T> {
172        Unalign(val)
173    }
174
175    /// Consumes `self`, returning the inner `T`.
176    #[inline(always)]
177    pub const fn into_inner(self) -> T {
178        // SAFETY: Since `Unalign` is `#[repr(C, packed)]`, it has the same size
179        // and bit validity as `T`.
180        //
181        // We do this instead of just destructuring in order to prevent
182        // `Unalign`'s `Drop::drop` from being run, since dropping is not
183        // supported in `const fn`s.
184        //
185        // FIXME(https://github.com/rust-lang/rust/issues/73255): Destructure
186        // instead of using unsafe.
187        unsafe { crate::util::transmute_unchecked(self) }
188    }
189
190    /// Attempts to return a reference to the wrapped `T`, failing if `self` is
191    /// not properly aligned.
192    ///
193    /// If `self` does not satisfy `align_of::<T>()`, then `try_deref` returns
194    /// `Err`.
195    ///
196    /// If `T: Unaligned`, then `Unalign<T>` implements [`Deref`], and callers
197    /// may prefer [`Deref::deref`], which is infallible.
198    #[inline(always)]
199    pub fn try_deref(&self) -> Result<&T, AlignmentError<&Self, T>> {
200        let inner = Ptr::from_ref(self).transmute();
201        match inner.try_into_aligned() {
202            Ok(aligned) => Ok(aligned.as_ref()),
203            Err(err) => Err(err.map_src(|src| src.into_unalign().as_ref())),
204        }
205    }
206
207    /// Attempts to return a mutable reference to the wrapped `T`, failing if
208    /// `self` is not properly aligned.
209    ///
210    /// If `self` does not satisfy `align_of::<T>()`, then `try_deref` returns
211    /// `Err`.
212    ///
213    /// If `T: Unaligned`, then `Unalign<T>` implements [`DerefMut`], and
214    /// callers may prefer [`DerefMut::deref_mut`], which is infallible.
215    #[inline(always)]
216    pub fn try_deref_mut(&mut self) -> Result<&mut T, AlignmentError<&mut Self, T>> {
217        let inner = Ptr::from_mut(self).transmute::<_, _, (_, (_, _))>();
218        match inner.try_into_aligned() {
219            Ok(aligned) => Ok(aligned.as_mut()),
220            Err(err) => Err(err.map_src(|src| src.into_unalign().as_mut())),
221        }
222    }
223
224    /// Returns a reference to the wrapped `T` without checking alignment.
225    ///
226    /// If `T: Unaligned`, then `Unalign<T>` implements[ `Deref`], and callers
227    /// may prefer [`Deref::deref`], which is safe.
228    ///
229    /// # Safety
230    ///
231    /// The caller must guarantee that `self` satisfies `align_of::<T>()`.
232    #[inline(always)]
233    pub const unsafe fn deref_unchecked(&self) -> &T {
234        // SAFETY: `Unalign<T>` is `repr(transparent)`, so there is a valid `T`
235        // at the same memory location as `self`. It has no alignment guarantee,
236        // but the caller has promised that `self` is properly aligned, so we
237        // know that it is sound to create a reference to `T` at this memory
238        // location.
239        //
240        // We use `mem::transmute` instead of `&*self.get_ptr()` because
241        // dereferencing pointers is not stable in `const` on our current MSRV
242        // (1.56 as of this writing).
243        unsafe { mem::transmute(self) }
244    }
245
246    /// Returns a mutable reference to the wrapped `T` without checking
247    /// alignment.
248    ///
249    /// If `T: Unaligned`, then `Unalign<T>` implements[ `DerefMut`], and
250    /// callers may prefer [`DerefMut::deref_mut`], which is safe.
251    ///
252    /// # Safety
253    ///
254    /// The caller must guarantee that `self` satisfies `align_of::<T>()`.
255    #[inline(always)]
256    pub unsafe fn deref_mut_unchecked(&mut self) -> &mut T {
257        // SAFETY: `self.get_mut_ptr()` returns a raw pointer to a valid `T` at
258        // the same memory location as `self`. It has no alignment guarantee,
259        // but the caller has promised that `self` is properly aligned, so we
260        // know that the pointer itself is aligned, and thus that it is sound to
261        // create a reference to a `T` at this memory location.
262        unsafe { &mut *self.get_mut_ptr() }
263    }
264
265    /// Gets an unaligned raw pointer to the inner `T`.
266    ///
267    /// # Safety
268    ///
269    /// The returned raw pointer is not necessarily aligned to
270    /// `align_of::<T>()`. Most functions which operate on raw pointers require
271    /// those pointers to be aligned, so calling those functions with the result
272    /// of `get_ptr` will result in undefined behavior if alignment is not
273    /// guaranteed using some out-of-band mechanism. In general, the only
274    /// functions which are safe to call with this pointer are those which are
275    /// explicitly documented as being sound to use with an unaligned pointer,
276    /// such as [`read_unaligned`].
277    ///
278    /// Even if the caller is permitted to mutate `self` (e.g. they have
279    /// ownership or a mutable borrow), it is not guaranteed to be sound to
280    /// write through the returned pointer. If writing is required, prefer
281    /// [`get_mut_ptr`] instead.
282    ///
283    /// [`read_unaligned`]: core::ptr::read_unaligned
284    /// [`get_mut_ptr`]: Unalign::get_mut_ptr
285    #[inline(always)]
286    pub const fn get_ptr(&self) -> *const T {
287        ptr::addr_of!(self.0)
288    }
289
290    /// Gets an unaligned mutable raw pointer to the inner `T`.
291    ///
292    /// # Safety
293    ///
294    /// The returned raw pointer is not necessarily aligned to
295    /// `align_of::<T>()`. Most functions which operate on raw pointers require
296    /// those pointers to be aligned, so calling those functions with the result
297    /// of `get_ptr` will result in undefined behavior if alignment is not
298    /// guaranteed using some out-of-band mechanism. In general, the only
299    /// functions which are safe to call with this pointer are those which are
300    /// explicitly documented as being sound to use with an unaligned pointer,
301    /// such as [`read_unaligned`].
302    ///
303    /// [`read_unaligned`]: core::ptr::read_unaligned
304    // FIXME(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
305    #[inline(always)]
306    pub fn get_mut_ptr(&mut self) -> *mut T {
307        ptr::addr_of_mut!(self.0)
308    }
309
310    /// Sets the inner `T`, dropping the previous value.
311    // FIXME(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
312    #[inline(always)]
313    pub fn set(&mut self, t: T) {
314        *self = Unalign::new(t);
315    }
316
317    /// Updates the inner `T` by calling a function on it.
318    ///
319    /// If [`T: Unaligned`], then `Unalign<T>` implements [`DerefMut`], and that
320    /// impl should be preferred over this method when performing updates, as it
321    /// will usually be faster and more ergonomic.
322    ///
323    /// For large types, this method may be expensive, as it requires copying
324    /// `2 * size_of::<T>()` bytes. \[1\]
325    ///
326    /// \[1\] Since the inner `T` may not be aligned, it would not be sound to
327    /// invoke `f` on it directly. Instead, `update` moves it into a
328    /// properly-aligned location in the local stack frame, calls `f` on it, and
329    /// then moves it back to its original location in `self`.
330    ///
331    /// [`T: Unaligned`]: Unaligned
332    #[inline]
333    pub fn update<O, F: FnOnce(&mut T) -> O>(&mut self, f: F) -> O {
334        if mem::align_of::<T>() == 1 {
335            // While we advise callers to use `DerefMut` when `T: Unaligned`,
336            // not all callers will be able to guarantee `T: Unaligned` in all
337            // cases. In particular, callers who are themselves providing an API
338            // which is generic over `T` may sometimes be called by *their*
339            // callers with `T` such that `align_of::<T>() == 1`, but cannot
340            // guarantee this in the general case. Thus, this optimization may
341            // sometimes be helpful.
342
343            // SAFETY: Since `T`'s alignment is 1, `self` satisfies its
344            // alignment by definition.
345            let t = unsafe { self.deref_mut_unchecked() };
346            return f(t);
347        }
348
349        // On drop, this moves `copy` out of itself and uses `ptr::write` to
350        // overwrite `slf`.
351        struct WriteBackOnDrop<T> {
352            copy: ManuallyDrop<T>,
353            slf: *mut Unalign<T>,
354        }
355
356        impl<T> Drop for WriteBackOnDrop<T> {
357            fn drop(&mut self) {
358                // SAFETY: We never use `copy` again as required by
359                // `ManuallyDrop::take`.
360                let copy = unsafe { ManuallyDrop::take(&mut self.copy) };
361                // SAFETY: `slf` is the raw pointer value of `self`. We know it
362                // is valid for writes and properly aligned because `self` is a
363                // mutable reference, which guarantees both of these properties.
364                unsafe { ptr::write(self.slf, Unalign::new(copy)) };
365            }
366        }
367
368        // SAFETY: We know that `self` is valid for reads, properly aligned, and
369        // points to an initialized `Unalign<T>` because it is a mutable
370        // reference, which guarantees all of these properties.
371        //
372        // Since `T: !Copy`, it would be unsound in the general case to allow
373        // both the original `Unalign<T>` and the copy to be used by safe code.
374        // We guarantee that the copy is used to overwrite the original in the
375        // `Drop::drop` impl of `WriteBackOnDrop`. So long as this `drop` is
376        // called before any other safe code executes, soundness is upheld.
377        // While this method can terminate in two ways (by returning normally or
378        // by unwinding due to a panic in `f`), in both cases, `write_back` is
379        // dropped - and its `drop` called - before any other safe code can
380        // execute.
381        let copy = unsafe { ptr::read(self) }.into_inner();
382        let mut write_back = WriteBackOnDrop { copy: ManuallyDrop::new(copy), slf: self };
383
384        let ret = f(&mut write_back.copy);
385
386        drop(write_back);
387        ret
388    }
389}
390
391impl<T: Copy> Unalign<T> {
392    /// Gets a copy of the inner `T`.
393    // FIXME(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
394    #[inline(always)]
395    pub fn get(&self) -> T {
396        let Unalign(val) = *self;
397        val
398    }
399}
400
401impl<T: Unaligned> Deref for Unalign<T> {
402    type Target = T;
403
404    #[inline(always)]
405    fn deref(&self) -> &T {
406        Ptr::from_ref(self).transmute().bikeshed_recall_aligned().as_ref()
407    }
408}
409
410impl<T: Unaligned> DerefMut for Unalign<T> {
411    #[inline(always)]
412    fn deref_mut(&mut self) -> &mut T {
413        Ptr::from_mut(self).transmute::<_, _, (_, (_, _))>().bikeshed_recall_aligned().as_mut()
414    }
415}
416
417impl<T: Unaligned + PartialOrd> PartialOrd<Unalign<T>> for Unalign<T> {
418    #[inline(always)]
419    fn partial_cmp(&self, other: &Unalign<T>) -> Option<Ordering> {
420        PartialOrd::partial_cmp(self.deref(), other.deref())
421    }
422}
423
424impl<T: Unaligned + Ord> Ord for Unalign<T> {
425    #[inline(always)]
426    fn cmp(&self, other: &Unalign<T>) -> Ordering {
427        Ord::cmp(self.deref(), other.deref())
428    }
429}
430
431impl<T: Unaligned + PartialEq> PartialEq<Unalign<T>> for Unalign<T> {
432    #[inline(always)]
433    fn eq(&self, other: &Unalign<T>) -> bool {
434        PartialEq::eq(self.deref(), other.deref())
435    }
436}
437
438impl<T: Unaligned + Eq> Eq for Unalign<T> {}
439
440impl<T: Unaligned + Hash> Hash for Unalign<T> {
441    #[inline(always)]
442    fn hash<H>(&self, state: &mut H)
443    where
444        H: Hasher,
445    {
446        self.deref().hash(state);
447    }
448}
449
450impl<T: Unaligned + Debug> Debug for Unalign<T> {
451    #[inline(always)]
452    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
453        Debug::fmt(self.deref(), f)
454    }
455}
456
457impl<T: Unaligned + Display> Display for Unalign<T> {
458    #[inline(always)]
459    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
460        Display::fmt(self.deref(), f)
461    }
462}
463
464/// A wrapper type to construct uninitialized instances of `T`.
465///
466/// `MaybeUninit` is identical to the [standard library
467/// `MaybeUninit`][core-maybe-uninit] type except that it supports unsized
468/// types.
469///
470/// # Layout
471///
472/// The same layout guarantees and caveats apply to `MaybeUninit<T>` as apply to
473/// the [standard library `MaybeUninit`][core-maybe-uninit] with one exception:
474/// for `T: !Sized`, there is no single value for `T`'s size. Instead, for such
475/// types, the following are guaranteed:
476/// - Every [valid size][valid-size] for `T` is a valid size for
477///   `MaybeUninit<T>` and vice versa
478/// - Given `t: *const T` and `m: *const MaybeUninit<T>` with identical fat
479///   pointer metadata, `t` and `m` address the same number of bytes (and
480///   likewise for `*mut`)
481///
482/// [core-maybe-uninit]: core::mem::MaybeUninit
483/// [valid-size]: crate::KnownLayout#what-is-a-valid-size
484#[repr(transparent)]
485#[doc(hidden)]
486pub struct MaybeUninit<T: ?Sized + KnownLayout>(
487    // SAFETY: `MaybeUninit<T>` has the same size as `T`, because (by invariant
488    // on `T::MaybeUninit`) `T::MaybeUninit` has `T::LAYOUT` identical to `T`,
489    // and because (invariant on `T::LAYOUT`) we can trust that `LAYOUT`
490    // accurately reflects the layout of `T`. By invariant on `T::MaybeUninit`,
491    // it admits uninitialized bytes in all positions. Because `MaybeUninit` is
492    // marked `repr(transparent)`, these properties additionally hold true for
493    // `Self`.
494    T::MaybeUninit,
495);
496
497#[doc(hidden)]
498impl<T: ?Sized + KnownLayout> MaybeUninit<T> {
499    /// Constructs a `MaybeUninit<T>` initialized with the given value.
500    #[inline(always)]
501    pub fn new(val: T) -> Self
502    where
503        T: Sized,
504        Self: Sized,
505    {
506        // SAFETY: It is valid to transmute `val` to `MaybeUninit<T>` because it
507        // is both valid to transmute `val` to `T::MaybeUninit`, and it is valid
508        // to transmute from `T::MaybeUninit` to `MaybeUninit<T>`.
509        //
510        // First, it is valid to transmute `val` to `T::MaybeUninit` because, by
511        // invariant on `T::MaybeUninit`:
512        // - For `T: Sized`, `T` and `T::MaybeUninit` have the same size.
513        // - All byte sequences of the correct size are valid values of
514        //   `T::MaybeUninit`.
515        //
516        // Second, it is additionally valid to transmute from `T::MaybeUninit`
517        // to `MaybeUninit<T>`, because `MaybeUninit<T>` is a
518        // `repr(transparent)` wrapper around `T::MaybeUninit`.
519        //
520        // These two transmutes are collapsed into one so we don't need to add a
521        // `T::MaybeUninit: Sized` bound to this function's `where` clause.
522        unsafe { crate::util::transmute_unchecked(val) }
523    }
524
525    /// Constructs an uninitialized `MaybeUninit<T>`.
526    #[must_use]
527    #[inline(always)]
528    pub fn uninit() -> Self
529    where
530        T: Sized,
531        Self: Sized,
532    {
533        let uninit = CoreMaybeUninit::<T>::uninit();
534        // SAFETY: It is valid to transmute from `CoreMaybeUninit<T>` to
535        // `MaybeUninit<T>` since they both admit uninitialized bytes in all
536        // positions, and they have the same size (i.e., that of `T`).
537        //
538        // `MaybeUninit<T>` has the same size as `T`, because (by invariant on
539        // `T::MaybeUninit`) `T::MaybeUninit` has `T::LAYOUT` identical to `T`,
540        // and because (invariant on `T::LAYOUT`) we can trust that `LAYOUT`
541        // accurately reflects the layout of `T`.
542        //
543        // `CoreMaybeUninit<T>` has the same size as `T` [1] and admits
544        // uninitialized bytes in all positions.
545        //
546        // [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
547        //
548        //   `MaybeUninit<T>` is guaranteed to have the same size, alignment,
549        //   and ABI as `T`
550        unsafe { crate::util::transmute_unchecked(uninit) }
551    }
552
553    /// Creates a `Box<MaybeUninit<T>>`.
554    ///
555    /// This function is useful for allocating large, uninit values on the heap
556    /// without ever creating a temporary instance of `Self` on the stack.
557    ///
558    /// # Errors
559    ///
560    /// Returns an error on allocation failure. Allocation failure is guaranteed
561    /// never to cause a panic or an abort.
562    #[cfg(feature = "alloc")]
563    #[inline]
564    pub fn new_boxed_uninit(meta: T::PointerMetadata) -> Result<Box<Self>, AllocError> {
565        // SAFETY: `alloc::alloc::alloc_zeroed` is a valid argument of
566        // `new_box`. The referent of the pointer returned by `alloc` (and,
567        // consequently, the `Box` derived from it) is a valid instance of
568        // `Self`, because `Self` is `MaybeUninit` and thus admits arbitrary
569        // (un)initialized bytes.
570        unsafe { crate::util::new_box(meta, alloc::alloc::alloc) }
571    }
572
573    /// Extracts the value from the `MaybeUninit<T>` container.
574    ///
575    /// # Safety
576    ///
577    /// The caller must ensure that `self` is in an bit-valid state. Depending
578    /// on subsequent use, it may also need to be in a library-valid state.
579    #[inline(always)]
580    pub unsafe fn assume_init(self) -> T
581    where
582        T: Sized,
583        Self: Sized,
584    {
585        // SAFETY: The caller guarantees that `self` is in an bit-valid state.
586        unsafe { crate::util::transmute_unchecked(self) }
587    }
588}
589
590impl<T: ?Sized + KnownLayout> fmt::Debug for MaybeUninit<T> {
591    #[inline]
592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593        f.pad(core::any::type_name::<Self>())
594    }
595}
596
597#[cfg(test)]
598mod tests {
599    use core::panic::AssertUnwindSafe;
600
601    use super::*;
602    use crate::util::testutil::*;
603
604    #[test]
605    fn test_unalign() {
606        // Test methods that don't depend on alignment.
607        let mut u = Unalign::new(AU64(123));
608        assert_eq!(u.get(), AU64(123));
609        assert_eq!(u.into_inner(), AU64(123));
610        assert_eq!(u.get_ptr(), <*const _>::cast::<AU64>(&u));
611        assert_eq!(u.get_mut_ptr(), <*mut _>::cast::<AU64>(&mut u));
612        u.set(AU64(321));
613        assert_eq!(u.get(), AU64(321));
614
615        // Test methods that depend on alignment (when alignment is satisfied).
616        let mut u: Align<_, AU64> = Align::new(Unalign::new(AU64(123)));
617        assert_eq!(u.t.try_deref().unwrap(), &AU64(123));
618        assert_eq!(u.t.try_deref_mut().unwrap(), &mut AU64(123));
619        // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
620        assert_eq!(unsafe { u.t.deref_unchecked() }, &AU64(123));
621        // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
622        assert_eq!(unsafe { u.t.deref_mut_unchecked() }, &mut AU64(123));
623        *u.t.try_deref_mut().unwrap() = AU64(321);
624        assert_eq!(u.t.get(), AU64(321));
625
626        // Test methods that depend on alignment (when alignment is not
627        // satisfied).
628        let mut u: ForceUnalign<_, AU64> = ForceUnalign::new(Unalign::new(AU64(123)));
629        assert!(matches!(u.t.try_deref(), Err(AlignmentError { .. })));
630        assert!(matches!(u.t.try_deref_mut(), Err(AlignmentError { .. })));
631
632        // Test methods that depend on `T: Unaligned`.
633        let mut u = Unalign::new(123u8);
634        assert_eq!(u.try_deref(), Ok(&123));
635        assert_eq!(u.try_deref_mut(), Ok(&mut 123));
636        assert_eq!(u.deref(), &123);
637        assert_eq!(u.deref_mut(), &mut 123);
638        *u = 21;
639        assert_eq!(u.get(), 21);
640
641        // Test that some `Unalign` functions and methods are `const`.
642        const _UNALIGN: Unalign<u64> = Unalign::new(0);
643        const _UNALIGN_PTR: *const u64 = _UNALIGN.get_ptr();
644        const _U64: u64 = _UNALIGN.into_inner();
645        // Make sure all code is considered "used".
646        //
647        // FIXME(https://github.com/rust-lang/rust/issues/104084): Remove this
648        // attribute.
649        #[allow(dead_code)]
650        const _: () = {
651            let x: Align<_, AU64> = Align::new(Unalign::new(AU64(123)));
652            // Make sure that `deref_unchecked` is `const`.
653            //
654            // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
655            let au64 = unsafe { x.t.deref_unchecked() };
656            match au64 {
657                AU64(123) => {}
658                _ => const_unreachable!(),
659            }
660        };
661    }
662
663    #[test]
664    fn test_unalign_update() {
665        let mut u = Unalign::new(AU64(123));
666        u.update(|a| a.0 += 1);
667        assert_eq!(u.get(), AU64(124));
668
669        // Test that, even if the callback panics, the original is still
670        // correctly overwritten. Use a `Box` so that Miri is more likely to
671        // catch any unsoundness (which would likely result in two `Box`es for
672        // the same heap object, which is the sort of thing that Miri would
673        // probably catch).
674        let mut u = Unalign::new(Box::new(AU64(123)));
675        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
676            u.update(|a| {
677                a.0 += 1;
678                panic!();
679            })
680        }));
681        assert!(res.is_err());
682        assert_eq!(u.into_inner(), Box::new(AU64(124)));
683
684        // Test the align_of::<T>() == 1 optimization.
685        let mut u = Unalign::new([0u8, 1]);
686        u.update(|a| a[0] += 1);
687        assert_eq!(u.get(), [1u8, 1]);
688    }
689
690    #[test]
691    fn test_unalign_copy_clone() {
692        // Test that `Copy` and `Clone` do not cause soundness issues. This test
693        // is mainly meant to exercise UB that would be caught by Miri.
694
695        // `u.t` is definitely not validly-aligned for `AU64`'s alignment of 8.
696        let u = ForceUnalign::<_, AU64>::new(Unalign::new(AU64(123)));
697        #[allow(clippy::clone_on_copy)]
698        let v = u.t.clone();
699        let w = u.t;
700        assert_eq!(u.t.get(), v.get());
701        assert_eq!(u.t.get(), w.get());
702        assert_eq!(v.get(), w.get());
703    }
704
705    #[test]
706    fn test_unalign_trait_impls() {
707        let zero = Unalign::new(0u8);
708        let one = Unalign::new(1u8);
709
710        assert!(zero < one);
711        assert_eq!(PartialOrd::partial_cmp(&zero, &one), Some(Ordering::Less));
712        assert_eq!(Ord::cmp(&zero, &one), Ordering::Less);
713
714        assert_ne!(zero, one);
715        assert_eq!(zero, zero);
716        assert!(!PartialEq::eq(&zero, &one));
717        assert!(PartialEq::eq(&zero, &zero));
718
719        fn hash<T: Hash>(t: &T) -> u64 {
720            let mut h = std::collections::hash_map::DefaultHasher::new();
721            t.hash(&mut h);
722            h.finish()
723        }
724
725        assert_eq!(hash(&zero), hash(&0u8));
726        assert_eq!(hash(&one), hash(&1u8));
727
728        assert_eq!(format!("{:?}", zero), format!("{:?}", 0u8));
729        assert_eq!(format!("{:?}", one), format!("{:?}", 1u8));
730        assert_eq!(format!("{}", zero), format!("{}", 0u8));
731        assert_eq!(format!("{}", one), format!("{}", 1u8));
732    }
733
734    #[test]
735    #[allow(clippy::as_conversions)]
736    fn test_maybe_uninit() {
737        // int
738        {
739            let input = 42;
740            let uninit = MaybeUninit::new(input);
741            // SAFETY: `uninit` is in an initialized state
742            let output = unsafe { uninit.assume_init() };
743            assert_eq!(input, output);
744        }
745
746        // thin ref
747        {
748            let input = 42;
749            let uninit = MaybeUninit::new(&input);
750            // SAFETY: `uninit` is in an initialized state
751            let output = unsafe { uninit.assume_init() };
752            assert_eq!(&input as *const _, output as *const _);
753            assert_eq!(input, *output);
754        }
755
756        // wide ref
757        {
758            let input = [1, 2, 3, 4];
759            let uninit = MaybeUninit::new(&input[..]);
760            // SAFETY: `uninit` is in an initialized state
761            let output = unsafe { uninit.assume_init() };
762            assert_eq!(&input[..] as *const _, output as *const _);
763            assert_eq!(input, *output);
764        }
765    }
766}