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