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::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
122safety_comment! {
123    /// SAFETY:
124    /// - `Unalign<T>` promises to have alignment 1, and so we don't require
125    ///   that `T: Unaligned`.
126    /// - `Unalign<T>` has the same bit validity as `T`, and so it is
127    ///   `FromZeros`, `FromBytes`, or `IntoBytes` exactly when `T` is as well.
128    /// - `Immutable`: `Unalign<T>` has the same fields as `T`, so it contains
129    ///   `UnsafeCell`s exactly when `T` does.
130    /// - `TryFromBytes`: `Unalign<T>` has the same the same bit validity as
131    ///   `T`, so `T::is_bit_valid` is a sound implementation of `is_bit_valid`.
132    ///   Furthermore:
133    ///   - Since `T` and `Unalign<T>` have the same layout, they have the same
134    ///     size (as required by `unsafe_impl!`).
135    ///   - Since `T` and `Unalign<T>` have the same fields, they have
136    ///     `UnsafeCell`s at the same byte ranges (as required by
137    ///     `unsafe_impl!`).
138    impl_or_verify!(T => Unaligned for Unalign<T>);
139    impl_or_verify!(T: Immutable => Immutable for Unalign<T>);
140    impl_or_verify!(
141        T: TryFromBytes => TryFromBytes for Unalign<T>;
142        |c: Maybe<T>| T::is_bit_valid(c)
143    );
144    impl_or_verify!(T: FromZeros => FromZeros for Unalign<T>);
145    impl_or_verify!(T: FromBytes => FromBytes for Unalign<T>);
146    impl_or_verify!(T: IntoBytes => IntoBytes for Unalign<T>);
147}
148
149// Note that `Unalign: Clone` only if `T: Copy`. Since the inner `T` may not be
150// aligned, there's no way to safely call `T::clone`, and so a `T: Clone` bound
151// is not sufficient to implement `Clone` for `Unalign`.
152impl<T: Copy> Clone for Unalign<T> {
153    #[inline(always)]
154    fn clone(&self) -> Unalign<T> {
155        *self
156    }
157}
158
159impl<T> Unalign<T> {
160    /// Constructs a new `Unalign`.
161    #[inline(always)]
162    pub const fn new(val: T) -> Unalign<T> {
163        Unalign(val)
164    }
165
166    /// Consumes `self`, returning the inner `T`.
167    #[inline(always)]
168    pub const fn into_inner(self) -> T {
169        // Use this instead of `mem::transmute` since the latter can't tell
170        // that `Unalign<T>` and `T` have the same size.
171        #[repr(C)]
172        union Transmute<T> {
173            u: ManuallyDrop<Unalign<T>>,
174            t: ManuallyDrop<T>,
175        }
176
177        // SAFETY: Since `Unalign` is `#[repr(C, packed)]`, it has the same
178        // layout as `T`. `ManuallyDrop<U>` is guaranteed to have the same
179        // layout as `U`, and so `ManuallyDrop<Unalign<T>>` has the same layout
180        // as `ManuallyDrop<T>`. Since `Transmute<T>` is `#[repr(C)]`, its `t`
181        // and `u` fields both start at the same offset (namely, 0) within the
182        // union.
183        //
184        // We do this instead of just destructuring in order to prevent
185        // `Unalign`'s `Drop::drop` from being run, since dropping is not
186        // supported in `const fn`s.
187        //
188        // TODO(https://github.com/rust-lang/rust/issues/73255): Destructure
189        // instead of using unsafe.
190        unsafe { ManuallyDrop::into_inner(Transmute { u: ManuallyDrop::new(self) }.t) }
191    }
192
193    /// Attempts to return a reference to the wrapped `T`, failing if `self` is
194    /// not properly aligned.
195    ///
196    /// If `self` does not satisfy `align_of::<T>()`, then `try_deref` returns
197    /// `Err`.
198    ///
199    /// If `T: Unaligned`, then `Unalign<T>` implements [`Deref`], and callers
200    /// may prefer [`Deref::deref`], which is infallible.
201    #[inline(always)]
202    pub fn try_deref(&self) -> Result<&T, AlignmentError<&Self, T>> {
203        let inner = Ptr::from_ref(self).transparent_wrapper_into_inner();
204        match inner.bikeshed_try_into_aligned() {
205            Ok(aligned) => Ok(aligned.as_ref()),
206            Err(err) => Err(err.map_src(|src| src.into_unalign().as_ref())),
207        }
208    }
209
210    /// Attempts to return a mutable reference to the wrapped `T`, failing if
211    /// `self` is not properly aligned.
212    ///
213    /// If `self` does not satisfy `align_of::<T>()`, then `try_deref` returns
214    /// `Err`.
215    ///
216    /// If `T: Unaligned`, then `Unalign<T>` implements [`DerefMut`], and
217    /// callers may prefer [`DerefMut::deref_mut`], which is infallible.
218    #[inline(always)]
219    pub fn try_deref_mut(&mut self) -> Result<&mut T, AlignmentError<&mut Self, T>> {
220        let inner = Ptr::from_mut(self).transparent_wrapper_into_inner();
221        match inner.bikeshed_try_into_aligned() {
222            Ok(aligned) => Ok(aligned.as_mut()),
223            Err(err) => Err(err.map_src(|src| src.into_unalign().as_mut())),
224        }
225    }
226
227    /// Returns a reference to the wrapped `T` without checking alignment.
228    ///
229    /// If `T: Unaligned`, then `Unalign<T>` implements[ `Deref`], and callers
230    /// may prefer [`Deref::deref`], which is safe.
231    ///
232    /// # Safety
233    ///
234    /// The caller must guarantee that `self` satisfies `align_of::<T>()`.
235    #[inline(always)]
236    pub const unsafe fn deref_unchecked(&self) -> &T {
237        // SAFETY: `Unalign<T>` is `repr(transparent)`, so there is a valid `T`
238        // at the same memory location as `self`. It has no alignment guarantee,
239        // but the caller has promised that `self` is properly aligned, so we
240        // know that it is sound to create a reference to `T` at this memory
241        // location.
242        //
243        // We use `mem::transmute` instead of `&*self.get_ptr()` because
244        // dereferencing pointers is not stable in `const` on our current MSRV
245        // (1.56 as of this writing).
246        unsafe { mem::transmute(self) }
247    }
248
249    /// Returns a mutable reference to the wrapped `T` without checking
250    /// alignment.
251    ///
252    /// If `T: Unaligned`, then `Unalign<T>` implements[ `DerefMut`], and
253    /// callers may prefer [`DerefMut::deref_mut`], which is safe.
254    ///
255    /// # Safety
256    ///
257    /// The caller must guarantee that `self` satisfies `align_of::<T>()`.
258    #[inline(always)]
259    pub unsafe fn deref_mut_unchecked(&mut self) -> &mut T {
260        // SAFETY: `self.get_mut_ptr()` returns a raw pointer to a valid `T` at
261        // the same memory location as `self`. It has no alignment guarantee,
262        // but the caller has promised that `self` is properly aligned, so we
263        // know that the pointer itself is aligned, and thus that it is sound to
264        // create a reference to a `T` at this memory location.
265        unsafe { &mut *self.get_mut_ptr() }
266    }
267
268    /// Gets an unaligned raw pointer to the inner `T`.
269    ///
270    /// # Safety
271    ///
272    /// The returned raw pointer is not necessarily aligned to
273    /// `align_of::<T>()`. Most functions which operate on raw pointers require
274    /// those pointers to be aligned, so calling those functions with the result
275    /// of `get_ptr` will result in undefined behavior if alignment is not
276    /// guaranteed using some out-of-band mechanism. In general, the only
277    /// functions which are safe to call with this pointer are those which are
278    /// explicitly documented as being sound to use with an unaligned pointer,
279    /// such as [`read_unaligned`].
280    ///
281    /// Even if the caller is permitted to mutate `self` (e.g. they have
282    /// ownership or a mutable borrow), it is not guaranteed to be sound to
283    /// write through the returned pointer. If writing is required, prefer
284    /// [`get_mut_ptr`] instead.
285    ///
286    /// [`read_unaligned`]: core::ptr::read_unaligned
287    /// [`get_mut_ptr`]: Unalign::get_mut_ptr
288    #[inline(always)]
289    pub const fn get_ptr(&self) -> *const T {
290        ptr::addr_of!(self.0)
291    }
292
293    /// Gets an unaligned mutable raw pointer to the inner `T`.
294    ///
295    /// # Safety
296    ///
297    /// The returned raw pointer is not necessarily aligned to
298    /// `align_of::<T>()`. Most functions which operate on raw pointers require
299    /// those pointers to be aligned, so calling those functions with the result
300    /// of `get_ptr` will result in undefined behavior if alignment is not
301    /// guaranteed using some out-of-band mechanism. In general, the only
302    /// functions which are safe to call with this pointer are those which are
303    /// explicitly documented as being sound to use with an unaligned pointer,
304    /// such as [`read_unaligned`].
305    ///
306    /// [`read_unaligned`]: core::ptr::read_unaligned
307    // TODO(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
308    #[inline(always)]
309    pub fn get_mut_ptr(&mut self) -> *mut T {
310        ptr::addr_of_mut!(self.0)
311    }
312
313    /// Sets the inner `T`, dropping the previous value.
314    // TODO(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
315    #[inline(always)]
316    pub fn set(&mut self, t: T) {
317        *self = Unalign::new(t);
318    }
319
320    /// Updates the inner `T` by calling a function on it.
321    ///
322    /// If [`T: Unaligned`], then `Unalign<T>` implements [`DerefMut`], and that
323    /// impl should be preferred over this method when performing updates, as it
324    /// will usually be faster and more ergonomic.
325    ///
326    /// For large types, this method may be expensive, as it requires copying
327    /// `2 * size_of::<T>()` bytes. \[1\]
328    ///
329    /// \[1\] Since the inner `T` may not be aligned, it would not be sound to
330    /// invoke `f` on it directly. Instead, `update` moves it into a
331    /// properly-aligned location in the local stack frame, calls `f` on it, and
332    /// then moves it back to its original location in `self`.
333    ///
334    /// [`T: Unaligned`]: Unaligned
335    #[inline]
336    pub fn update<O, F: FnOnce(&mut T) -> O>(&mut self, f: F) -> O {
337        if mem::align_of::<T>() == 1 {
338            // While we advise callers to use `DerefMut` when `T: Unaligned`,
339            // not all callers will be able to guarantee `T: Unaligned` in all
340            // cases. In particular, callers who are themselves providing an API
341            // which is generic over `T` may sometimes be called by *their*
342            // callers with `T` such that `align_of::<T>() == 1`, but cannot
343            // guarantee this in the general case. Thus, this optimization may
344            // sometimes be helpful.
345
346            // SAFETY: Since `T`'s alignment is 1, `self` satisfies its
347            // alignment by definition.
348            let t = unsafe { self.deref_mut_unchecked() };
349            return f(t);
350        }
351
352        // On drop, this moves `copy` out of itself and uses `ptr::write` to
353        // overwrite `slf`.
354        struct WriteBackOnDrop<T> {
355            copy: ManuallyDrop<T>,
356            slf: *mut Unalign<T>,
357        }
358
359        impl<T> Drop for WriteBackOnDrop<T> {
360            fn drop(&mut self) {
361                // SAFETY: We never use `copy` again as required by
362                // `ManuallyDrop::take`.
363                let copy = unsafe { ManuallyDrop::take(&mut self.copy) };
364                // SAFETY: `slf` is the raw pointer value of `self`. We know it
365                // is valid for writes and properly aligned because `self` is a
366                // mutable reference, which guarantees both of these properties.
367                unsafe { ptr::write(self.slf, Unalign::new(copy)) };
368            }
369        }
370
371        // SAFETY: We know that `self` is valid for reads, properly aligned, and
372        // points to an initialized `Unalign<T>` because it is a mutable
373        // reference, which guarantees all of these properties.
374        //
375        // Since `T: !Copy`, it would be unsound in the general case to allow
376        // both the original `Unalign<T>` and the copy to be used by safe code.
377        // We guarantee that the copy is used to overwrite the original in the
378        // `Drop::drop` impl of `WriteBackOnDrop`. So long as this `drop` is
379        // called before any other safe code executes, soundness is upheld.
380        // While this method can terminate in two ways (by returning normally or
381        // by unwinding due to a panic in `f`), in both cases, `write_back` is
382        // dropped - and its `drop` called - before any other safe code can
383        // execute.
384        let copy = unsafe { ptr::read(self) }.into_inner();
385        let mut write_back = WriteBackOnDrop { copy: ManuallyDrop::new(copy), slf: self };
386
387        let ret = f(&mut write_back.copy);
388
389        drop(write_back);
390        ret
391    }
392}
393
394impl<T: Copy> Unalign<T> {
395    /// Gets a copy of the inner `T`.
396    // TODO(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
397    #[inline(always)]
398    pub fn get(&self) -> T {
399        let Unalign(val) = *self;
400        val
401    }
402}
403
404impl<T: Unaligned> Deref for Unalign<T> {
405    type Target = T;
406
407    #[inline(always)]
408    fn deref(&self) -> &T {
409        Ptr::from_ref(self).transparent_wrapper_into_inner().bikeshed_recall_aligned().as_ref()
410    }
411}
412
413impl<T: Unaligned> DerefMut for Unalign<T> {
414    #[inline(always)]
415    fn deref_mut(&mut self) -> &mut T {
416        Ptr::from_mut(self).transparent_wrapper_into_inner().bikeshed_recall_aligned().as_mut()
417    }
418}
419
420impl<T: Unaligned + PartialOrd> PartialOrd<Unalign<T>> for Unalign<T> {
421    #[inline(always)]
422    fn partial_cmp(&self, other: &Unalign<T>) -> Option<Ordering> {
423        PartialOrd::partial_cmp(self.deref(), other.deref())
424    }
425}
426
427impl<T: Unaligned + Ord> Ord for Unalign<T> {
428    #[inline(always)]
429    fn cmp(&self, other: &Unalign<T>) -> Ordering {
430        Ord::cmp(self.deref(), other.deref())
431    }
432}
433
434impl<T: Unaligned + PartialEq> PartialEq<Unalign<T>> for Unalign<T> {
435    #[inline(always)]
436    fn eq(&self, other: &Unalign<T>) -> bool {
437        PartialEq::eq(self.deref(), other.deref())
438    }
439}
440
441impl<T: Unaligned + Eq> Eq for Unalign<T> {}
442
443impl<T: Unaligned + Hash> Hash for Unalign<T> {
444    #[inline(always)]
445    fn hash<H>(&self, state: &mut H)
446    where
447        H: Hasher,
448    {
449        self.deref().hash(state);
450    }
451}
452
453impl<T: Unaligned + Debug> Debug for Unalign<T> {
454    #[inline(always)]
455    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
456        Debug::fmt(self.deref(), f)
457    }
458}
459
460impl<T: Unaligned + Display> Display for Unalign<T> {
461    #[inline(always)]
462    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
463        Display::fmt(self.deref(), f)
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    use core::panic::AssertUnwindSafe;
470
471    use super::*;
472    use crate::util::testutil::*;
473
474    #[test]
475    fn test_unalign() {
476        // Test methods that don't depend on alignment.
477        let mut u = Unalign::new(AU64(123));
478        assert_eq!(u.get(), AU64(123));
479        assert_eq!(u.into_inner(), AU64(123));
480        assert_eq!(u.get_ptr(), <*const _>::cast::<AU64>(&u));
481        assert_eq!(u.get_mut_ptr(), <*mut _>::cast::<AU64>(&mut u));
482        u.set(AU64(321));
483        assert_eq!(u.get(), AU64(321));
484
485        // Test methods that depend on alignment (when alignment is satisfied).
486        let mut u: Align<_, AU64> = Align::new(Unalign::new(AU64(123)));
487        assert_eq!(u.t.try_deref().unwrap(), &AU64(123));
488        assert_eq!(u.t.try_deref_mut().unwrap(), &mut AU64(123));
489        // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
490        assert_eq!(unsafe { u.t.deref_unchecked() }, &AU64(123));
491        // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
492        assert_eq!(unsafe { u.t.deref_mut_unchecked() }, &mut AU64(123));
493        *u.t.try_deref_mut().unwrap() = AU64(321);
494        assert_eq!(u.t.get(), AU64(321));
495
496        // Test methods that depend on alignment (when alignment is not
497        // satisfied).
498        let mut u: ForceUnalign<_, AU64> = ForceUnalign::new(Unalign::new(AU64(123)));
499        assert!(matches!(u.t.try_deref(), Err(AlignmentError { .. })));
500        assert!(matches!(u.t.try_deref_mut(), Err(AlignmentError { .. })));
501
502        // Test methods that depend on `T: Unaligned`.
503        let mut u = Unalign::new(123u8);
504        assert_eq!(u.try_deref(), Ok(&123));
505        assert_eq!(u.try_deref_mut(), Ok(&mut 123));
506        assert_eq!(u.deref(), &123);
507        assert_eq!(u.deref_mut(), &mut 123);
508        *u = 21;
509        assert_eq!(u.get(), 21);
510
511        // Test that some `Unalign` functions and methods are `const`.
512        const _UNALIGN: Unalign<u64> = Unalign::new(0);
513        const _UNALIGN_PTR: *const u64 = _UNALIGN.get_ptr();
514        const _U64: u64 = _UNALIGN.into_inner();
515        // Make sure all code is considered "used".
516        //
517        // TODO(https://github.com/rust-lang/rust/issues/104084): Remove this
518        // attribute.
519        #[allow(dead_code)]
520        const _: () = {
521            let x: Align<_, AU64> = Align::new(Unalign::new(AU64(123)));
522            // Make sure that `deref_unchecked` is `const`.
523            //
524            // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
525            let au64 = unsafe { x.t.deref_unchecked() };
526            match au64 {
527                AU64(123) => {}
528                _ => const_unreachable!(),
529            }
530        };
531    }
532
533    #[test]
534    fn test_unalign_update() {
535        let mut u = Unalign::new(AU64(123));
536        u.update(|a| a.0 += 1);
537        assert_eq!(u.get(), AU64(124));
538
539        // Test that, even if the callback panics, the original is still
540        // correctly overwritten. Use a `Box` so that Miri is more likely to
541        // catch any unsoundness (which would likely result in two `Box`es for
542        // the same heap object, which is the sort of thing that Miri would
543        // probably catch).
544        let mut u = Unalign::new(Box::new(AU64(123)));
545        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
546            u.update(|a| {
547                a.0 += 1;
548                panic!();
549            })
550        }));
551        assert!(res.is_err());
552        assert_eq!(u.into_inner(), Box::new(AU64(124)));
553
554        // Test the align_of::<T>() == 1 optimization.
555        let mut u = Unalign::new([0u8, 1]);
556        u.update(|a| a[0] += 1);
557        assert_eq!(u.get(), [1u8, 1]);
558    }
559
560    #[test]
561    fn test_copy_clone() {
562        // Test that `Copy` and `Clone` do not cause soundness issues. This test
563        // is mainly meant to exercise UB that would be caught by Miri.
564
565        // `u.t` is definitely not validly-aligned for `AU64`'s alignment of 8.
566        let u = ForceUnalign::<_, AU64>::new(Unalign::new(AU64(123)));
567        #[allow(clippy::clone_on_copy)]
568        let v = u.t.clone();
569        let w = u.t;
570        assert_eq!(u.t.get(), v.get());
571        assert_eq!(u.t.get(), w.get());
572        assert_eq!(v.get(), w.get());
573    }
574
575    #[test]
576    fn test_trait_impls() {
577        let zero = Unalign::new(0u8);
578        let one = Unalign::new(1u8);
579
580        assert!(zero < one);
581        assert_eq!(PartialOrd::partial_cmp(&zero, &one), Some(Ordering::Less));
582        assert_eq!(Ord::cmp(&zero, &one), Ordering::Less);
583
584        assert_ne!(zero, one);
585        assert_eq!(zero, zero);
586        assert!(!PartialEq::eq(&zero, &one));
587        assert!(PartialEq::eq(&zero, &zero));
588
589        fn hash<T: Hash>(t: &T) -> u64 {
590            let mut h = std::collections::hash_map::DefaultHasher::new();
591            t.hash(&mut h);
592            h.finish()
593        }
594
595        assert_eq!(hash(&zero), hash(&0u8));
596        assert_eq!(hash(&one), hash(&1u8));
597
598        assert_eq!(format!("{:?}", zero), format!("{:?}", 0u8));
599        assert_eq!(format!("{:?}", one), format!("{:?}", 1u8));
600        assert_eq!(format!("{}", zero), format!("{}", 0u8));
601        assert_eq!(format!("{}", one), format!("{}", 1u8));
602    }
603}