zerocopy/wrappers.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
11use core::{borrow::Borrow, fmt, hash::Hash};
12
13use super::*;
14use crate::pointer::{invariant::Safe, SizeEq, TransmuteFrom};
15
16/// A type with no alignment requirement.
17///
18/// An `Unalign` wraps a `T`, removing any alignment requirement. `Unalign<T>`
19/// has the same size and bit validity as `T`, but not necessarily the same
20/// alignment [or ABI]. This is useful if a type with an alignment requirement
21/// needs to be read from a chunk of memory which provides no alignment
22/// guarantees.
23///
24/// Since `Unalign` has no alignment requirement, the inner `T` may not be
25/// properly aligned in memory. There are five ways to access the inner `T`:
26/// - by value, using [`get`] or [`into_inner`]
27/// - by reference inside of a callback, using [`update`]
28/// - fallibly by reference, using [`try_deref`] or [`try_deref_mut`]; these can
29/// fail if the `Unalign` does not satisfy `T`'s alignment requirement at
30/// runtime
31/// - unsafely by reference, using [`deref_unchecked`] or
32/// [`deref_mut_unchecked`]; it is the caller's responsibility to ensure that
33/// the `Unalign` satisfies `T`'s alignment requirement
34/// - (where `T: Unaligned`) infallibly by reference, using [`Deref::deref`] or
35/// [`DerefMut::deref_mut`]
36///
37/// [or ABI]: https://github.com/google/zerocopy/issues/164
38/// [`get`]: Unalign::get
39/// [`into_inner`]: Unalign::into_inner
40/// [`update`]: Unalign::update
41/// [`try_deref`]: Unalign::try_deref
42/// [`try_deref_mut`]: Unalign::try_deref_mut
43/// [`deref_unchecked`]: Unalign::deref_unchecked
44/// [`deref_mut_unchecked`]: Unalign::deref_mut_unchecked
45///
46/// # Example
47///
48/// In this example, we need `EthernetFrame` to have no alignment requirement -
49/// and thus implement [`Unaligned`]. `EtherType` is `#[repr(u16)]` and so
50/// cannot implement `Unaligned`. We use `Unalign` to relax `EtherType`'s
51/// alignment requirement so that `EthernetFrame` has no alignment requirement
52/// and can implement `Unaligned`.
53///
54/// ```rust
55/// use zerocopy::*;
56/// # use zerocopy_derive::*;
57/// # #[derive(FromBytes, KnownLayout, Immutable, Unaligned)] #[repr(C)] struct Mac([u8; 6]);
58///
59/// # #[derive(PartialEq, Copy, Clone, Debug)]
60/// #[derive(TryFromBytes, KnownLayout, Immutable)]
61/// #[repr(u16)]
62/// enum EtherType {
63/// Ipv4 = 0x0800u16.to_be(),
64/// Arp = 0x0806u16.to_be(),
65/// Ipv6 = 0x86DDu16.to_be(),
66/// # /*
67/// ...
68/// # */
69/// }
70///
71/// #[derive(TryFromBytes, KnownLayout, Immutable, Unaligned)]
72/// #[repr(C)]
73/// struct EthernetFrame {
74/// src: Mac,
75/// dst: Mac,
76/// ethertype: Unalign<EtherType>,
77/// payload: [u8],
78/// }
79///
80/// let bytes = &[
81/// # 0, 1, 2, 3, 4, 5,
82/// # 6, 7, 8, 9, 10, 11,
83/// # /*
84/// ...
85/// # */
86/// 0x86, 0xDD, // EtherType
87/// 0xDE, 0xAD, 0xBE, 0xEF // Payload
88/// ][..];
89///
90/// // PANICS: Guaranteed not to panic because `bytes` is of the right
91/// // length, has the right contents, and `EthernetFrame` has no
92/// // alignment requirement.
93/// let packet = EthernetFrame::try_ref_from_bytes(&bytes).unwrap();
94///
95/// assert_eq!(packet.ethertype.get(), EtherType::Ipv6);
96/// assert_eq!(packet.payload, [0xDE, 0xAD, 0xBE, 0xEF]);
97/// ```
98///
99/// # Safety
100///
101/// `Unalign<T>` is guaranteed to have the same size and bit validity as `T`,
102/// and to have [`UnsafeCell`]s covering the same byte ranges as `T`.
103/// `Unalign<T>` is guaranteed to have alignment 1.
104// NOTE: This type is sound to use with types that need to be dropped. The
105// reason is that the compiler-generated drop code automatically moves all
106// values to aligned memory slots before dropping them in-place. This is not
107// well-documented, but it's hinted at in places like [1] and [2]. However, this
108// also means that `T` must be `Sized`; unless something changes, we can never
109// support unsized `T`. [3]
110//
111// [1] https://github.com/rust-lang/rust/issues/54148#issuecomment-420529646
112// [2] https://github.com/google/zerocopy/pull/126#discussion_r1018512323
113// [3] https://github.com/google/zerocopy/issues/209
114#[allow(missing_debug_implementations)]
115#[derive(Default, Copy)]
116#[cfg_attr(any(feature = "derive", test), derive(Immutable, FromBytes, IntoBytes, Unaligned))]
117#[repr(C, packed)]
118pub struct Unalign<T>(T);
119
120// We do not use `derive(KnownLayout)` on `Unalign`, because the derive is not
121// smart enough to realize that `Unalign<T>` is always sized and thus emits a
122// `KnownLayout` impl bounded on `T: KnownLayout.` This is overly restrictive.
123impl_known_layout!(T => Unalign<T>);
124
125// FIXME(https://github.com/rust-lang/rust-clippy/issues/16087): Move these
126// attributes below the comment once this Clippy bug is fixed.
127#[cfg_attr(
128 all(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS, any(feature = "derive", test)),
129 expect(unused_unsafe)
130)]
131#[cfg_attr(
132 all(
133 not(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS),
134 any(feature = "derive", test)
135 ),
136 allow(unused_unsafe)
137)]
138// SAFETY:
139// - `Unalign<T>` promises to have alignment 1, and so we don't require that `T:
140// Unaligned`.
141// - `Unalign<T>` has the same bit validity as `T`, and so it is `FromZeros`,
142// `FromBytes`, or `IntoBytes` exactly when `T` is as well.
143// - `Immutable`: `Unalign<T>` has the same fields as `T`, so it permits interior
144// mutation exactly when `T` does.
145// - `TryFromBytes`: `Unalign<T>` has the same the same bit validity as `T`, so
146// `T::is_safe` is a sound implementation of `is_safe`.
147//
148#[allow(clippy::multiple_unsafe_ops_per_block)]
149const _: () = unsafe {
150 impl_or_verify!(T => Unaligned for Unalign<T>);
151 impl_or_verify!(T: Immutable => Immutable for Unalign<T>);
152 impl_or_verify!(
153 T: TryFromBytes => TryFromBytes for Unalign<T>;
154 |c| T::is_safe(c.transmute::<_, _, BecauseImmutable>())
155 );
156 impl_or_verify!(T: FromZeros => FromZeros for Unalign<T>);
157 impl_or_verify!(T: FromBytes => FromBytes for Unalign<T>);
158 impl_or_verify!(T: IntoBytes => IntoBytes for Unalign<T>);
159};
160
161// Note that `Unalign: Clone` only if `T: Copy`. Since the inner `T` may not be
162// aligned, there's no way to safely call `T::clone`, and so a `T: Clone` bound
163// is not sufficient to implement `Clone` for `Unalign`.
164impl<T: Copy> Clone for Unalign<T> {
165 #[inline(always)]
166 fn clone(&self) -> Unalign<T> {
167 *self
168 }
169}
170
171impl<T> Unalign<T> {
172 /// Constructs a new `Unalign`.
173 #[inline(always)]
174 pub const fn new(val: T) -> Unalign<T> {
175 Unalign(val)
176 }
177
178 /// Consumes `self`, returning the inner `T`.
179 #[inline(always)]
180 pub const fn into_inner(self) -> T {
181 // SAFETY: Since `Unalign` is `#[repr(C, packed)]`, it has the same size
182 // and bit validity as `T`.
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 // FIXME(https://github.com/rust-lang/rust/issues/73255): Destructure
189 // instead of using unsafe.
190 unsafe { crate::util::transmute_unchecked(self) }
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).transmute();
204 match inner.try_into_aligned() {
205 Ok(aligned) => Ok(aligned.as_ref()),
206 Err(err) => Err(err.map_src(
207 #[inline(always)]
208 |src| src.into_unalign().as_ref(),
209 )),
210 }
211 }
212
213 /// Attempts to return a mutable reference to the wrapped `T`, failing if
214 /// `self` is not properly aligned.
215 ///
216 /// If `self` does not satisfy `align_of::<T>()`, then `try_deref` returns
217 /// `Err`.
218 ///
219 /// If `T: Unaligned`, then `Unalign<T>` implements [`DerefMut`], and
220 /// callers may prefer [`DerefMut::deref_mut`], which is infallible.
221 #[inline(always)]
222 pub fn try_deref_mut(&mut self) -> Result<&mut T, AlignmentError<&mut Self, T>> {
223 let inner = Ptr::from_mut(self).transmute::<_, _, (_, (_, _))>();
224 match inner.try_into_aligned() {
225 Ok(aligned) => Ok(aligned.as_mut()),
226 Err(err) => Err(err.map_src(|src| src.into_unalign().as_mut())),
227 }
228 }
229
230 /// Returns a reference to the wrapped `T` without checking alignment.
231 ///
232 /// If `T: Unaligned`, then `Unalign<T>` implements[ `Deref`], and callers
233 /// may prefer [`Deref::deref`], which is safe.
234 ///
235 /// # Safety
236 ///
237 /// The caller must guarantee that `self` satisfies `align_of::<T>()`.
238 #[inline(always)]
239 pub const unsafe fn deref_unchecked(&self) -> &T {
240 // SAFETY: `Unalign<T>` is `repr(transparent)`, so there is a valid `T`
241 // at the same memory location as `self`. It has no alignment guarantee,
242 // but the caller has promised that `self` is properly aligned, so we
243 // know that it is sound to create a reference to `T` at this memory
244 // location.
245 //
246 // We use `mem::transmute` instead of `&*self.get_ptr()` because
247 // dereferencing pointers is not stable in `const` on our current MSRV
248 // (1.56 as of this writing).
249 unsafe { mem::transmute(self) }
250 }
251
252 /// Returns a mutable reference to the wrapped `T` without checking
253 /// alignment.
254 ///
255 /// If `T: Unaligned`, then `Unalign<T>` implements[ `DerefMut`], and
256 /// callers may prefer [`DerefMut::deref_mut`], which is safe.
257 ///
258 /// # Safety
259 ///
260 /// The caller must guarantee that `self` satisfies `align_of::<T>()`.
261 #[inline(always)]
262 pub unsafe fn deref_mut_unchecked(&mut self) -> &mut T {
263 // SAFETY: `self.get_mut_ptr()` returns a raw pointer to a valid `T` at
264 // the same memory location as `self`. It has no alignment guarantee,
265 // but the caller has promised that `self` is properly aligned, so we
266 // know that the pointer itself is aligned, and thus that it is sound to
267 // create a reference to a `T` at this memory location.
268 unsafe { &mut *self.get_mut_ptr() }
269 }
270
271 /// Gets an unaligned raw pointer to the inner `T`.
272 ///
273 /// # Safety
274 ///
275 /// The returned raw pointer is not necessarily aligned to
276 /// `align_of::<T>()`. Most functions which operate on raw pointers require
277 /// those pointers to be aligned, so calling those functions with the result
278 /// of `get_ptr` will result in undefined behavior if alignment is not
279 /// guaranteed using some out-of-band mechanism. In general, the only
280 /// functions which are safe to call with this pointer are those which are
281 /// explicitly documented as being sound to use with an unaligned pointer,
282 /// such as [`read_unaligned`].
283 ///
284 /// Even if the caller is permitted to mutate `self` (e.g. they have
285 /// ownership or a mutable borrow), it is not guaranteed to be sound to
286 /// write through the returned pointer. If writing is required, prefer
287 /// [`get_mut_ptr`] instead.
288 ///
289 /// [`read_unaligned`]: core::ptr::read_unaligned
290 /// [`get_mut_ptr`]: Unalign::get_mut_ptr
291 #[inline(always)]
292 pub const fn get_ptr(&self) -> *const T {
293 ptr::addr_of!(self.0)
294 }
295
296 /// Gets an unaligned mutable raw pointer to the inner `T`.
297 ///
298 /// # Safety
299 ///
300 /// The returned raw pointer is not necessarily aligned to
301 /// `align_of::<T>()`. Most functions which operate on raw pointers require
302 /// those pointers to be aligned, so calling those functions with the result
303 /// of `get_ptr` will result in undefined behavior if alignment is not
304 /// guaranteed using some out-of-band mechanism. In general, the only
305 /// functions which are safe to call with this pointer are those which are
306 /// explicitly documented as being sound to use with an unaligned pointer,
307 /// such as [`read_unaligned`].
308 ///
309 /// [`read_unaligned`]: core::ptr::read_unaligned
310 // FIXME(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
311 #[inline(always)]
312 pub fn get_mut_ptr(&mut self) -> *mut T {
313 ptr::addr_of_mut!(self.0)
314 }
315
316 /// Sets the inner `T`, dropping the previous value.
317 // FIXME(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
318 #[inline(always)]
319 pub fn set(&mut self, t: T) {
320 *self = Unalign::new(t);
321 }
322
323 /// Updates the inner `T` by calling a function on it.
324 ///
325 /// If [`T: Unaligned`], then `Unalign<T>` implements [`DerefMut`], and that
326 /// impl should be preferred over this method when performing updates, as it
327 /// will usually be faster and more ergonomic.
328 ///
329 /// For large types, this method may be expensive, as it requires copying
330 /// `2 * size_of::<T>()` bytes. \[1\]
331 ///
332 /// \[1\] Since the inner `T` may not be aligned, it would not be sound to
333 /// invoke `f` on it directly. Instead, `update` moves it into a
334 /// properly-aligned location in the local stack frame, calls `f` on it, and
335 /// then moves it back to its original location in `self`.
336 ///
337 /// [`T: Unaligned`]: Unaligned
338 #[inline]
339 pub fn update<O, F: FnOnce(&mut T) -> O>(&mut self, f: F) -> O {
340 if mem::align_of::<T>() == 1 {
341 // While we advise callers to use `DerefMut` when `T: Unaligned`,
342 // not all callers will be able to guarantee `T: Unaligned` in all
343 // cases. In particular, callers who are themselves providing an API
344 // which is generic over `T` may sometimes be called by *their*
345 // callers with `T` such that `align_of::<T>() == 1`, but cannot
346 // guarantee this in the general case. Thus, this optimization may
347 // sometimes be helpful.
348
349 // SAFETY: Since `T`'s alignment is 1, `self` satisfies its
350 // alignment by definition.
351 let t = unsafe { self.deref_mut_unchecked() };
352 return f(t);
353 }
354
355 // On drop, this moves `copy` out of itself and uses `ptr::write` to
356 // overwrite `slf`.
357 struct WriteBackOnDrop<T> {
358 copy: ManuallyDrop<T>,
359 slf: *mut Unalign<T>,
360 }
361
362 impl<T> Drop for WriteBackOnDrop<T> {
363 fn drop(&mut self) {
364 // SAFETY: We never use `copy` again as required by
365 // `ManuallyDrop::take`.
366 let copy = unsafe { ManuallyDrop::take(&mut self.copy) };
367 // SAFETY: `slf` is the raw pointer value of `self`. We know it
368 // is valid for writes and properly aligned because `self` is a
369 // mutable reference, which guarantees both of these properties.
370 unsafe { ptr::write(self.slf, Unalign::new(copy)) };
371 }
372 }
373
374 // SAFETY: We know that `self` is valid for reads, properly aligned, and
375 // points to an initialized `Unalign<T>` because it is a mutable
376 // reference, which guarantees all of these properties.
377 //
378 // Since `T: !Copy`, it would be unsound in the general case to allow
379 // both the original `Unalign<T>` and the copy to be used by safe code.
380 // We guarantee that the copy is used to overwrite the original in the
381 // `Drop::drop` impl of `WriteBackOnDrop`. So long as this `drop` is
382 // called before any other safe code executes, soundness is upheld.
383 // While this method can terminate in two ways (by returning normally or
384 // by unwinding due to a panic in `f`), in both cases, `write_back` is
385 // dropped - and its `drop` called - before any other safe code can
386 // execute.
387 let copy = unsafe { ptr::read(self) }.into_inner();
388 let mut write_back = WriteBackOnDrop { copy: ManuallyDrop::new(copy), slf: self };
389
390 let ret = f(&mut write_back.copy);
391
392 drop(write_back);
393 ret
394 }
395}
396
397impl<T: Copy> Unalign<T> {
398 /// Gets a copy of the inner `T`.
399 // FIXME(https://github.com/rust-lang/rust/issues/57349): Make this `const`.
400 #[inline(always)]
401 pub fn get(&self) -> T {
402 let Unalign(val) = *self;
403 val
404 }
405}
406
407impl<T: Unaligned> Deref for Unalign<T> {
408 type Target = T;
409
410 #[inline(always)]
411 fn deref(&self) -> &T {
412 Ptr::from_ref(self).transmute().bikeshed_recall_aligned().as_ref()
413 }
414}
415
416impl<T: Unaligned> DerefMut for Unalign<T> {
417 #[inline(always)]
418 fn deref_mut(&mut self) -> &mut T {
419 Ptr::from_mut(self).transmute::<_, _, (_, (_, _))>().bikeshed_recall_aligned().as_mut()
420 }
421}
422
423impl<T: Unaligned + PartialOrd> PartialOrd<Unalign<T>> for Unalign<T> {
424 #[inline(always)]
425 fn partial_cmp(&self, other: &Unalign<T>) -> Option<Ordering> {
426 PartialOrd::partial_cmp(self.deref(), other.deref())
427 }
428}
429
430impl<T: Unaligned + Ord> Ord for Unalign<T> {
431 #[inline(always)]
432 fn cmp(&self, other: &Unalign<T>) -> Ordering {
433 Ord::cmp(self.deref(), other.deref())
434 }
435}
436
437impl<T: Unaligned + PartialEq> PartialEq<Unalign<T>> for Unalign<T> {
438 #[inline(always)]
439 fn eq(&self, other: &Unalign<T>) -> bool {
440 PartialEq::eq(self.deref(), other.deref())
441 }
442}
443
444impl<T: Unaligned + Eq> Eq for Unalign<T> {}
445
446impl<T: Unaligned + Hash> Hash for Unalign<T> {
447 #[inline(always)]
448 fn hash<H>(&self, state: &mut H)
449 where
450 H: Hasher,
451 {
452 self.deref().hash(state);
453 }
454}
455
456impl<T: Unaligned + Debug> Debug for Unalign<T> {
457 #[inline(always)]
458 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
459 Debug::fmt(self.deref(), f)
460 }
461}
462
463impl<T: Unaligned + Display> Display for Unalign<T> {
464 #[inline(always)]
465 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
466 Display::fmt(self.deref(), f)
467 }
468}
469
470/// A wrapper type to construct uninitialized instances of `T`.
471///
472/// `MaybeUninit` is identical to the [standard library
473/// `MaybeUninit`][core-maybe-uninit] type except that it supports unsized
474/// types.
475///
476/// # Layout
477///
478/// The same layout guarantees and caveats apply to `MaybeUninit<T>` as apply to
479/// the [standard library `MaybeUninit`][core-maybe-uninit] with one exception:
480/// for `T: !Sized`, there is no single value for `T`'s size. Instead, for such
481/// types, the following are guaranteed:
482/// - Every [valid size][valid-size] for `T` is a valid size for
483/// `MaybeUninit<T>` and vice versa
484/// - Given `t: *const T` and `m: *const MaybeUninit<T>` with identical fat
485/// pointer metadata, `t` and `m` address the same number of bytes (and
486/// likewise for `*mut`)
487///
488/// [core-maybe-uninit]: core::mem::MaybeUninit
489/// [valid-size]: crate::KnownLayout#what-is-a-valid-size
490#[repr(transparent)]
491#[doc(hidden)]
492pub struct MaybeUninit<T: ?Sized + KnownLayout>(
493 // SAFETY: `MaybeUninit<T>` has the same size as `T`, because (by invariant
494 // on `T::MaybeUninit`) `T::MaybeUninit` has `T::LAYOUT` identical to `T`,
495 // and because (invariant on `T::LAYOUT`) we can trust that `LAYOUT`
496 // accurately reflects the layout of `T`. By invariant on `T::MaybeUninit`,
497 // it admits uninitialized bytes in all positions. Because `MaybeUninit` is
498 // marked `repr(transparent)`, these properties additionally hold true for
499 // `Self`.
500 T::MaybeUninit,
501);
502
503#[doc(hidden)]
504impl<T: ?Sized + KnownLayout> MaybeUninit<T> {
505 /// Constructs a `MaybeUninit<T>` initialized with the given value.
506 #[inline(always)]
507 pub fn new(val: T) -> Self
508 where
509 T: Sized,
510 Self: Sized,
511 {
512 // SAFETY: It is valid to transmute `val` to `MaybeUninit<T>` because it
513 // is both valid to transmute `val` to `T::MaybeUninit`, and it is valid
514 // to transmute from `T::MaybeUninit` to `MaybeUninit<T>`.
515 //
516 // First, it is valid to transmute `val` to `T::MaybeUninit` because, by
517 // invariant on `T::MaybeUninit`:
518 // - For `T: Sized`, `T` and `T::MaybeUninit` have the same size.
519 // - All byte sequences of the correct size are valid values of
520 // `T::MaybeUninit`.
521 //
522 // Second, it is additionally valid to transmute from `T::MaybeUninit`
523 // to `MaybeUninit<T>`, because `MaybeUninit<T>` is a
524 // `repr(transparent)` wrapper around `T::MaybeUninit`.
525 //
526 // These two transmutes are collapsed into one so we don't need to add a
527 // `T::MaybeUninit: Sized` bound to this function's `where` clause.
528 unsafe { crate::util::transmute_unchecked(val) }
529 }
530
531 /// Constructs an uninitialized `MaybeUninit<T>`.
532 #[must_use]
533 #[inline(always)]
534 pub fn uninit() -> Self
535 where
536 T: Sized,
537 Self: Sized,
538 {
539 let uninit = CoreMaybeUninit::<T>::uninit();
540 // SAFETY: It is valid to transmute from `CoreMaybeUninit<T>` to
541 // `MaybeUninit<T>` since they both admit uninitialized bytes in all
542 // positions, and they have the same size (i.e., that of `T`).
543 //
544 // `MaybeUninit<T>` has the same size as `T`, because (by invariant on
545 // `T::MaybeUninit`) `T::MaybeUninit` has `T::LAYOUT` identical to `T`,
546 // and because (invariant on `T::LAYOUT`) we can trust that `LAYOUT`
547 // accurately reflects the layout of `T`.
548 //
549 // `CoreMaybeUninit<T>` has the same size as `T` [1] and admits
550 // uninitialized bytes in all positions.
551 //
552 // [1] Per https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#layout-1:
553 //
554 // `MaybeUninit<T>` is guaranteed to have the same size, alignment,
555 // and ABI as `T`
556 unsafe { crate::util::transmute_unchecked(uninit) }
557 }
558
559 /// Creates a `Box<MaybeUninit<T>>`.
560 ///
561 /// This function is useful for allocating large, uninit values on the heap
562 /// without ever creating a temporary instance of `Self` on the stack.
563 ///
564 /// # Errors
565 ///
566 /// Returns an error on allocation failure. Allocation failure is guaranteed
567 /// never to cause a panic or an abort.
568 #[cfg(feature = "alloc")]
569 #[inline]
570 pub fn new_boxed_uninit(meta: T::PointerMetadata) -> Result<Box<Self>, AllocError> {
571 // SAFETY: `GlobalAlloc::allocate` is a valid argument of `new_box`. The
572 // referent of the pointer returned by `allocate` (and, consequently,
573 // the `Box` derived from it) is a valid instance of `Self`, because
574 // `Self` is `MaybeUninit` and thus admits arbitrary (un)initialized
575 // bytes.
576 unsafe {
577 crate::util::new_box(meta, crate::util::GlobalAlloc, crate::util::GlobalAlloc::allocate)
578 }
579 }
580
581 /// Extracts the value from the `MaybeUninit<T>` container.
582 ///
583 /// # Safety
584 ///
585 /// The caller must ensure that `self` is in an bit-valid state. Depending
586 /// on subsequent use, it may also need to be in a library-valid state.
587 #[inline(always)]
588 pub unsafe fn assume_init(self) -> T
589 where
590 T: Sized,
591 Self: Sized,
592 {
593 // SAFETY: The caller guarantees that `self` is in an bit-valid state.
594 unsafe { crate::util::transmute_unchecked(self) }
595 }
596}
597
598impl<T: ?Sized + KnownLayout> fmt::Debug for MaybeUninit<T> {
599 #[inline]
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601 f.pad(core::any::type_name::<Self>())
602 }
603}
604
605#[allow(unreachable_pub)] // False positive on MSRV
606#[doc(hidden)]
607pub use read_only_def::*;
608mod read_only_def {
609 /// A read-only wrapper.
610 ///
611 /// A `ReadOnly<T>` disables any interior mutability in `T`, ensuring that
612 /// a `&ReadOnly<T>` is genuinely read-only. Thus, `ReadOnly<T>` is
613 /// [`Immutable`] regardless of whether `T` is.
614 ///
615 /// Note that `&mut ReadOnly<T>` still permits mutation – the read-only
616 /// property only applies to shared references.
617 ///
618 /// `ReadOnly<T>` implements [`Copy`] and [`Clone`] when `T: Copy`. Cloning
619 /// copies the value without calling `T::clone`. Trait implementations that
620 /// expose or operate on a shared reference to `T` require `T: Immutable`.
621 /// Constructing a wrapper or accessing its contents through [`AsMut`]
622 /// does not require `T: Immutable`.
623 ///
624 /// [`Immutable`]: crate::Immutable
625 #[derive(Copy)]
626 #[repr(transparent)]
627 pub struct ReadOnly<T: ?Sized> {
628 // INVARIANT: `inner` is never mutated through a `&ReadOnly<T>`
629 // reference.
630 inner: T,
631 }
632
633 impl<T> ReadOnly<T> {
634 /// Creates a new `ReadOnly`.
635 #[must_use]
636 #[inline(always)]
637 pub const fn new(t: T) -> ReadOnly<T> {
638 ReadOnly { inner: t }
639 }
640
641 /// Returns the inner value.
642 #[must_use]
643 #[inline(always)]
644 pub fn into_inner(r: ReadOnly<T>) -> T {
645 r.inner
646 }
647 }
648
649 impl<T: ?Sized> ReadOnly<T> {
650 #[inline(always)]
651 pub(crate) fn as_mut(r: &mut ReadOnly<T>) -> &mut T {
652 // SAFETY: `r: &mut ReadOnly`, so this doesn't violate the invariant
653 // that `inner` is never mutated through a `&ReadOnly<T>` reference.
654 &mut r.inner
655 }
656
657 /// # Safety
658 ///
659 /// The caller promises not to mutate the referent (i.e., via interior
660 /// mutation).
661 pub(crate) const unsafe fn as_ref_unchecked(r: &ReadOnly<T>) -> &T {
662 // SAFETY: The caller promises not to mutate the referent.
663 &r.inner
664 }
665 }
666}
667
668// SAFETY: `ReadOnly<T>` is a `#[repr(transparent)` wrapper around `T`.
669const _: () = unsafe {
670 unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] ReadOnly<T>);
671};
672
673#[allow(clippy::multiple_unsafe_ops_per_block)]
674// SAFETY:
675// - `ReadOnly<T>` has the same alignment as `T`, and so it is `Unaligned`
676// exactly when `T` is as well.
677// - `ReadOnly<T>` has the same bit validity as `T`, and so this `is_safe`
678// implementation is correct, and thus the `TryFromBytes` impl is sound.
679// - `ReadOnly<T>` has the same bit validity as `T`, and so it is `FromZeros`,
680// `FromBytes`, and `IntoBytes` exactly when `T` is as well.
681const _: () = unsafe {
682 unsafe_impl!(T: ?Sized + Unaligned => Unaligned for ReadOnly<T>);
683 unsafe_impl!(
684 T: ?Sized + TryFromBytes => TryFromBytes for ReadOnly<T>;
685 |c| T::is_safe(c.cast::<_, <ReadOnly<T> as SizeEq<ReadOnly<ReadOnly<T>>>>::CastFrom, _>())
686 );
687 unsafe_impl!(T: ?Sized + FromZeros => FromZeros for ReadOnly<T>);
688 unsafe_impl!(T: ?Sized + FromBytes => FromBytes for ReadOnly<T>);
689 unsafe_impl!(T: ?Sized + IntoBytes => IntoBytes for ReadOnly<T>);
690};
691
692// SAFETY: By invariant, `inner` is never mutated through a `&ReadOnly<T>`
693// reference.
694const _: () = unsafe {
695 unsafe_impl!(T: ?Sized => Immutable for ReadOnly<T>);
696};
697
698const _: () = {
699 use crate::pointer::cast::CastExact;
700
701 // SAFETY: `ReadOnly<T>` has the same layout as `T`.
702 define_cast!(unsafe { pub CastFromReadOnly<T: ?Sized> = ReadOnly<T> => T});
703 // SAFETY: `ReadOnly<T>` has the same layout as `T`.
704 unsafe impl<T: ?Sized> CastExact<ReadOnly<T>, T> for CastFromReadOnly {}
705 // SAFETY: `ReadOnly<T>` has the same layout as `T`.
706 define_cast!(unsafe { pub CastToReadOnly<T: ?Sized> = T => ReadOnly<T>});
707 // SAFETY: `ReadOnly<T>` has the same layout as `T`.
708 unsafe impl<T: ?Sized> CastExact<T, ReadOnly<T>> for CastToReadOnly {}
709
710 impl<T: ?Sized> SizeEq<ReadOnly<T>> for T {
711 type CastFrom = CastFromReadOnly;
712 }
713
714 impl<T: ?Sized> SizeEq<T> for ReadOnly<T> {
715 type CastFrom = CastToReadOnly;
716 }
717};
718
719// SAFETY: `ReadOnly<T>` is a `#[repr(transparent)]` wrapper around `T`, and so
720// it has the same bit validity as `T`.
721unsafe impl<T: ?Sized> TransmuteFrom<T, Safe, Safe> for ReadOnly<T> {}
722
723// SAFETY: `ReadOnly<T>` is a `#[repr(transparent)]` wrapper around `T`, and so
724// it has the same bit validity as `T`.
725unsafe impl<T: ?Sized> TransmuteFrom<ReadOnly<T>, Safe, Safe> for T {}
726
727impl<T: Default> Default for ReadOnly<T> {
728 #[inline(always)]
729 fn default() -> Self {
730 Self::new(Default::default())
731 }
732}
733
734// Copying avoids calling `T::clone`, which could mutate through a shared
735// reference to `T` and violate `ReadOnly`'s invariant.
736impl<T: Copy> Clone for ReadOnly<T> {
737 #[inline(always)]
738 fn clone(&self) -> Self {
739 *self
740 }
741}
742
743impl<T> From<T> for ReadOnly<T> {
744 #[inline(always)]
745 fn from(t: T) -> Self {
746 Self::new(t)
747 }
748}
749
750impl<'a, T: ?Sized + Immutable> From<&'a T> for &'a ReadOnly<T> {
751 #[inline(always)]
752 fn from(t: &'a T) -> &'a ReadOnly<T> {
753 let ro = Ptr::from_ref(t).transmute::<_, _, (_, _)>();
754 // SAFETY: `ReadOnly<T>` has the same alignment as `T`, and
755 // `Ptr::from_ref` produces an aligned `Ptr`.
756 let ro = unsafe { ro.assume_alignment() };
757 ro.as_ref()
758 }
759}
760
761impl<T: ?Sized + Immutable> Deref for ReadOnly<T> {
762 type Target = T;
763
764 #[inline(always)]
765 fn deref(&self) -> &Self::Target {
766 // SAFETY: By `T: Immutable`, `&T` doesn't permit interior mutation.
767 unsafe { ReadOnly::as_ref_unchecked(self) }
768 }
769}
770
771impl<T: ?Sized + Immutable> DerefMut for ReadOnly<T> {
772 #[inline(always)]
773 fn deref_mut(&mut self) -> &mut Self::Target {
774 ReadOnly::as_mut(self)
775 }
776}
777
778impl<T: ?Sized + Immutable> AsRef<T> for ReadOnly<T> {
779 #[inline(always)]
780 fn as_ref(&self) -> &T {
781 self.deref()
782 }
783}
784
785impl<T: ?Sized + Immutable> Borrow<T> for ReadOnly<T> {
786 #[inline(always)]
787 fn borrow(&self) -> &T {
788 self.deref()
789 }
790}
791
792impl<T: ?Sized> AsMut<T> for ReadOnly<T> {
793 #[inline(always)]
794 fn as_mut(&mut self) -> &mut T {
795 ReadOnly::as_mut(self)
796 }
797}
798
799// Delegate shared access through `Deref`, which requires `T: Immutable` and
800// thus prevents interior mutation of the wrapped value by these trait methods.
801impl<T: ?Sized + Immutable + PartialEq> PartialEq for ReadOnly<T> {
802 #[inline(always)]
803 fn eq(&self, other: &Self) -> bool {
804 self.deref().eq(other.deref())
805 }
806}
807
808impl<T: ?Sized + Immutable + Eq> Eq for ReadOnly<T> {}
809
810impl<T: ?Sized + Immutable + PartialOrd> PartialOrd for ReadOnly<T> {
811 #[inline(always)]
812 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
813 self.deref().partial_cmp(other.deref())
814 }
815}
816
817impl<T: ?Sized + Immutable + Ord> Ord for ReadOnly<T> {
818 #[inline(always)]
819 fn cmp(&self, other: &Self) -> Ordering {
820 self.deref().cmp(other.deref())
821 }
822}
823
824impl<T: ?Sized + Immutable + Hash> Hash for ReadOnly<T> {
825 #[inline(always)]
826 fn hash<H: Hasher>(&self, state: &mut H) {
827 self.deref().hash(state);
828 }
829}
830
831macro_rules! impl_read_only_fmt {
832 ($($trait:ident),* $(,)?) => {$(
833 impl<T: ?Sized + Immutable + fmt::$trait> fmt::$trait for ReadOnly<T> {
834 #[inline(always)]
835 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
836 fmt::$trait::fmt(self.deref(), f)
837 }
838 }
839 )*};
840}
841
842impl_read_only_fmt!(Debug, Display, Binary, Octal, LowerHex, UpperHex, LowerExp, UpperExp);
843
844// SAFETY: See safety comment on `ProjectToTag`.
845unsafe impl<T: HasTag<Client> + ?Sized, Client> HasTag<Client> for ReadOnly<T> {
846 #[allow(clippy::missing_inline_in_public_items)]
847 fn only_derive_is_allowed_to_implement_this_trait()
848 where
849 Self: Sized,
850 {
851 }
852
853 type Tag = <T as HasTag<Client>>::Tag;
854
855 // SAFETY: `<T as SizeEq<ReadOnly<T>>>::CastFrom` is a no-op projection that
856 // produces a pointer with the same referent. By invariant, for any
857 // `Ptr<'_, T, I>` it is sound to use
858 // `<T as HasTag<Client>>::ProjectToTag` to project to a
859 // shared `Ptr<'_, <T as HasTag<Client>>::Tag,
860 // (_, I::Alignment, I::Validity)>`. Since `ReadOnly<T>` has the same
861 // layout and validity as `T`, the same is true of projecting from a
862 // `Ptr<'_, ReadOnly<T>, I>`.
863 type ProjectToTag = crate::pointer::cast::TransitiveProject<
864 T,
865 <T as SizeEq<ReadOnly<T>>>::CastFrom,
866 <T as HasTag<Client>>::ProjectToTag,
867 >;
868}
869
870// SAFETY: `ReadOnly<T>` is a `#[repr(transparent)]` wrapper around `T`, and so
871// has the same fields at the same offsets. Thus, it satisfies the safety
872// invariants of `HasField<Client, Field, VARIANT_ID, FIELD_ID>` for field `f`
873// exactly when `T` does, as guaranteed by the `T: HasField` bound:
874// - If `VARIANT_ID` is `STRUCT_VARIANT_ID`, `UNION_VARIANT_ID`, or
875// `REPR_C_UNION_VARIANT_ID`, then `T` has the layout of a struct, non-C union,
876// or C union type respectively. Since `ReadOnly<T>` is a transparent wrapper
877// around `T`, it does too. Otherwise, `VARIANT_ID` is the identifier ID of an
878// enum variant; `T` has the layout of an enum type, and `ReadOnly<T>` does too.
879// - By `T: HasField<_, _, _, FIELD_ID>`:
880// - `T` has a field `f` with name `n` such that
881// `FIELD_ID = zerocopy::ident_id!(n)` or at index `i` such that
882// `FIELD_ID = zerocopy::ident_id!(i)`.
883// - `Field` has the same visibility as `f`.
884// - `T::Type` has the same type as `f`. Thus, `ReadOnly<T::Type>` has the
885// same type as `f`, wrapped in `ReadOnly`.
886//
887// `project` satisfies its post-condition – namely, that the returned pointer
888// refers to a non-strict subset of the bytes of `slf`'s referent, and has the
889// same provenance as `slf` – because all intermediate operations satisfy those
890// same conditions.
891unsafe impl<T, Client, Field, const VARIANT_ID: i128, const FIELD_ID: i128>
892 HasField<Client, Field, VARIANT_ID, FIELD_ID> for ReadOnly<T>
893where
894 T: HasField<Client, Field, VARIANT_ID, FIELD_ID> + ?Sized,
895{
896 #[allow(clippy::missing_inline_in_public_items)]
897 fn only_derive_is_allowed_to_implement_this_trait()
898 where
899 Self: Sized,
900 {
901 }
902
903 type Type = ReadOnly<T::Type>;
904
905 #[inline(always)]
906 fn project(slf: PtrInner<'_, Self>) -> *mut ReadOnly<T::Type> {
907 slf.project::<_, <T as SizeEq<ReadOnly<T>>>::CastFrom>()
908 .project::<_, crate::pointer::cast::Projection<Client, Field, VARIANT_ID, FIELD_ID>>()
909 .project::<_, <ReadOnly<T::Type> as SizeEq<T::Type>>::CastFrom>()
910 .as_non_null()
911 .as_ptr()
912 }
913}
914
915// SAFETY: `ReadOnly<T>` is a `#[repr(transparent)]` wrapper around `T`, and so
916// has the same fields at the same offsets. `is_projectable` simply delegates to
917// `T::is_projectable`, which is sound because a `Ptr<'_, ReadOnly<T>, I>` will
918// be projectable exactly when a `Ptr<'_, T, I>` referent is.
919unsafe impl<T, Client, Field, I, const VARIANT_ID: i128, const FIELD_ID: i128>
920 ProjectField<Client, Field, I, VARIANT_ID, FIELD_ID> for ReadOnly<T>
921where
922 T: ProjectField<Client, Field, I, VARIANT_ID, FIELD_ID> + ?Sized,
923 I: invariant::Invariants,
924{
925 #[allow(clippy::missing_inline_in_public_items)]
926 fn only_derive_is_allowed_to_implement_this_trait()
927 where
928 Self: Sized,
929 {
930 }
931
932 type Invariants = <T as ProjectField<Client, Field, I, VARIANT_ID, FIELD_ID>>::Invariants;
933
934 type Error = <T as ProjectField<Client, Field, I, VARIANT_ID, FIELD_ID>>::Error;
935
936 #[inline(always)]
937 fn is_projectable<'a>(
938 ptr: Ptr<'a, <Self as HasTag<Client>>::Tag, (invariant::Shared, I::Alignment, I::Validity)>,
939 ) -> Result<(), Self::Error> {
940 <T as ProjectField<Client, Field, I, VARIANT_ID, FIELD_ID>>::is_projectable(ptr)
941 }
942}
943
944#[cfg(test)]
945mod tests {
946 use core::panic::AssertUnwindSafe;
947
948 use super::*;
949 use crate::util::testutil::*;
950
951 #[test]
952 #[allow(clippy::clone_on_copy, clippy::non_canonical_clone_impl)]
953 fn test_read_only_copy_clone() {
954 // This type deliberately does not implement `Immutable`. Copying the
955 // wrapper must not require it or invoke the inner `Clone` impl.
956 #[derive(Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
957 struct PanickingClone(u16);
958
959 impl Clone for PanickingClone {
960 fn clone(&self) -> Self {
961 panic!("ReadOnly must not call the inner Clone implementation")
962 }
963 }
964
965 static_assertions::assert_not_impl_any!(
966 ReadOnly<PanickingClone>: Debug, PartialEq, Eq, PartialOrd, Ord,
967 Hash, AsRef<PanickingClone>, Borrow<PanickingClone>
968 );
969 static_assertions::assert_not_impl_any!(
970 ReadOnly<Cell<u8>>: Copy, Clone, Deref, AsRef<Cell<u8>>, Borrow<Cell<u8>>
971 );
972
973 let value = ReadOnly::new(PanickingClone(42));
974 let copy = value;
975 let clone = value.clone();
976 assert_eq!(ReadOnly::into_inner(copy).0, 42);
977 assert_eq!(ReadOnly::into_inner(clone).0, 42);
978 }
979
980 #[test]
981 fn test_read_only_mutable_access() {
982 // Construction and exclusive access also support interior mutability.
983 let mut value = ReadOnly::<Cell<u8>>::default();
984 let inner: &mut Cell<u8> = value.as_mut();
985 inner.set(42);
986 assert_eq!(ReadOnly::into_inner(value).get(), 42);
987
988 let value = ReadOnly::from(Cell::new(7));
989 assert_eq!(ReadOnly::into_inner(value).get(), 7);
990 }
991
992 #[test]
993 fn test_read_only_borrowed_lookup() {
994 // Borrowed lookups require equality, hashing, and ordering to agree
995 // between the wrapper and the inner value.
996 let mut hash_map = std::collections::HashMap::new();
997 hash_map.insert(ReadOnly::new(42u16), true);
998 assert_eq!(hash_map.get(&42u16), Some(&true));
999 assert_eq!(hash_map.get(&43u16), None);
1000
1001 let mut tree = std::collections::BTreeMap::new();
1002 tree.insert(ReadOnly::new(42u16), true);
1003 assert_eq!(tree.get(&42u16), Some(&true));
1004 assert_eq!(tree.get(&43u16), None);
1005
1006 // Preserve partial orders, including incomparable values.
1007 let nan = ReadOnly::new(f32::NAN);
1008 assert_eq!(nan.partial_cmp(&nan), None);
1009 assert_ne!(nan, nan);
1010 }
1011
1012 #[test]
1013 fn test_read_only_unsized() {
1014 let bytes = [1u8, 2];
1015 let value: &ReadOnly<[u8]> = (&bytes[..]).into();
1016 let as_ref: &[u8] = value.as_ref();
1017 let borrowed: &[u8] = value.borrow();
1018 assert_eq!(as_ref, bytes);
1019 assert_eq!(borrowed, bytes);
1020 assert_eq!(value, value);
1021 assert_eq!(value.cmp(value), Ordering::Equal);
1022
1023 let text: &ReadOnly<str> = "hello".into();
1024 assert_eq!(format!("{:.3}", text), "hel");
1025 }
1026
1027 #[test]
1028 fn test_read_only_formatting() {
1029 let value = ReadOnly::new(42u16);
1030 // Check that formatting flags are forwarded as well as the value.
1031 assert_eq!(format!("{:04?}", value), "0042");
1032 assert_eq!(format!("{:04}", value), "0042");
1033 assert_eq!(format!("{:#010b}", value), "0b00101010");
1034 assert_eq!(format!("{:#06o}", value), "0o0052");
1035 assert_eq!(format!("{:#06x}", value), "0x002a");
1036 assert_eq!(format!("{:#06X}", value), "0x002A");
1037 assert_eq!(format!("{:.2e}", value), "4.20e1");
1038 assert_eq!(format!("{:.2E}", value), "4.20E1");
1039 }
1040
1041 #[test]
1042 fn test_unalign() {
1043 // Test methods that don't depend on alignment.
1044 let mut u = Unalign::new(AU64(123));
1045 assert_eq!(u.get(), AU64(123));
1046 assert_eq!(u.into_inner(), AU64(123));
1047 assert_eq!(u.get_ptr(), <*const _>::cast::<AU64>(&u));
1048 assert_eq!(u.get_mut_ptr(), <*mut _>::cast::<AU64>(&mut u));
1049 u.set(AU64(321));
1050 assert_eq!(u.get(), AU64(321));
1051
1052 // Test methods that depend on alignment (when alignment is satisfied).
1053 let mut u: Align<_, AU64> = Align::new(Unalign::new(AU64(123)));
1054 assert_eq!(u.t.try_deref().unwrap(), &AU64(123));
1055 assert_eq!(u.t.try_deref_mut().unwrap(), &mut AU64(123));
1056 // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
1057 assert_eq!(unsafe { u.t.deref_unchecked() }, &AU64(123));
1058 // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
1059 assert_eq!(unsafe { u.t.deref_mut_unchecked() }, &mut AU64(123));
1060 *u.t.try_deref_mut().unwrap() = AU64(321);
1061 assert_eq!(u.t.get(), AU64(321));
1062
1063 // Test methods that depend on alignment (when alignment is not
1064 // satisfied).
1065 let mut u: ForceUnalign<_, AU64> = ForceUnalign::new(Unalign::new(AU64(123)));
1066 assert!(matches!(u.t.try_deref(), Err(AlignmentError { .. })));
1067 assert!(matches!(u.t.try_deref_mut(), Err(AlignmentError { .. })));
1068
1069 // Test methods that depend on `T: Unaligned`.
1070 let mut u = Unalign::new(123u8);
1071 assert_eq!(u.try_deref(), Ok(&123));
1072 assert_eq!(u.try_deref_mut(), Ok(&mut 123));
1073 assert_eq!(u.deref(), &123);
1074 assert_eq!(u.deref_mut(), &mut 123);
1075 *u = 21;
1076 assert_eq!(u.get(), 21);
1077
1078 // Test that some `Unalign` functions and methods are `const`.
1079 const _UNALIGN: Unalign<u64> = Unalign::new(0);
1080 const _UNALIGN_PTR: *const u64 = _UNALIGN.get_ptr();
1081 const _U64: u64 = _UNALIGN.into_inner();
1082 // Make sure all code is considered "used".
1083 //
1084 // FIXME(https://github.com/rust-lang/rust/issues/104084): Remove this
1085 // attribute.
1086 #[allow(dead_code)]
1087 const _: () = {
1088 let x: Align<_, AU64> = Align::new(Unalign::new(AU64(123)));
1089 // Make sure that `deref_unchecked` is `const`.
1090 //
1091 // SAFETY: The `Align<_, AU64>` guarantees proper alignment.
1092 let au64 = unsafe { x.t.deref_unchecked() };
1093 match au64 {
1094 AU64(123) => {}
1095 _ => const_unreachable!(),
1096 }
1097 };
1098 }
1099
1100 #[test]
1101 fn test_unalign_update() {
1102 let mut u = Unalign::new(AU64(123));
1103 u.update(|a| a.0 += 1);
1104 assert_eq!(u.get(), AU64(124));
1105
1106 // Test that, even if the callback panics, the original is still
1107 // correctly overwritten. Use a `Box` so that Miri is more likely to
1108 // catch any unsoundness (which would likely result in two `Box`es for
1109 // the same heap object, which is the sort of thing that Miri would
1110 // probably catch).
1111 let mut u = Unalign::new(Box::new(AU64(123)));
1112 let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
1113 u.update(|a| {
1114 a.0 += 1;
1115 panic!();
1116 })
1117 }));
1118 assert!(res.is_err());
1119 assert_eq!(u.into_inner(), Box::new(AU64(124)));
1120
1121 // Test the align_of::<T>() == 1 optimization.
1122 let mut u = Unalign::new([0u8, 1]);
1123 u.update(|a| a[0] += 1);
1124 assert_eq!(u.get(), [1u8, 1]);
1125 }
1126
1127 #[test]
1128 fn test_unalign_copy_clone() {
1129 // Test that `Copy` and `Clone` do not cause soundness issues. This test
1130 // is mainly meant to exercise UB that would be caught by Miri.
1131
1132 // `u.t` is definitely not validly-aligned for `AU64`'s alignment of 8.
1133 let u = ForceUnalign::<_, AU64>::new(Unalign::new(AU64(123)));
1134 #[allow(clippy::clone_on_copy)]
1135 let v = u.t.clone();
1136 let w = u.t;
1137 assert_eq!(u.t.get(), v.get());
1138 assert_eq!(u.t.get(), w.get());
1139 assert_eq!(v.get(), w.get());
1140 }
1141
1142 #[test]
1143 fn test_unalign_trait_impls() {
1144 let zero = Unalign::new(0u8);
1145 let one = Unalign::new(1u8);
1146
1147 assert!(zero < one);
1148 assert_eq!(PartialOrd::partial_cmp(&zero, &one), Some(Ordering::Less));
1149 assert_eq!(Ord::cmp(&zero, &one), Ordering::Less);
1150
1151 assert_ne!(zero, one);
1152 assert_eq!(zero, zero);
1153 assert!(!PartialEq::eq(&zero, &one));
1154 assert!(PartialEq::eq(&zero, &zero));
1155
1156 fn hash<T: Hash>(t: &T) -> u64 {
1157 let mut h = std::collections::hash_map::DefaultHasher::new();
1158 t.hash(&mut h);
1159 h.finish()
1160 }
1161
1162 assert_eq!(hash(&zero), hash(&0u8));
1163 assert_eq!(hash(&one), hash(&1u8));
1164
1165 assert_eq!(format!("{:?}", zero), format!("{:?}", 0u8));
1166 assert_eq!(format!("{:?}", one), format!("{:?}", 1u8));
1167 assert_eq!(format!("{}", zero), format!("{}", 0u8));
1168 assert_eq!(format!("{}", one), format!("{}", 1u8));
1169 }
1170
1171 #[test]
1172 #[allow(clippy::as_conversions)]
1173 fn test_maybe_uninit() {
1174 // int
1175 {
1176 let input = 42;
1177 let uninit = MaybeUninit::new(input);
1178 // SAFETY: `uninit` is in an initialized state
1179 let output = unsafe { uninit.assume_init() };
1180 assert_eq!(input, output);
1181 }
1182
1183 // thin ref
1184 {
1185 let input = 42;
1186 let uninit = MaybeUninit::new(&input);
1187 // SAFETY: `uninit` is in an initialized state
1188 let output = unsafe { uninit.assume_init() };
1189 assert_eq!(&input as *const _, output as *const _);
1190 assert_eq!(input, *output);
1191 }
1192
1193 // wide ref
1194 {
1195 let input = [1, 2, 3, 4];
1196 let uninit = MaybeUninit::new(&input[..]);
1197 // SAFETY: `uninit` is in an initialized state
1198 let output = unsafe { uninit.assume_init() };
1199 assert_eq!(&input[..] as *const _, output as *const _);
1200 assert_eq!(input, *output);
1201 }
1202 }
1203 #[test]
1204 fn test_maybe_uninit_uninit() {
1205 let _uninit = MaybeUninit::<u8>::uninit();
1206 // Cannot check value, but can check it compiles and runs
1207 }
1208
1209 #[test]
1210 #[cfg(feature = "alloc")]
1211 fn test_maybe_uninit_new_boxed_uninit() {
1212 let _boxed = MaybeUninit::<u8>::new_boxed_uninit(()).unwrap();
1213 }
1214
1215 #[test]
1216 fn test_maybe_uninit_debug() {
1217 let uninit = MaybeUninit::<u8>::uninit();
1218 assert!(format!("{:?}", uninit).contains("MaybeUninit"));
1219 }
1220}