zerocopy/pointer/mod.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
9//! Abstractions over raw pointers.
10
11mod aliasing_safety;
12mod ptr;
13
14pub use aliasing_safety::{AliasingSafe, AliasingSafeReason, BecauseExclusive, BecauseImmutable};
15pub use ptr::{invariant, Ptr};
16
17use crate::Unaligned;
18
19/// A shorthand for a maybe-valid, maybe-aligned reference. Used as the argument
20/// to [`TryFromBytes::is_bit_valid`].
21///
22/// [`TryFromBytes::is_bit_valid`]: crate::TryFromBytes::is_bit_valid
23pub type Maybe<'a, T, Aliasing = invariant::Shared, Alignment = invariant::Any> =
24 Ptr<'a, T, (Aliasing, Alignment, invariant::Initialized)>;
25
26/// A semi-user-facing wrapper type representing a maybe-aligned reference, for
27/// use in [`TryFromBytes::is_bit_valid`].
28///
29/// [`TryFromBytes::is_bit_valid`]: crate::TryFromBytes::is_bit_valid
30pub type MaybeAligned<'a, T, Aliasing = invariant::Shared, Alignment = invariant::Any> =
31 Ptr<'a, T, (Aliasing, Alignment, invariant::Valid)>;
32
33// These methods are defined on the type alias, `MaybeAligned`, so as to bring
34// them to the forefront of the rendered rustdoc for that type alias.
35impl<'a, T, Aliasing, Alignment> MaybeAligned<'a, T, Aliasing, Alignment>
36where
37 T: 'a + ?Sized,
38 Aliasing: invariant::Aliasing + invariant::AtLeast<invariant::Shared>,
39 Alignment: invariant::Alignment,
40{
41 /// Reads the value from `MaybeAligned`.
42 #[must_use]
43 #[inline]
44 pub fn read_unaligned(self) -> T
45 where
46 T: Copy,
47 {
48 let raw = self.as_non_null().as_ptr();
49 // SAFETY: By invariant on `MaybeAligned`, `raw` contains
50 // validly-initialized data for `T`. The value is safe to read and
51 // return, because `T` is copy.
52 unsafe { core::ptr::read_unaligned(raw) }
53 }
54
55 /// Views the value as an aligned reference.
56 ///
57 /// This is only available if `T` is [`Unaligned`].
58 #[must_use]
59 #[inline]
60 pub fn unaligned_as_ref(self) -> &'a T
61 where
62 T: Unaligned,
63 {
64 self.bikeshed_recall_aligned().as_ref()
65 }
66}
67
68/// Checks if the referent is zeroed.
69pub(crate) fn is_zeroed<T, I>(ptr: Ptr<'_, T, I>) -> bool
70where
71 T: crate::Immutable + crate::KnownLayout,
72 I: invariant::Invariants<Validity = invariant::Initialized>,
73 I::Aliasing: invariant::AtLeast<invariant::Shared>,
74{
75 ptr.as_bytes::<BecauseImmutable>().as_ref().iter().all(|&byte| byte == 0)
76}