1*c3739801SMiguel Ojeda // Copyright 2023 The Fuchsia Authors 2*c3739801SMiguel Ojeda // 3*c3739801SMiguel Ojeda // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 4*c3739801SMiguel Ojeda // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT 5*c3739801SMiguel Ojeda // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. 6*c3739801SMiguel Ojeda // This file may not be copied, modified, or distributed except according to 7*c3739801SMiguel Ojeda // those terms. 8*c3739801SMiguel Ojeda 9*c3739801SMiguel Ojeda #![allow(missing_docs)] 10*c3739801SMiguel Ojeda 11*c3739801SMiguel Ojeda use core::{ 12*c3739801SMiguel Ojeda fmt::{Debug, Formatter}, 13*c3739801SMiguel Ojeda marker::PhantomData, 14*c3739801SMiguel Ojeda }; 15*c3739801SMiguel Ojeda 16*c3739801SMiguel Ojeda use crate::{ 17*c3739801SMiguel Ojeda pointer::{ 18*c3739801SMiguel Ojeda inner::PtrInner, 19*c3739801SMiguel Ojeda invariant::*, 20*c3739801SMiguel Ojeda transmute::{MutationCompatible, SizeEq, TransmuteFromPtr}, 21*c3739801SMiguel Ojeda }, 22*c3739801SMiguel Ojeda AlignmentError, CastError, CastType, KnownLayout, SizeError, TryFromBytes, ValidityError, 23*c3739801SMiguel Ojeda }; 24*c3739801SMiguel Ojeda 25*c3739801SMiguel Ojeda /// Module used to gate access to [`Ptr`]'s fields. 26*c3739801SMiguel Ojeda mod def { 27*c3739801SMiguel Ojeda #[cfg(doc)] 28*c3739801SMiguel Ojeda use super::super::invariant; 29*c3739801SMiguel Ojeda use super::*; 30*c3739801SMiguel Ojeda 31*c3739801SMiguel Ojeda /// A raw pointer with more restrictions. 32*c3739801SMiguel Ojeda /// 33*c3739801SMiguel Ojeda /// `Ptr<T>` is similar to [`NonNull<T>`], but it is more restrictive in the 34*c3739801SMiguel Ojeda /// following ways (note that these requirements only hold of non-zero-sized 35*c3739801SMiguel Ojeda /// referents): 36*c3739801SMiguel Ojeda /// - It must derive from a valid allocation. 37*c3739801SMiguel Ojeda /// - It must reference a byte range which is contained inside the 38*c3739801SMiguel Ojeda /// allocation from which it derives. 39*c3739801SMiguel Ojeda /// - As a consequence, the byte range it references must have a size 40*c3739801SMiguel Ojeda /// which does not overflow `isize`. 41*c3739801SMiguel Ojeda /// 42*c3739801SMiguel Ojeda /// Depending on how `Ptr` is parameterized, it may have additional 43*c3739801SMiguel Ojeda /// invariants: 44*c3739801SMiguel Ojeda /// - `ptr` conforms to the aliasing invariant of 45*c3739801SMiguel Ojeda /// [`I::Aliasing`](invariant::Aliasing). 46*c3739801SMiguel Ojeda /// - `ptr` conforms to the alignment invariant of 47*c3739801SMiguel Ojeda /// [`I::Alignment`](invariant::Alignment). 48*c3739801SMiguel Ojeda /// - `ptr` conforms to the validity invariant of 49*c3739801SMiguel Ojeda /// [`I::Validity`](invariant::Validity). 50*c3739801SMiguel Ojeda /// 51*c3739801SMiguel Ojeda /// `Ptr<'a, T>` is [covariant] in `'a` and invariant in `T`. 52*c3739801SMiguel Ojeda /// 53*c3739801SMiguel Ojeda /// [`NonNull<T>`]: core::ptr::NonNull 54*c3739801SMiguel Ojeda /// [covariant]: https://doc.rust-lang.org/reference/subtyping.html 55*c3739801SMiguel Ojeda pub struct Ptr<'a, T, I> 56*c3739801SMiguel Ojeda where 57*c3739801SMiguel Ojeda T: ?Sized, 58*c3739801SMiguel Ojeda I: Invariants, 59*c3739801SMiguel Ojeda { 60*c3739801SMiguel Ojeda /// # Invariants 61*c3739801SMiguel Ojeda /// 62*c3739801SMiguel Ojeda /// 0. `ptr` conforms to the aliasing invariant of 63*c3739801SMiguel Ojeda /// [`I::Aliasing`](invariant::Aliasing). 64*c3739801SMiguel Ojeda /// 1. `ptr` conforms to the alignment invariant of 65*c3739801SMiguel Ojeda /// [`I::Alignment`](invariant::Alignment). 66*c3739801SMiguel Ojeda /// 2. `ptr` conforms to the validity invariant of 67*c3739801SMiguel Ojeda /// [`I::Validity`](invariant::Validity). 68*c3739801SMiguel Ojeda // SAFETY: `PtrInner<'a, T>` is covariant in `'a` and invariant in `T`. 69*c3739801SMiguel Ojeda ptr: PtrInner<'a, T>, 70*c3739801SMiguel Ojeda _invariants: PhantomData<I>, 71*c3739801SMiguel Ojeda } 72*c3739801SMiguel Ojeda 73*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 74*c3739801SMiguel Ojeda where 75*c3739801SMiguel Ojeda T: 'a + ?Sized, 76*c3739801SMiguel Ojeda I: Invariants, 77*c3739801SMiguel Ojeda { 78*c3739801SMiguel Ojeda /// Constructs a new `Ptr` from a [`PtrInner`]. 79*c3739801SMiguel Ojeda /// 80*c3739801SMiguel Ojeda /// # Safety 81*c3739801SMiguel Ojeda /// 82*c3739801SMiguel Ojeda /// The caller promises that: 83*c3739801SMiguel Ojeda /// 84*c3739801SMiguel Ojeda /// 0. `ptr` conforms to the aliasing invariant of 85*c3739801SMiguel Ojeda /// [`I::Aliasing`](invariant::Aliasing). 86*c3739801SMiguel Ojeda /// 1. `ptr` conforms to the alignment invariant of 87*c3739801SMiguel Ojeda /// [`I::Alignment`](invariant::Alignment). 88*c3739801SMiguel Ojeda /// 2. `ptr` conforms to the validity invariant of 89*c3739801SMiguel Ojeda /// [`I::Validity`](invariant::Validity). 90*c3739801SMiguel Ojeda pub(crate) unsafe fn from_inner(ptr: PtrInner<'a, T>) -> Ptr<'a, T, I> { 91*c3739801SMiguel Ojeda // SAFETY: The caller has promised to satisfy all safety invariants 92*c3739801SMiguel Ojeda // of `Ptr`. 93*c3739801SMiguel Ojeda Self { ptr, _invariants: PhantomData } 94*c3739801SMiguel Ojeda } 95*c3739801SMiguel Ojeda 96*c3739801SMiguel Ojeda /// Converts this `Ptr<T>` to a [`PtrInner<T>`]. 97*c3739801SMiguel Ojeda /// 98*c3739801SMiguel Ojeda /// Note that this method does not consume `self`. The caller should 99*c3739801SMiguel Ojeda /// watch out for `unsafe` code which uses the returned value in a way 100*c3739801SMiguel Ojeda /// that violates the safety invariants of `self`. 101*c3739801SMiguel Ojeda #[inline] 102*c3739801SMiguel Ojeda #[must_use] 103*c3739801SMiguel Ojeda pub fn as_inner(&self) -> PtrInner<'a, T> { 104*c3739801SMiguel Ojeda self.ptr 105*c3739801SMiguel Ojeda } 106*c3739801SMiguel Ojeda } 107*c3739801SMiguel Ojeda } 108*c3739801SMiguel Ojeda 109*c3739801SMiguel Ojeda #[allow(unreachable_pub)] // This is a false positive on our MSRV toolchain. 110*c3739801SMiguel Ojeda pub use def::Ptr; 111*c3739801SMiguel Ojeda 112*c3739801SMiguel Ojeda /// External trait implementations on [`Ptr`]. 113*c3739801SMiguel Ojeda mod _external { 114*c3739801SMiguel Ojeda use super::*; 115*c3739801SMiguel Ojeda 116*c3739801SMiguel Ojeda /// SAFETY: Shared pointers are safely `Copy`. `Ptr`'s other invariants 117*c3739801SMiguel Ojeda /// (besides aliasing) are unaffected by the number of references that exist 118*c3739801SMiguel Ojeda /// to `Ptr`'s referent. The notable cases are: 119*c3739801SMiguel Ojeda /// - Alignment is a property of the referent type (`T`) and the address, 120*c3739801SMiguel Ojeda /// both of which are unchanged 121*c3739801SMiguel Ojeda /// - Let `S(T, V)` be the set of bit values permitted to appear in the 122*c3739801SMiguel Ojeda /// referent of a `Ptr<T, I: Invariants<Validity = V>>`. Since this copy 123*c3739801SMiguel Ojeda /// does not change `I::Validity` or `T`, `S(T, I::Validity)` is also 124*c3739801SMiguel Ojeda /// unchanged. 125*c3739801SMiguel Ojeda /// 126*c3739801SMiguel Ojeda /// We are required to guarantee that the referents of the original `Ptr` 127*c3739801SMiguel Ojeda /// and of the copy (which, of course, are actually the same since they 128*c3739801SMiguel Ojeda /// live in the same byte address range) both remain in the set `S(T, 129*c3739801SMiguel Ojeda /// I::Validity)`. Since this invariant holds on the original `Ptr`, it 130*c3739801SMiguel Ojeda /// cannot be violated by the original `Ptr`, and thus the original `Ptr` 131*c3739801SMiguel Ojeda /// cannot be used to violate this invariant on the copy. The inverse 132*c3739801SMiguel Ojeda /// holds as well. 133*c3739801SMiguel Ojeda impl<'a, T, I> Copy for Ptr<'a, T, I> 134*c3739801SMiguel Ojeda where 135*c3739801SMiguel Ojeda T: 'a + ?Sized, 136*c3739801SMiguel Ojeda I: Invariants<Aliasing = Shared>, 137*c3739801SMiguel Ojeda { 138*c3739801SMiguel Ojeda } 139*c3739801SMiguel Ojeda 140*c3739801SMiguel Ojeda /// SAFETY: See the safety comment on `Copy`. 141*c3739801SMiguel Ojeda impl<'a, T, I> Clone for Ptr<'a, T, I> 142*c3739801SMiguel Ojeda where 143*c3739801SMiguel Ojeda T: 'a + ?Sized, 144*c3739801SMiguel Ojeda I: Invariants<Aliasing = Shared>, 145*c3739801SMiguel Ojeda { 146*c3739801SMiguel Ojeda #[inline] 147*c3739801SMiguel Ojeda fn clone(&self) -> Self { 148*c3739801SMiguel Ojeda *self 149*c3739801SMiguel Ojeda } 150*c3739801SMiguel Ojeda } 151*c3739801SMiguel Ojeda 152*c3739801SMiguel Ojeda impl<'a, T, I> Debug for Ptr<'a, T, I> 153*c3739801SMiguel Ojeda where 154*c3739801SMiguel Ojeda T: 'a + ?Sized, 155*c3739801SMiguel Ojeda I: Invariants, 156*c3739801SMiguel Ojeda { 157*c3739801SMiguel Ojeda #[inline] 158*c3739801SMiguel Ojeda fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { 159*c3739801SMiguel Ojeda self.as_inner().as_non_null().fmt(f) 160*c3739801SMiguel Ojeda } 161*c3739801SMiguel Ojeda } 162*c3739801SMiguel Ojeda } 163*c3739801SMiguel Ojeda 164*c3739801SMiguel Ojeda /// Methods for converting to and from `Ptr` and Rust's safe reference types. 165*c3739801SMiguel Ojeda mod _conversions { 166*c3739801SMiguel Ojeda use super::*; 167*c3739801SMiguel Ojeda use crate::pointer::cast::{CastExact, CastSized, IdCast}; 168*c3739801SMiguel Ojeda 169*c3739801SMiguel Ojeda /// `&'a T` → `Ptr<'a, T>` 170*c3739801SMiguel Ojeda impl<'a, T> Ptr<'a, T, (Shared, Aligned, Valid)> 171*c3739801SMiguel Ojeda where 172*c3739801SMiguel Ojeda T: 'a + ?Sized, 173*c3739801SMiguel Ojeda { 174*c3739801SMiguel Ojeda /// Constructs a `Ptr` from a shared reference. 175*c3739801SMiguel Ojeda #[inline(always)] 176*c3739801SMiguel Ojeda pub fn from_ref(ptr: &'a T) -> Self { 177*c3739801SMiguel Ojeda let inner = PtrInner::from_ref(ptr); 178*c3739801SMiguel Ojeda // SAFETY: 179*c3739801SMiguel Ojeda // 0. `ptr`, by invariant on `&'a T`, conforms to the aliasing 180*c3739801SMiguel Ojeda // invariant of `Shared`. 181*c3739801SMiguel Ojeda // 1. `ptr`, by invariant on `&'a T`, conforms to the alignment 182*c3739801SMiguel Ojeda // invariant of `Aligned`. 183*c3739801SMiguel Ojeda // 2. `ptr`'s referent, by invariant on `&'a T`, is a bit-valid `T`. 184*c3739801SMiguel Ojeda // This satisfies the requirement that a `Ptr<T, (_, _, Valid)>` 185*c3739801SMiguel Ojeda // point to a bit-valid `T`. Even if `T` permits interior 186*c3739801SMiguel Ojeda // mutation, this invariant guarantees that the returned `Ptr` 187*c3739801SMiguel Ojeda // can only ever be used to modify the referent to store 188*c3739801SMiguel Ojeda // bit-valid `T`s, which ensures that the returned `Ptr` cannot 189*c3739801SMiguel Ojeda // be used to violate the soundness of the original `ptr: &'a T` 190*c3739801SMiguel Ojeda // or of any other references that may exist to the same 191*c3739801SMiguel Ojeda // referent. 192*c3739801SMiguel Ojeda unsafe { Self::from_inner(inner) } 193*c3739801SMiguel Ojeda } 194*c3739801SMiguel Ojeda } 195*c3739801SMiguel Ojeda 196*c3739801SMiguel Ojeda /// `&'a mut T` → `Ptr<'a, T>` 197*c3739801SMiguel Ojeda impl<'a, T> Ptr<'a, T, (Exclusive, Aligned, Valid)> 198*c3739801SMiguel Ojeda where 199*c3739801SMiguel Ojeda T: 'a + ?Sized, 200*c3739801SMiguel Ojeda { 201*c3739801SMiguel Ojeda /// Constructs a `Ptr` from an exclusive reference. 202*c3739801SMiguel Ojeda #[inline(always)] 203*c3739801SMiguel Ojeda pub fn from_mut(ptr: &'a mut T) -> Self { 204*c3739801SMiguel Ojeda let inner = PtrInner::from_mut(ptr); 205*c3739801SMiguel Ojeda // SAFETY: 206*c3739801SMiguel Ojeda // 0. `ptr`, by invariant on `&'a mut T`, conforms to the aliasing 207*c3739801SMiguel Ojeda // invariant of `Exclusive`. 208*c3739801SMiguel Ojeda // 1. `ptr`, by invariant on `&'a mut T`, conforms to the alignment 209*c3739801SMiguel Ojeda // invariant of `Aligned`. 210*c3739801SMiguel Ojeda // 2. `ptr`'s referent, by invariant on `&'a mut T`, is a bit-valid 211*c3739801SMiguel Ojeda // `T`. This satisfies the requirement that a `Ptr<T, (_, _, 212*c3739801SMiguel Ojeda // Valid)>` point to a bit-valid `T`. This invariant guarantees 213*c3739801SMiguel Ojeda // that the returned `Ptr` can only ever be used to modify the 214*c3739801SMiguel Ojeda // referent to store bit-valid `T`s, which ensures that the 215*c3739801SMiguel Ojeda // returned `Ptr` cannot be used to violate the soundness of the 216*c3739801SMiguel Ojeda // original `ptr: &'a mut T`. 217*c3739801SMiguel Ojeda unsafe { Self::from_inner(inner) } 218*c3739801SMiguel Ojeda } 219*c3739801SMiguel Ojeda } 220*c3739801SMiguel Ojeda 221*c3739801SMiguel Ojeda /// `Ptr<'a, T>` → `&'a T` 222*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 223*c3739801SMiguel Ojeda where 224*c3739801SMiguel Ojeda T: 'a + ?Sized, 225*c3739801SMiguel Ojeda I: Invariants<Alignment = Aligned, Validity = Valid>, 226*c3739801SMiguel Ojeda I::Aliasing: Reference, 227*c3739801SMiguel Ojeda { 228*c3739801SMiguel Ojeda /// Converts `self` to a shared reference. 229*c3739801SMiguel Ojeda // This consumes `self`, not `&self`, because `self` is, logically, a 230*c3739801SMiguel Ojeda // pointer. For `I::Aliasing = invariant::Shared`, `Self: Copy`, and so 231*c3739801SMiguel Ojeda // this doesn't prevent the caller from still using the pointer after 232*c3739801SMiguel Ojeda // calling `as_ref`. 233*c3739801SMiguel Ojeda #[allow(clippy::wrong_self_convention)] 234*c3739801SMiguel Ojeda #[inline] 235*c3739801SMiguel Ojeda #[must_use] 236*c3739801SMiguel Ojeda pub fn as_ref(self) -> &'a T { 237*c3739801SMiguel Ojeda let raw = self.as_inner().as_non_null(); 238*c3739801SMiguel Ojeda // SAFETY: `self` satisfies the `Aligned` invariant, so we know that 239*c3739801SMiguel Ojeda // `raw` is validly-aligned for `T`. 240*c3739801SMiguel Ojeda #[cfg(miri)] 241*c3739801SMiguel Ojeda unsafe { 242*c3739801SMiguel Ojeda crate::util::miri_promise_symbolic_alignment( 243*c3739801SMiguel Ojeda raw.as_ptr().cast(), 244*c3739801SMiguel Ojeda core::mem::align_of_val_raw(raw.as_ptr()), 245*c3739801SMiguel Ojeda ); 246*c3739801SMiguel Ojeda } 247*c3739801SMiguel Ojeda // SAFETY: This invocation of `NonNull::as_ref` satisfies its 248*c3739801SMiguel Ojeda // documented safety preconditions: 249*c3739801SMiguel Ojeda // 250*c3739801SMiguel Ojeda // 1. The pointer is properly aligned. This is ensured by-contract 251*c3739801SMiguel Ojeda // on `Ptr`, because the `I::Alignment` is `Aligned`. 252*c3739801SMiguel Ojeda // 253*c3739801SMiguel Ojeda // 2. If the pointer's referent is not zero-sized, then the pointer 254*c3739801SMiguel Ojeda // must be “dereferenceable” in the sense defined in the module 255*c3739801SMiguel Ojeda // documentation; i.e.: 256*c3739801SMiguel Ojeda // 257*c3739801SMiguel Ojeda // > The memory range of the given size starting at the pointer 258*c3739801SMiguel Ojeda // > must all be within the bounds of a single allocated object. 259*c3739801SMiguel Ojeda // > [2] 260*c3739801SMiguel Ojeda // 261*c3739801SMiguel Ojeda // This is ensured by contract on all `PtrInner`s. 262*c3739801SMiguel Ojeda // 263*c3739801SMiguel Ojeda // 3. The pointer must point to a validly-initialized instance of 264*c3739801SMiguel Ojeda // `T`. This is ensured by-contract on `Ptr`, because the 265*c3739801SMiguel Ojeda // `I::Validity` is `Valid`. 266*c3739801SMiguel Ojeda // 267*c3739801SMiguel Ojeda // 4. You must enforce Rust’s aliasing rules. This is ensured by 268*c3739801SMiguel Ojeda // contract on `Ptr`, because `I::Aliasing: Reference`. Either it 269*c3739801SMiguel Ojeda // is `Shared` or `Exclusive`. If it is `Shared`, other 270*c3739801SMiguel Ojeda // references may not mutate the referent outside of 271*c3739801SMiguel Ojeda // `UnsafeCell`s. 272*c3739801SMiguel Ojeda // 273*c3739801SMiguel Ojeda // [1]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_ref 274*c3739801SMiguel Ojeda // [2]: https://doc.rust-lang.org/std/ptr/index.html#safety 275*c3739801SMiguel Ojeda unsafe { raw.as_ref() } 276*c3739801SMiguel Ojeda } 277*c3739801SMiguel Ojeda } 278*c3739801SMiguel Ojeda 279*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 280*c3739801SMiguel Ojeda where 281*c3739801SMiguel Ojeda T: 'a + ?Sized, 282*c3739801SMiguel Ojeda I: Invariants, 283*c3739801SMiguel Ojeda I::Aliasing: Reference, 284*c3739801SMiguel Ojeda { 285*c3739801SMiguel Ojeda /// Reborrows `self`, producing another `Ptr`. 286*c3739801SMiguel Ojeda /// 287*c3739801SMiguel Ojeda /// Since `self` is borrowed mutably, this prevents any methods from 288*c3739801SMiguel Ojeda /// being called on `self` as long as the returned `Ptr` exists. 289*c3739801SMiguel Ojeda #[inline] 290*c3739801SMiguel Ojeda #[must_use] 291*c3739801SMiguel Ojeda #[allow(clippy::needless_lifetimes)] // Allows us to name the lifetime in the safety comment below. 292*c3739801SMiguel Ojeda pub fn reborrow<'b>(&'b mut self) -> Ptr<'b, T, I> 293*c3739801SMiguel Ojeda where 294*c3739801SMiguel Ojeda 'a: 'b, 295*c3739801SMiguel Ojeda { 296*c3739801SMiguel Ojeda // SAFETY: The following all hold by invariant on `self`, and thus 297*c3739801SMiguel Ojeda // hold of `ptr = self.as_inner()`: 298*c3739801SMiguel Ojeda // 0. SEE BELOW. 299*c3739801SMiguel Ojeda // 1. `ptr` conforms to the alignment invariant of 300*c3739801SMiguel Ojeda // [`I::Alignment`](invariant::Alignment). 301*c3739801SMiguel Ojeda // 2. `ptr` conforms to the validity invariant of 302*c3739801SMiguel Ojeda // [`I::Validity`](invariant::Validity). `self` and the returned 303*c3739801SMiguel Ojeda // `Ptr` permit the same bit values in their referents since they 304*c3739801SMiguel Ojeda // have the same referent type (`T`) and the same validity 305*c3739801SMiguel Ojeda // (`I::Validity`). Thus, regardless of what mutation is 306*c3739801SMiguel Ojeda // permitted (`Exclusive` aliasing or `Shared`-aliased interior 307*c3739801SMiguel Ojeda // mutation), neither can be used to write a value to the 308*c3739801SMiguel Ojeda // referent which violates the other's validity invariant. 309*c3739801SMiguel Ojeda // 310*c3739801SMiguel Ojeda // For aliasing (0 above), since `I::Aliasing: Reference`, 311*c3739801SMiguel Ojeda // there are two cases for `I::Aliasing`: 312*c3739801SMiguel Ojeda // - For `invariant::Shared`: `'a` outlives `'b`, and so the 313*c3739801SMiguel Ojeda // returned `Ptr` does not permit accessing the referent any 314*c3739801SMiguel Ojeda // longer than is possible via `self`. For shared aliasing, it is 315*c3739801SMiguel Ojeda // sound for multiple `Ptr`s to exist simultaneously which 316*c3739801SMiguel Ojeda // reference the same memory, so creating a new one is not 317*c3739801SMiguel Ojeda // problematic. 318*c3739801SMiguel Ojeda // - For `invariant::Exclusive`: Since `self` is `&'b mut` and we 319*c3739801SMiguel Ojeda // return a `Ptr` with lifetime `'b`, `self` is inaccessible to 320*c3739801SMiguel Ojeda // the caller for the lifetime `'b` - in other words, `self` is 321*c3739801SMiguel Ojeda // inaccessible to the caller as long as the returned `Ptr` 322*c3739801SMiguel Ojeda // exists. Since `self` is an exclusive `Ptr`, no other live 323*c3739801SMiguel Ojeda // references or `Ptr`s may exist which refer to the same memory 324*c3739801SMiguel Ojeda // while `self` is live. Thus, as long as the returned `Ptr` 325*c3739801SMiguel Ojeda // exists, no other references or `Ptr`s which refer to the same 326*c3739801SMiguel Ojeda // memory may be live. 327*c3739801SMiguel Ojeda unsafe { Ptr::from_inner(self.as_inner()) } 328*c3739801SMiguel Ojeda } 329*c3739801SMiguel Ojeda 330*c3739801SMiguel Ojeda /// Reborrows `self` as shared, producing another `Ptr` with `Shared` 331*c3739801SMiguel Ojeda /// aliasing. 332*c3739801SMiguel Ojeda /// 333*c3739801SMiguel Ojeda /// Since `self` is borrowed mutably, this prevents any methods from 334*c3739801SMiguel Ojeda /// being called on `self` as long as the returned `Ptr` exists. 335*c3739801SMiguel Ojeda #[inline] 336*c3739801SMiguel Ojeda #[must_use] 337*c3739801SMiguel Ojeda #[allow(clippy::needless_lifetimes)] // Allows us to name the lifetime in the safety comment below. 338*c3739801SMiguel Ojeda pub fn reborrow_shared<'b>(&'b mut self) -> Ptr<'b, T, (Shared, I::Alignment, I::Validity)> 339*c3739801SMiguel Ojeda where 340*c3739801SMiguel Ojeda 'a: 'b, 341*c3739801SMiguel Ojeda { 342*c3739801SMiguel Ojeda // SAFETY: The following all hold by invariant on `self`, and thus 343*c3739801SMiguel Ojeda // hold of `ptr = self.as_inner()`: 344*c3739801SMiguel Ojeda // 0. SEE BELOW. 345*c3739801SMiguel Ojeda // 1. `ptr` conforms to the alignment invariant of 346*c3739801SMiguel Ojeda // [`I::Alignment`](invariant::Alignment). 347*c3739801SMiguel Ojeda // 2. `ptr` conforms to the validity invariant of 348*c3739801SMiguel Ojeda // [`I::Validity`](invariant::Validity). `self` and the returned 349*c3739801SMiguel Ojeda // `Ptr` permit the same bit values in their referents since they 350*c3739801SMiguel Ojeda // have the same referent type (`T`) and the same validity 351*c3739801SMiguel Ojeda // (`I::Validity`). Thus, regardless of what mutation is 352*c3739801SMiguel Ojeda // permitted (`Exclusive` aliasing or `Shared`-aliased interior 353*c3739801SMiguel Ojeda // mutation), neither can be used to write a value to the 354*c3739801SMiguel Ojeda // referent which violates the other's validity invariant. 355*c3739801SMiguel Ojeda // 356*c3739801SMiguel Ojeda // For aliasing (0 above), since `I::Aliasing: Reference`, 357*c3739801SMiguel Ojeda // there are two cases for `I::Aliasing`: 358*c3739801SMiguel Ojeda // - For `invariant::Shared`: `'a` outlives `'b`, and so the 359*c3739801SMiguel Ojeda // returned `Ptr` does not permit accessing the referent any 360*c3739801SMiguel Ojeda // longer than is possible via `self`. For shared aliasing, it is 361*c3739801SMiguel Ojeda // sound for multiple `Ptr`s to exist simultaneously which 362*c3739801SMiguel Ojeda // reference the same memory, so creating a new one is not 363*c3739801SMiguel Ojeda // problematic. 364*c3739801SMiguel Ojeda // - For `invariant::Exclusive`: Since `self` is `&'b mut` and we 365*c3739801SMiguel Ojeda // return a `Ptr` with lifetime `'b`, `self` is inaccessible to 366*c3739801SMiguel Ojeda // the caller for the lifetime `'b` - in other words, `self` is 367*c3739801SMiguel Ojeda // inaccessible to the caller as long as the returned `Ptr` 368*c3739801SMiguel Ojeda // exists. Since `self` is an exclusive `Ptr`, no other live 369*c3739801SMiguel Ojeda // references or `Ptr`s may exist which refer to the same memory 370*c3739801SMiguel Ojeda // while `self` is live. Thus, as long as the returned `Ptr` 371*c3739801SMiguel Ojeda // exists, no other references or `Ptr`s which refer to the same 372*c3739801SMiguel Ojeda // memory may be live. 373*c3739801SMiguel Ojeda unsafe { Ptr::from_inner(self.as_inner()) } 374*c3739801SMiguel Ojeda } 375*c3739801SMiguel Ojeda } 376*c3739801SMiguel Ojeda 377*c3739801SMiguel Ojeda /// `Ptr<'a, T>` → `&'a mut T` 378*c3739801SMiguel Ojeda impl<'a, T> Ptr<'a, T, (Exclusive, Aligned, Valid)> 379*c3739801SMiguel Ojeda where 380*c3739801SMiguel Ojeda T: 'a + ?Sized, 381*c3739801SMiguel Ojeda { 382*c3739801SMiguel Ojeda /// Converts `self` to a mutable reference. 383*c3739801SMiguel Ojeda #[allow(clippy::wrong_self_convention)] 384*c3739801SMiguel Ojeda #[inline] 385*c3739801SMiguel Ojeda #[must_use] 386*c3739801SMiguel Ojeda pub fn as_mut(self) -> &'a mut T { 387*c3739801SMiguel Ojeda let mut raw = self.as_inner().as_non_null(); 388*c3739801SMiguel Ojeda // SAFETY: `self` satisfies the `Aligned` invariant, so we know that 389*c3739801SMiguel Ojeda // `raw` is validly-aligned for `T`. 390*c3739801SMiguel Ojeda #[cfg(miri)] 391*c3739801SMiguel Ojeda unsafe { 392*c3739801SMiguel Ojeda crate::util::miri_promise_symbolic_alignment( 393*c3739801SMiguel Ojeda raw.as_ptr().cast(), 394*c3739801SMiguel Ojeda core::mem::align_of_val_raw(raw.as_ptr()), 395*c3739801SMiguel Ojeda ); 396*c3739801SMiguel Ojeda } 397*c3739801SMiguel Ojeda // SAFETY: This invocation of `NonNull::as_mut` satisfies its 398*c3739801SMiguel Ojeda // documented safety preconditions: 399*c3739801SMiguel Ojeda // 400*c3739801SMiguel Ojeda // 1. The pointer is properly aligned. This is ensured by-contract 401*c3739801SMiguel Ojeda // on `Ptr`, because the `ALIGNMENT_INVARIANT` is `Aligned`. 402*c3739801SMiguel Ojeda // 403*c3739801SMiguel Ojeda // 2. If the pointer's referent is not zero-sized, then the pointer 404*c3739801SMiguel Ojeda // must be “dereferenceable” in the sense defined in the module 405*c3739801SMiguel Ojeda // documentation; i.e.: 406*c3739801SMiguel Ojeda // 407*c3739801SMiguel Ojeda // > The memory range of the given size starting at the pointer 408*c3739801SMiguel Ojeda // > must all be within the bounds of a single allocated object. 409*c3739801SMiguel Ojeda // > [2] 410*c3739801SMiguel Ojeda // 411*c3739801SMiguel Ojeda // This is ensured by contract on all `PtrInner`s. 412*c3739801SMiguel Ojeda // 413*c3739801SMiguel Ojeda // 3. The pointer must point to a validly-initialized instance of 414*c3739801SMiguel Ojeda // `T`. This is ensured by-contract on `Ptr`, because the 415*c3739801SMiguel Ojeda // validity invariant is `Valid`. 416*c3739801SMiguel Ojeda // 417*c3739801SMiguel Ojeda // 4. You must enforce Rust’s aliasing rules. This is ensured by 418*c3739801SMiguel Ojeda // contract on `Ptr`, because the `ALIASING_INVARIANT` is 419*c3739801SMiguel Ojeda // `Exclusive`. 420*c3739801SMiguel Ojeda // 421*c3739801SMiguel Ojeda // [1]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_mut 422*c3739801SMiguel Ojeda // [2]: https://doc.rust-lang.org/std/ptr/index.html#safety 423*c3739801SMiguel Ojeda unsafe { raw.as_mut() } 424*c3739801SMiguel Ojeda } 425*c3739801SMiguel Ojeda } 426*c3739801SMiguel Ojeda 427*c3739801SMiguel Ojeda /// `Ptr<'a, T>` → `Ptr<'a, U>` 428*c3739801SMiguel Ojeda impl<'a, T: ?Sized, I> Ptr<'a, T, I> 429*c3739801SMiguel Ojeda where 430*c3739801SMiguel Ojeda I: Invariants, 431*c3739801SMiguel Ojeda { 432*c3739801SMiguel Ojeda #[must_use] 433*c3739801SMiguel Ojeda #[inline(always)] 434*c3739801SMiguel Ojeda pub fn transmute<U, V, R>(self) -> Ptr<'a, U, (I::Aliasing, Unaligned, V)> 435*c3739801SMiguel Ojeda where 436*c3739801SMiguel Ojeda V: Validity, 437*c3739801SMiguel Ojeda U: TransmuteFromPtr<T, I::Aliasing, I::Validity, V, <U as SizeEq<T>>::CastFrom, R> 438*c3739801SMiguel Ojeda + SizeEq<T> 439*c3739801SMiguel Ojeda + ?Sized, 440*c3739801SMiguel Ojeda { 441*c3739801SMiguel Ojeda self.transmute_with::<U, V, <U as SizeEq<T>>::CastFrom, R>() 442*c3739801SMiguel Ojeda } 443*c3739801SMiguel Ojeda 444*c3739801SMiguel Ojeda #[inline] 445*c3739801SMiguel Ojeda #[must_use] 446*c3739801SMiguel Ojeda pub fn transmute_with<U, V, C, R>(self) -> Ptr<'a, U, (I::Aliasing, Unaligned, V)> 447*c3739801SMiguel Ojeda where 448*c3739801SMiguel Ojeda V: Validity, 449*c3739801SMiguel Ojeda U: TransmuteFromPtr<T, I::Aliasing, I::Validity, V, C, R> + ?Sized, 450*c3739801SMiguel Ojeda C: CastExact<T, U>, 451*c3739801SMiguel Ojeda { 452*c3739801SMiguel Ojeda // SAFETY: 453*c3739801SMiguel Ojeda // - By `C: CastExact`, `C` preserves referent address, and so we 454*c3739801SMiguel Ojeda // don't need to consider projections in the following safety 455*c3739801SMiguel Ojeda // arguments. 456*c3739801SMiguel Ojeda // - If aliasing is `Shared`, then by `U: TransmuteFromPtr<T>`, at 457*c3739801SMiguel Ojeda // least one of the following holds: 458*c3739801SMiguel Ojeda // - `T: Immutable` and `U: Immutable`, in which case it is 459*c3739801SMiguel Ojeda // trivially sound for shared code to operate on a `&T` and `&U` 460*c3739801SMiguel Ojeda // at the same time, as neither can perform interior mutation 461*c3739801SMiguel Ojeda // - It is directly guaranteed that it is sound for shared code to 462*c3739801SMiguel Ojeda // operate on these references simultaneously 463*c3739801SMiguel Ojeda // - By `U: TransmuteFromPtr<T, I::Aliasing, I::Validity, C, V>`, it 464*c3739801SMiguel Ojeda // is sound to perform this transmute using `C`. 465*c3739801SMiguel Ojeda unsafe { self.project_transmute_unchecked::<_, _, C>() } 466*c3739801SMiguel Ojeda } 467*c3739801SMiguel Ojeda 468*c3739801SMiguel Ojeda #[inline] 469*c3739801SMiguel Ojeda #[must_use] 470*c3739801SMiguel Ojeda pub fn recall_validity<V, R>(self) -> Ptr<'a, T, (I::Aliasing, I::Alignment, V)> 471*c3739801SMiguel Ojeda where 472*c3739801SMiguel Ojeda V: Validity, 473*c3739801SMiguel Ojeda T: TransmuteFromPtr<T, I::Aliasing, I::Validity, V, IdCast, R>, 474*c3739801SMiguel Ojeda { 475*c3739801SMiguel Ojeda let ptr = self.transmute_with::<T, V, IdCast, R>(); 476*c3739801SMiguel Ojeda // SAFETY: `self` and `ptr` have the same address and referent type. 477*c3739801SMiguel Ojeda // Therefore, if `self` satisfies `I::Alignment`, then so does 478*c3739801SMiguel Ojeda // `ptr`. 479*c3739801SMiguel Ojeda unsafe { ptr.assume_alignment::<I::Alignment>() } 480*c3739801SMiguel Ojeda } 481*c3739801SMiguel Ojeda 482*c3739801SMiguel Ojeda /// Projects and/or transmutes to a different (unsized) referent type 483*c3739801SMiguel Ojeda /// without checking interior mutability. 484*c3739801SMiguel Ojeda /// 485*c3739801SMiguel Ojeda /// Callers should prefer [`cast`] or [`project`] where possible. 486*c3739801SMiguel Ojeda /// 487*c3739801SMiguel Ojeda /// [`cast`]: Ptr::cast 488*c3739801SMiguel Ojeda /// [`project`]: Ptr::project 489*c3739801SMiguel Ojeda /// 490*c3739801SMiguel Ojeda /// # Safety 491*c3739801SMiguel Ojeda /// 492*c3739801SMiguel Ojeda /// The caller promises that: 493*c3739801SMiguel Ojeda /// - If `I::Aliasing` is [`Shared`], it must not be possible for safe 494*c3739801SMiguel Ojeda /// code, operating on a `&T` and `&U`, with the referents of `self` 495*c3739801SMiguel Ojeda /// and `self.project_transmute_unchecked()`, respectively, to cause 496*c3739801SMiguel Ojeda /// undefined behavior. 497*c3739801SMiguel Ojeda /// - It is sound to project and/or transmute a pointer of type `T` with 498*c3739801SMiguel Ojeda /// aliasing `I::Aliasing` and validity `I::Validity` to a pointer of 499*c3739801SMiguel Ojeda /// type `U` with aliasing `I::Aliasing` and validity `V`. This is a 500*c3739801SMiguel Ojeda /// subtle soundness requirement that is a function of `T`, `U`, 501*c3739801SMiguel Ojeda /// `I::Aliasing`, `I::Validity`, and `V`, and may depend upon the 502*c3739801SMiguel Ojeda /// presence, absence, or specific location of `UnsafeCell`s in `T` 503*c3739801SMiguel Ojeda /// and/or `U`, and on whether interior mutation is ever permitted via 504*c3739801SMiguel Ojeda /// those `UnsafeCell`s. See [`Validity`] for more details. 505*c3739801SMiguel Ojeda #[inline] 506*c3739801SMiguel Ojeda #[must_use] 507*c3739801SMiguel Ojeda pub unsafe fn project_transmute_unchecked<U: ?Sized, V, P>( 508*c3739801SMiguel Ojeda self, 509*c3739801SMiguel Ojeda ) -> Ptr<'a, U, (I::Aliasing, Unaligned, V)> 510*c3739801SMiguel Ojeda where 511*c3739801SMiguel Ojeda V: Validity, 512*c3739801SMiguel Ojeda P: crate::pointer::cast::Project<T, U>, 513*c3739801SMiguel Ojeda { 514*c3739801SMiguel Ojeda let ptr = self.as_inner().project::<_, P>(); 515*c3739801SMiguel Ojeda 516*c3739801SMiguel Ojeda // SAFETY: 517*c3739801SMiguel Ojeda // 518*c3739801SMiguel Ojeda // The following safety arguments rely on the fact that `P: Project` 519*c3739801SMiguel Ojeda // guarantees that `P` is a referent-preserving or -shrinking 520*c3739801SMiguel Ojeda // projection. Thus, `ptr` addresses a subset of the bytes of 521*c3739801SMiguel Ojeda // `*self`, and so certain properties that hold of `*self` also hold 522*c3739801SMiguel Ojeda // of `*ptr`. 523*c3739801SMiguel Ojeda // 524*c3739801SMiguel Ojeda // 0. `ptr` conforms to the aliasing invariant of `I::Aliasing`: 525*c3739801SMiguel Ojeda // - `Exclusive`: `self` is the only `Ptr` or reference which is 526*c3739801SMiguel Ojeda // permitted to read or modify the referent for the lifetime 527*c3739801SMiguel Ojeda // `'a`. Since we consume `self` by value, the returned pointer 528*c3739801SMiguel Ojeda // remains the only `Ptr` or reference which is permitted to 529*c3739801SMiguel Ojeda // read or modify the referent for the lifetime `'a`. 530*c3739801SMiguel Ojeda // - `Shared`: Since `self` has aliasing `Shared`, we know that 531*c3739801SMiguel Ojeda // no other code may mutate the referent during the lifetime 532*c3739801SMiguel Ojeda // `'a`, except via `UnsafeCell`s, and except as permitted by 533*c3739801SMiguel Ojeda // `T`'s library safety invariants. The caller promises that 534*c3739801SMiguel Ojeda // any safe operations which can be permitted on a `&T` and a 535*c3739801SMiguel Ojeda // `&U` simultaneously must be sound. Thus, no operations on a 536*c3739801SMiguel Ojeda // `&U` could violate `&T`'s library safety invariants, and 537*c3739801SMiguel Ojeda // vice-versa. Since any mutation via shared references outside 538*c3739801SMiguel Ojeda // of `UnsafeCell`s is unsound, this must be impossible using 539*c3739801SMiguel Ojeda // `&T` and `&U`. 540*c3739801SMiguel Ojeda // - `Inaccessible`: There are no restrictions we need to uphold. 541*c3739801SMiguel Ojeda // 1. `ptr` trivially satisfies the alignment invariant `Unaligned`. 542*c3739801SMiguel Ojeda // 2. The caller promises that the returned pointer satisfies the 543*c3739801SMiguel Ojeda // validity invariant `V` with respect to its referent type, `U`. 544*c3739801SMiguel Ojeda unsafe { Ptr::from_inner(ptr) } 545*c3739801SMiguel Ojeda } 546*c3739801SMiguel Ojeda } 547*c3739801SMiguel Ojeda 548*c3739801SMiguel Ojeda /// `Ptr<'a, T, (_, _, _)>` → `Ptr<'a, Unalign<T>, (_, Aligned, _)>` 549*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 550*c3739801SMiguel Ojeda where 551*c3739801SMiguel Ojeda I: Invariants, 552*c3739801SMiguel Ojeda { 553*c3739801SMiguel Ojeda /// Converts a `Ptr` an unaligned `T` into a `Ptr` to an aligned 554*c3739801SMiguel Ojeda /// `Unalign<T>`. 555*c3739801SMiguel Ojeda #[inline] 556*c3739801SMiguel Ojeda #[must_use] 557*c3739801SMiguel Ojeda pub fn into_unalign( 558*c3739801SMiguel Ojeda self, 559*c3739801SMiguel Ojeda ) -> Ptr<'a, crate::Unalign<T>, (I::Aliasing, Aligned, I::Validity)> { 560*c3739801SMiguel Ojeda // FIXME(#1359): This should be a `transmute_with` call. 561*c3739801SMiguel Ojeda // Unfortunately, to avoid blanket impl conflicts, we only implement 562*c3739801SMiguel Ojeda // `TransmuteFrom<T>` for `Unalign<T>` (and vice versa) specifically 563*c3739801SMiguel Ojeda // for `Valid` validity, not for all validity types. 564*c3739801SMiguel Ojeda 565*c3739801SMiguel Ojeda // SAFETY: 566*c3739801SMiguel Ojeda // - By `CastSized: Cast`, `CastSized` preserves referent address, 567*c3739801SMiguel Ojeda // and so we don't need to consider projections in the following 568*c3739801SMiguel Ojeda // safety arguments. 569*c3739801SMiguel Ojeda // - Since `Unalign<T>` has the same layout as `T`, the returned 570*c3739801SMiguel Ojeda // pointer refers to `UnsafeCell`s at the same locations as 571*c3739801SMiguel Ojeda // `self`. 572*c3739801SMiguel Ojeda // - `Unalign<T>` promises to have the same bit validity as `T`. By 573*c3739801SMiguel Ojeda // invariant on `Validity`, the set of bit patterns allowed in the 574*c3739801SMiguel Ojeda // referent of a `Ptr<X, (_, _, V)>` is only a function of the 575*c3739801SMiguel Ojeda // validity of `X` and of `V`. Thus, the set of bit patterns 576*c3739801SMiguel Ojeda // allowed in the referent of a `Ptr<T, (_, _, I::Validity)>` is 577*c3739801SMiguel Ojeda // the same as the set of bit patterns allowed in the referent of 578*c3739801SMiguel Ojeda // a `Ptr<Unalign<T>, (_, _, I::Validity)>`. As a result, `self` 579*c3739801SMiguel Ojeda // and the returned `Ptr` permit the same set of bit patterns in 580*c3739801SMiguel Ojeda // their referents, and so neither can be used to violate the 581*c3739801SMiguel Ojeda // validity of the other. 582*c3739801SMiguel Ojeda let ptr = unsafe { self.project_transmute_unchecked::<_, _, CastSized>() }; 583*c3739801SMiguel Ojeda ptr.bikeshed_recall_aligned() 584*c3739801SMiguel Ojeda } 585*c3739801SMiguel Ojeda } 586*c3739801SMiguel Ojeda 587*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 588*c3739801SMiguel Ojeda where 589*c3739801SMiguel Ojeda T: ?Sized, 590*c3739801SMiguel Ojeda I: Invariants<Validity = Valid>, 591*c3739801SMiguel Ojeda I::Aliasing: Reference, 592*c3739801SMiguel Ojeda { 593*c3739801SMiguel Ojeda /// Reads the referent. 594*c3739801SMiguel Ojeda #[must_use] 595*c3739801SMiguel Ojeda #[inline(always)] 596*c3739801SMiguel Ojeda pub fn read<R>(self) -> T 597*c3739801SMiguel Ojeda where 598*c3739801SMiguel Ojeda T: Copy, 599*c3739801SMiguel Ojeda T: Read<I::Aliasing, R>, 600*c3739801SMiguel Ojeda { 601*c3739801SMiguel Ojeda <I::Alignment as Alignment>::read(self) 602*c3739801SMiguel Ojeda } 603*c3739801SMiguel Ojeda 604*c3739801SMiguel Ojeda /// Views the value as an aligned reference. 605*c3739801SMiguel Ojeda /// 606*c3739801SMiguel Ojeda /// This is only available if `T` is [`Unaligned`]. 607*c3739801SMiguel Ojeda #[must_use] 608*c3739801SMiguel Ojeda #[inline] 609*c3739801SMiguel Ojeda pub fn unaligned_as_ref(self) -> &'a T 610*c3739801SMiguel Ojeda where 611*c3739801SMiguel Ojeda T: crate::Unaligned, 612*c3739801SMiguel Ojeda { 613*c3739801SMiguel Ojeda self.bikeshed_recall_aligned().as_ref() 614*c3739801SMiguel Ojeda } 615*c3739801SMiguel Ojeda } 616*c3739801SMiguel Ojeda } 617*c3739801SMiguel Ojeda 618*c3739801SMiguel Ojeda /// State transitions between invariants. 619*c3739801SMiguel Ojeda mod _transitions { 620*c3739801SMiguel Ojeda use super::*; 621*c3739801SMiguel Ojeda use crate::{ 622*c3739801SMiguel Ojeda pointer::{cast::IdCast, transmute::TryTransmuteFromPtr}, 623*c3739801SMiguel Ojeda ReadOnly, 624*c3739801SMiguel Ojeda }; 625*c3739801SMiguel Ojeda 626*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 627*c3739801SMiguel Ojeda where 628*c3739801SMiguel Ojeda T: 'a + ?Sized, 629*c3739801SMiguel Ojeda I: Invariants, 630*c3739801SMiguel Ojeda { 631*c3739801SMiguel Ojeda /// Assumes that `self` satisfies the invariants `H`. 632*c3739801SMiguel Ojeda /// 633*c3739801SMiguel Ojeda /// # Safety 634*c3739801SMiguel Ojeda /// 635*c3739801SMiguel Ojeda /// The caller promises that `self` satisfies the invariants `H`. 636*c3739801SMiguel Ojeda unsafe fn assume_invariants<H: Invariants>(self) -> Ptr<'a, T, H> { 637*c3739801SMiguel Ojeda // SAFETY: The caller has promised to satisfy all parameterized 638*c3739801SMiguel Ojeda // invariants of `Ptr`. `Ptr`'s other invariants are satisfied 639*c3739801SMiguel Ojeda // by-contract by the source `Ptr`. 640*c3739801SMiguel Ojeda unsafe { Ptr::from_inner(self.as_inner()) } 641*c3739801SMiguel Ojeda } 642*c3739801SMiguel Ojeda 643*c3739801SMiguel Ojeda /// Helps the type system unify two distinct invariant types which are 644*c3739801SMiguel Ojeda /// actually the same. 645*c3739801SMiguel Ojeda #[inline] 646*c3739801SMiguel Ojeda #[must_use] 647*c3739801SMiguel Ojeda pub fn unify_invariants< 648*c3739801SMiguel Ojeda H: Invariants<Aliasing = I::Aliasing, Alignment = I::Alignment, Validity = I::Validity>, 649*c3739801SMiguel Ojeda >( 650*c3739801SMiguel Ojeda self, 651*c3739801SMiguel Ojeda ) -> Ptr<'a, T, H> { 652*c3739801SMiguel Ojeda // SAFETY: The associated type bounds on `H` ensure that the 653*c3739801SMiguel Ojeda // invariants are unchanged. 654*c3739801SMiguel Ojeda unsafe { self.assume_invariants::<H>() } 655*c3739801SMiguel Ojeda } 656*c3739801SMiguel Ojeda 657*c3739801SMiguel Ojeda /// Assumes that `self`'s referent is validly-aligned for `T` if 658*c3739801SMiguel Ojeda /// required by `A`. 659*c3739801SMiguel Ojeda /// 660*c3739801SMiguel Ojeda /// # Safety 661*c3739801SMiguel Ojeda /// 662*c3739801SMiguel Ojeda /// The caller promises that `self`'s referent conforms to the alignment 663*c3739801SMiguel Ojeda /// invariant of `T` if required by `A`. 664*c3739801SMiguel Ojeda #[inline] 665*c3739801SMiguel Ojeda pub(crate) unsafe fn assume_alignment<A: Alignment>( 666*c3739801SMiguel Ojeda self, 667*c3739801SMiguel Ojeda ) -> Ptr<'a, T, (I::Aliasing, A, I::Validity)> { 668*c3739801SMiguel Ojeda // SAFETY: The caller promises that `self`'s referent is 669*c3739801SMiguel Ojeda // well-aligned for `T` if required by `A` . 670*c3739801SMiguel Ojeda unsafe { self.assume_invariants() } 671*c3739801SMiguel Ojeda } 672*c3739801SMiguel Ojeda 673*c3739801SMiguel Ojeda /// Checks the `self`'s alignment at runtime, returning an aligned `Ptr` 674*c3739801SMiguel Ojeda /// on success. 675*c3739801SMiguel Ojeda #[inline] 676*c3739801SMiguel Ojeda pub fn try_into_aligned( 677*c3739801SMiguel Ojeda self, 678*c3739801SMiguel Ojeda ) -> Result<Ptr<'a, T, (I::Aliasing, Aligned, I::Validity)>, AlignmentError<Self, T>> 679*c3739801SMiguel Ojeda where 680*c3739801SMiguel Ojeda T: Sized, 681*c3739801SMiguel Ojeda { 682*c3739801SMiguel Ojeda if let Err(err) = 683*c3739801SMiguel Ojeda crate::util::validate_aligned_to::<_, T>(self.as_inner().as_non_null()) 684*c3739801SMiguel Ojeda { 685*c3739801SMiguel Ojeda return Err(err.with_src(self)); 686*c3739801SMiguel Ojeda } 687*c3739801SMiguel Ojeda 688*c3739801SMiguel Ojeda // SAFETY: We just checked the alignment. 689*c3739801SMiguel Ojeda Ok(unsafe { self.assume_alignment::<Aligned>() }) 690*c3739801SMiguel Ojeda } 691*c3739801SMiguel Ojeda 692*c3739801SMiguel Ojeda /// Recalls that `self`'s referent is validly-aligned for `T`. 693*c3739801SMiguel Ojeda #[inline] 694*c3739801SMiguel Ojeda // FIXME(#859): Reconsider the name of this method before making it 695*c3739801SMiguel Ojeda // public. 696*c3739801SMiguel Ojeda #[must_use] 697*c3739801SMiguel Ojeda pub fn bikeshed_recall_aligned(self) -> Ptr<'a, T, (I::Aliasing, Aligned, I::Validity)> 698*c3739801SMiguel Ojeda where 699*c3739801SMiguel Ojeda T: crate::Unaligned, 700*c3739801SMiguel Ojeda { 701*c3739801SMiguel Ojeda // SAFETY: The bound `T: Unaligned` ensures that `T` has no 702*c3739801SMiguel Ojeda // non-trivial alignment requirement. 703*c3739801SMiguel Ojeda unsafe { self.assume_alignment::<Aligned>() } 704*c3739801SMiguel Ojeda } 705*c3739801SMiguel Ojeda 706*c3739801SMiguel Ojeda /// Assumes that `self`'s referent conforms to the validity requirement 707*c3739801SMiguel Ojeda /// of `V`. 708*c3739801SMiguel Ojeda /// 709*c3739801SMiguel Ojeda /// # Safety 710*c3739801SMiguel Ojeda /// 711*c3739801SMiguel Ojeda /// The caller promises that `self`'s referent conforms to the validity 712*c3739801SMiguel Ojeda /// requirement of `V`. 713*c3739801SMiguel Ojeda #[must_use] 714*c3739801SMiguel Ojeda #[inline] 715*c3739801SMiguel Ojeda pub unsafe fn assume_validity<V: Validity>( 716*c3739801SMiguel Ojeda self, 717*c3739801SMiguel Ojeda ) -> Ptr<'a, T, (I::Aliasing, I::Alignment, V)> { 718*c3739801SMiguel Ojeda // SAFETY: The caller promises that `self`'s referent conforms to 719*c3739801SMiguel Ojeda // the validity requirement of `V`. 720*c3739801SMiguel Ojeda unsafe { self.assume_invariants() } 721*c3739801SMiguel Ojeda } 722*c3739801SMiguel Ojeda 723*c3739801SMiguel Ojeda /// A shorthand for `self.assume_validity<invariant::Initialized>()`. 724*c3739801SMiguel Ojeda /// 725*c3739801SMiguel Ojeda /// # Safety 726*c3739801SMiguel Ojeda /// 727*c3739801SMiguel Ojeda /// The caller promises to uphold the safety preconditions of 728*c3739801SMiguel Ojeda /// `self.assume_validity<invariant::Initialized>()`. 729*c3739801SMiguel Ojeda #[must_use] 730*c3739801SMiguel Ojeda #[inline] 731*c3739801SMiguel Ojeda pub unsafe fn assume_initialized( 732*c3739801SMiguel Ojeda self, 733*c3739801SMiguel Ojeda ) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Initialized)> { 734*c3739801SMiguel Ojeda // SAFETY: The caller has promised to uphold the safety 735*c3739801SMiguel Ojeda // preconditions. 736*c3739801SMiguel Ojeda unsafe { self.assume_validity::<Initialized>() } 737*c3739801SMiguel Ojeda } 738*c3739801SMiguel Ojeda 739*c3739801SMiguel Ojeda /// A shorthand for `self.assume_validity<Valid>()`. 740*c3739801SMiguel Ojeda /// 741*c3739801SMiguel Ojeda /// # Safety 742*c3739801SMiguel Ojeda /// 743*c3739801SMiguel Ojeda /// The caller promises to uphold the safety preconditions of 744*c3739801SMiguel Ojeda /// `self.assume_validity<Valid>()`. 745*c3739801SMiguel Ojeda #[must_use] 746*c3739801SMiguel Ojeda #[inline] 747*c3739801SMiguel Ojeda pub unsafe fn assume_valid(self) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)> { 748*c3739801SMiguel Ojeda // SAFETY: The caller has promised to uphold the safety 749*c3739801SMiguel Ojeda // preconditions. 750*c3739801SMiguel Ojeda unsafe { self.assume_validity::<Valid>() } 751*c3739801SMiguel Ojeda } 752*c3739801SMiguel Ojeda 753*c3739801SMiguel Ojeda /// Checks that `self`'s referent is validly initialized for `T`, 754*c3739801SMiguel Ojeda /// returning a `Ptr` with `Valid` on success. 755*c3739801SMiguel Ojeda /// 756*c3739801SMiguel Ojeda /// # Panics 757*c3739801SMiguel Ojeda /// 758*c3739801SMiguel Ojeda /// This method will panic if 759*c3739801SMiguel Ojeda /// [`T::is_bit_valid`][TryFromBytes::is_bit_valid] panics. 760*c3739801SMiguel Ojeda /// 761*c3739801SMiguel Ojeda /// # Safety 762*c3739801SMiguel Ojeda /// 763*c3739801SMiguel Ojeda /// On error, unsafe code may rely on this method's returned 764*c3739801SMiguel Ojeda /// `ValidityError` containing `self`. 765*c3739801SMiguel Ojeda #[inline] 766*c3739801SMiguel Ojeda pub fn try_into_valid<R, S>( 767*c3739801SMiguel Ojeda mut self, 768*c3739801SMiguel Ojeda ) -> Result<Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)>, ValidityError<Self, T>> 769*c3739801SMiguel Ojeda where 770*c3739801SMiguel Ojeda T: TryFromBytes 771*c3739801SMiguel Ojeda + Read<I::Aliasing, R> 772*c3739801SMiguel Ojeda + TryTransmuteFromPtr<T, I::Aliasing, I::Validity, Valid, IdCast, S>, 773*c3739801SMiguel Ojeda ReadOnly<T>: Read<I::Aliasing, R>, 774*c3739801SMiguel Ojeda I::Aliasing: Reference, 775*c3739801SMiguel Ojeda I: Invariants<Validity = Initialized>, 776*c3739801SMiguel Ojeda { 777*c3739801SMiguel Ojeda // This call may panic. If that happens, it doesn't cause any 778*c3739801SMiguel Ojeda // soundness issues, as we have not generated any invalid state 779*c3739801SMiguel Ojeda // which we need to fix before returning. 780*c3739801SMiguel Ojeda if T::is_bit_valid(self.reborrow().transmute::<_, _, _>().reborrow_shared()) { 781*c3739801SMiguel Ojeda // SAFETY: If `T::is_bit_valid`, code may assume that `self` 782*c3739801SMiguel Ojeda // contains a bit-valid instance of `T`. By `T: 783*c3739801SMiguel Ojeda // TryTransmuteFromPtr<T, I::Aliasing, I::Validity, Valid>`, so 784*c3739801SMiguel Ojeda // long as `self`'s referent conforms to the `Valid` validity 785*c3739801SMiguel Ojeda // for `T` (which we just confirmed), then this transmute is 786*c3739801SMiguel Ojeda // sound. 787*c3739801SMiguel Ojeda Ok(unsafe { self.assume_valid() }) 788*c3739801SMiguel Ojeda } else { 789*c3739801SMiguel Ojeda Err(ValidityError::new(self)) 790*c3739801SMiguel Ojeda } 791*c3739801SMiguel Ojeda } 792*c3739801SMiguel Ojeda 793*c3739801SMiguel Ojeda /// Forgets that `self`'s referent is validly-aligned for `T`. 794*c3739801SMiguel Ojeda #[inline] 795*c3739801SMiguel Ojeda #[must_use] 796*c3739801SMiguel Ojeda pub fn forget_aligned(self) -> Ptr<'a, T, (I::Aliasing, Unaligned, I::Validity)> { 797*c3739801SMiguel Ojeda // SAFETY: `Unaligned` is less restrictive than `Aligned`. 798*c3739801SMiguel Ojeda unsafe { self.assume_invariants() } 799*c3739801SMiguel Ojeda } 800*c3739801SMiguel Ojeda } 801*c3739801SMiguel Ojeda } 802*c3739801SMiguel Ojeda 803*c3739801SMiguel Ojeda /// Casts of the referent type. 804*c3739801SMiguel Ojeda #[cfg_attr(not(zerocopy_unstable_ptr), allow(unreachable_pub))] 805*c3739801SMiguel Ojeda pub use _casts::TryWithError; 806*c3739801SMiguel Ojeda mod _casts { 807*c3739801SMiguel Ojeda use core::cell::UnsafeCell; 808*c3739801SMiguel Ojeda 809*c3739801SMiguel Ojeda use super::*; 810*c3739801SMiguel Ojeda use crate::{ 811*c3739801SMiguel Ojeda pointer::cast::{AsBytesCast, Cast}, 812*c3739801SMiguel Ojeda HasTag, ProjectField, 813*c3739801SMiguel Ojeda }; 814*c3739801SMiguel Ojeda 815*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 816*c3739801SMiguel Ojeda where 817*c3739801SMiguel Ojeda T: 'a + ?Sized, 818*c3739801SMiguel Ojeda I: Invariants, 819*c3739801SMiguel Ojeda { 820*c3739801SMiguel Ojeda /// Casts to a different referent type without checking interior 821*c3739801SMiguel Ojeda /// mutability. 822*c3739801SMiguel Ojeda /// 823*c3739801SMiguel Ojeda /// Callers should prefer [`cast`][Ptr::cast] where possible. 824*c3739801SMiguel Ojeda /// 825*c3739801SMiguel Ojeda /// # Safety 826*c3739801SMiguel Ojeda /// 827*c3739801SMiguel Ojeda /// If `I::Aliasing` is [`Shared`], it must not be possible for safe 828*c3739801SMiguel Ojeda /// code, operating on a `&T` and `&U` with the same referent 829*c3739801SMiguel Ojeda /// simultaneously, to cause undefined behavior. 830*c3739801SMiguel Ojeda #[inline] 831*c3739801SMiguel Ojeda #[must_use] 832*c3739801SMiguel Ojeda pub unsafe fn cast_unchecked<U, C: Cast<T, U>>( 833*c3739801SMiguel Ojeda self, 834*c3739801SMiguel Ojeda ) -> Ptr<'a, U, (I::Aliasing, Unaligned, I::Validity)> 835*c3739801SMiguel Ojeda where 836*c3739801SMiguel Ojeda U: 'a + CastableFrom<T, I::Validity, I::Validity> + ?Sized, 837*c3739801SMiguel Ojeda { 838*c3739801SMiguel Ojeda // SAFETY: 839*c3739801SMiguel Ojeda // - By `C: Cast`, `C` preserves the address of the referent. 840*c3739801SMiguel Ojeda // - If `I::Aliasing` is [`Shared`], the caller promises that it 841*c3739801SMiguel Ojeda // is not possible for safe code, operating on a `&T` and `&U` 842*c3739801SMiguel Ojeda // with the same referent simultaneously, to cause undefined 843*c3739801SMiguel Ojeda // behavior. 844*c3739801SMiguel Ojeda // - By `U: CastableFrom<T, I::Validity, I::Validity>`, 845*c3739801SMiguel Ojeda // `I::Validity` is either `Uninit` or `Initialized`. In both 846*c3739801SMiguel Ojeda // cases, the bit validity `I::Validity` has the same semantics 847*c3739801SMiguel Ojeda // regardless of referent type. In other words, the set of allowed 848*c3739801SMiguel Ojeda // referent values for `Ptr<T, (_, _, I::Validity)>` and `Ptr<U, 849*c3739801SMiguel Ojeda // (_, _, I::Validity)>` are identical. As a consequence, neither 850*c3739801SMiguel Ojeda // `self` nor the returned `Ptr` can be used to write values which 851*c3739801SMiguel Ojeda // are invalid for the other. 852*c3739801SMiguel Ojeda unsafe { self.project_transmute_unchecked::<_, _, C>() } 853*c3739801SMiguel Ojeda } 854*c3739801SMiguel Ojeda 855*c3739801SMiguel Ojeda /// Casts to a different referent type. 856*c3739801SMiguel Ojeda #[inline] 857*c3739801SMiguel Ojeda #[must_use] 858*c3739801SMiguel Ojeda pub fn cast<U, C, R>(self) -> Ptr<'a, U, (I::Aliasing, Unaligned, I::Validity)> 859*c3739801SMiguel Ojeda where 860*c3739801SMiguel Ojeda T: MutationCompatible<U, I::Aliasing, I::Validity, I::Validity, R>, 861*c3739801SMiguel Ojeda U: 'a + ?Sized + CastableFrom<T, I::Validity, I::Validity>, 862*c3739801SMiguel Ojeda C: Cast<T, U>, 863*c3739801SMiguel Ojeda { 864*c3739801SMiguel Ojeda // SAFETY: Because `T: MutationCompatible<U, I::Aliasing, R>`, one 865*c3739801SMiguel Ojeda // of the following holds: 866*c3739801SMiguel Ojeda // - `T: Read<I::Aliasing>` and `U: Read<I::Aliasing>`, in which 867*c3739801SMiguel Ojeda // case one of the following holds: 868*c3739801SMiguel Ojeda // - `I::Aliasing` is `Exclusive` 869*c3739801SMiguel Ojeda // - `T` and `U` are both `Immutable` 870*c3739801SMiguel Ojeda // - It is sound for safe code to operate on `&T` and `&U` with the 871*c3739801SMiguel Ojeda // same referent simultaneously. 872*c3739801SMiguel Ojeda unsafe { self.cast_unchecked::<_, C>() } 873*c3739801SMiguel Ojeda } 874*c3739801SMiguel Ojeda 875*c3739801SMiguel Ojeda #[inline(always)] 876*c3739801SMiguel Ojeda pub fn project<F, const VARIANT_ID: i128, const FIELD_ID: i128>( 877*c3739801SMiguel Ojeda mut self, 878*c3739801SMiguel Ojeda ) -> Result<Ptr<'a, T::Type, T::Invariants>, T::Error> 879*c3739801SMiguel Ojeda where 880*c3739801SMiguel Ojeda T: ProjectField<F, I, VARIANT_ID, FIELD_ID>, 881*c3739801SMiguel Ojeda I::Aliasing: Reference, 882*c3739801SMiguel Ojeda { 883*c3739801SMiguel Ojeda use crate::pointer::cast::Projection; 884*c3739801SMiguel Ojeda match T::is_projectable(self.reborrow().project_tag()) { 885*c3739801SMiguel Ojeda Ok(()) => { 886*c3739801SMiguel Ojeda let inner = self.as_inner(); 887*c3739801SMiguel Ojeda let projected = inner.project::<_, Projection<F, VARIANT_ID, FIELD_ID>>(); 888*c3739801SMiguel Ojeda // SAFETY: By `T: ProjectField<F, I, VARIANT_ID, FIELD_ID>`, 889*c3739801SMiguel Ojeda // for `self: Ptr<'_, T, I>` such that `T::is_projectable` 890*c3739801SMiguel Ojeda // (which we've verified in this match arm), 891*c3739801SMiguel Ojeda // `T::project(self.as_inner())` conforms to 892*c3739801SMiguel Ojeda // `T::Invariants`. The `projected` pointer satisfies these 893*c3739801SMiguel Ojeda // invariants because it is produced by way of an 894*c3739801SMiguel Ojeda // abstraction that is equivalent to 895*c3739801SMiguel Ojeda // `T::project(ptr.as_inner())`: by invariant on 896*c3739801SMiguel Ojeda // `PtrInner::project`, `projected` is guaranteed to address 897*c3739801SMiguel Ojeda // the subset of the bytes of `inner`'s referent addressed 898*c3739801SMiguel Ojeda // by `Projection::project(inner)`, and by invariant on 899*c3739801SMiguel Ojeda // `Projection`, `Projection::project` is implemented by 900*c3739801SMiguel Ojeda // delegating to an implementation of `HasField::project`. 901*c3739801SMiguel Ojeda Ok(unsafe { Ptr::from_inner(projected) }) 902*c3739801SMiguel Ojeda } 903*c3739801SMiguel Ojeda Err(err) => Err(err), 904*c3739801SMiguel Ojeda } 905*c3739801SMiguel Ojeda } 906*c3739801SMiguel Ojeda 907*c3739801SMiguel Ojeda #[must_use] 908*c3739801SMiguel Ojeda #[inline(always)] 909*c3739801SMiguel Ojeda pub(crate) fn project_tag(self) -> Ptr<'a, T::Tag, I> 910*c3739801SMiguel Ojeda where 911*c3739801SMiguel Ojeda T: HasTag, 912*c3739801SMiguel Ojeda { 913*c3739801SMiguel Ojeda // SAFETY: By invariant on `Self::ProjectToTag`, this is a sound 914*c3739801SMiguel Ojeda // projection. 915*c3739801SMiguel Ojeda let tag = unsafe { self.project_transmute_unchecked::<_, _, T::ProjectToTag>() }; 916*c3739801SMiguel Ojeda // SAFETY: By invariant on `Self::ProjectToTag`, the projected 917*c3739801SMiguel Ojeda // pointer has the same alignment as `ptr`. 918*c3739801SMiguel Ojeda let tag = unsafe { tag.assume_alignment() }; 919*c3739801SMiguel Ojeda tag.unify_invariants() 920*c3739801SMiguel Ojeda } 921*c3739801SMiguel Ojeda 922*c3739801SMiguel Ojeda /// Attempts to transform the pointer, restoring the original on 923*c3739801SMiguel Ojeda /// failure. 924*c3739801SMiguel Ojeda /// 925*c3739801SMiguel Ojeda /// # Safety 926*c3739801SMiguel Ojeda /// 927*c3739801SMiguel Ojeda /// If `I::Aliasing != Shared`, then if `f` returns `Err(err)`, no copy 928*c3739801SMiguel Ojeda /// of `f`'s argument must exist outside of `err`. 929*c3739801SMiguel Ojeda #[inline(always)] 930*c3739801SMiguel Ojeda pub(crate) unsafe fn try_with_unchecked<U, J, E, F>( 931*c3739801SMiguel Ojeda self, 932*c3739801SMiguel Ojeda f: F, 933*c3739801SMiguel Ojeda ) -> Result<Ptr<'a, U, J>, E::Mapped> 934*c3739801SMiguel Ojeda where 935*c3739801SMiguel Ojeda U: 'a + ?Sized, 936*c3739801SMiguel Ojeda J: Invariants<Aliasing = I::Aliasing>, 937*c3739801SMiguel Ojeda E: TryWithError<Self>, 938*c3739801SMiguel Ojeda F: FnOnce(Ptr<'a, T, I>) -> Result<Ptr<'a, U, J>, E>, 939*c3739801SMiguel Ojeda { 940*c3739801SMiguel Ojeda let old_inner = self.as_inner(); 941*c3739801SMiguel Ojeda #[rustfmt::skip] 942*c3739801SMiguel Ojeda let res = f(self).map_err(#[inline(always)] move |err: E| { 943*c3739801SMiguel Ojeda err.map(#[inline(always)] |src| { 944*c3739801SMiguel Ojeda drop(src); 945*c3739801SMiguel Ojeda 946*c3739801SMiguel Ojeda // SAFETY: 947*c3739801SMiguel Ojeda // 0. Aliasing is either `Shared` or `Exclusive`: 948*c3739801SMiguel Ojeda // - If aliasing is `Shared`, then it cannot violate 949*c3739801SMiguel Ojeda // aliasing make another copy of this pointer (in fact, 950*c3739801SMiguel Ojeda // using `I::Aliasing = Shared`, we could have just 951*c3739801SMiguel Ojeda // cloned `self`). 952*c3739801SMiguel Ojeda // - If aliasing is `Exclusive`, then `f` is not allowed 953*c3739801SMiguel Ojeda // to make another copy of `self`. In `map_err`, we are 954*c3739801SMiguel Ojeda // consuming the only value in the returned `Result`. 955*c3739801SMiguel Ojeda // By invariant on `E: TryWithError<Self>`, that `err: 956*c3739801SMiguel Ojeda // E` only contains a single `Self` and no other 957*c3739801SMiguel Ojeda // non-ZST fields which could be `Ptr`s or references 958*c3739801SMiguel Ojeda // to `self`'s referent. By the same invariant, `map` 959*c3739801SMiguel Ojeda // consumes this single `Self` and passes it to this 960*c3739801SMiguel Ojeda // closure. Since `self` was, by invariant on 961*c3739801SMiguel Ojeda // `Exclusive`, the only `Ptr` or reference live for 962*c3739801SMiguel Ojeda // `'a` with this referent, and since we `drop(src)` 963*c3739801SMiguel Ojeda // above, there are no copies left, and so we are 964*c3739801SMiguel Ojeda // creating the only copy. 965*c3739801SMiguel Ojeda // 1. `self` conforms to `I::Aliasing` by invariant on 966*c3739801SMiguel Ojeda // `Ptr`, and `old_inner` has the same address, so it 967*c3739801SMiguel Ojeda // does too. 968*c3739801SMiguel Ojeda // 2. `f` could not have violated `self`'s validity without 969*c3739801SMiguel Ojeda // itself being unsound. Assuming that `f` is sound, the 970*c3739801SMiguel Ojeda // referent of `self` is still valid for `T`. 971*c3739801SMiguel Ojeda unsafe { Ptr::from_inner(old_inner) } 972*c3739801SMiguel Ojeda }) 973*c3739801SMiguel Ojeda }); 974*c3739801SMiguel Ojeda res 975*c3739801SMiguel Ojeda } 976*c3739801SMiguel Ojeda 977*c3739801SMiguel Ojeda /// Attempts to transform the pointer, restoring the original on 978*c3739801SMiguel Ojeda /// failure. 979*c3739801SMiguel Ojeda #[inline(always)] 980*c3739801SMiguel Ojeda pub fn try_with<U, J, E, F>(self, f: F) -> Result<Ptr<'a, U, J>, E::Mapped> 981*c3739801SMiguel Ojeda where 982*c3739801SMiguel Ojeda U: 'a + ?Sized, 983*c3739801SMiguel Ojeda J: Invariants<Aliasing = I::Aliasing>, 984*c3739801SMiguel Ojeda E: TryWithError<Self>, 985*c3739801SMiguel Ojeda F: FnOnce(Ptr<'a, T, I>) -> Result<Ptr<'a, U, J>, E>, 986*c3739801SMiguel Ojeda I: Invariants<Aliasing = Shared>, 987*c3739801SMiguel Ojeda { 988*c3739801SMiguel Ojeda // SAFETY: `I::Aliasing = Shared`, so the safety condition does not 989*c3739801SMiguel Ojeda // apply. 990*c3739801SMiguel Ojeda unsafe { self.try_with_unchecked(f) } 991*c3739801SMiguel Ojeda } 992*c3739801SMiguel Ojeda } 993*c3739801SMiguel Ojeda 994*c3739801SMiguel Ojeda /// # Safety 995*c3739801SMiguel Ojeda /// 996*c3739801SMiguel Ojeda /// `Self` only contains a single `Self::Inner`, and `Self::Mapped` only 997*c3739801SMiguel Ojeda /// contains a single `MappedInner`. Other than that, `Self` and 998*c3739801SMiguel Ojeda /// `Self::Mapped` contain no non-ZST fields. 999*c3739801SMiguel Ojeda /// 1000*c3739801SMiguel Ojeda /// `map` must pass ownership of `self`'s sole `Self::Inner` to `f`. 1001*c3739801SMiguel Ojeda pub unsafe trait TryWithError<MappedInner> { 1002*c3739801SMiguel Ojeda type Inner; 1003*c3739801SMiguel Ojeda type Mapped; 1004*c3739801SMiguel Ojeda fn map<F: FnOnce(Self::Inner) -> MappedInner>(self, f: F) -> Self::Mapped; 1005*c3739801SMiguel Ojeda } 1006*c3739801SMiguel Ojeda 1007*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 1008*c3739801SMiguel Ojeda where 1009*c3739801SMiguel Ojeda T: 'a + KnownLayout + ?Sized, 1010*c3739801SMiguel Ojeda I: Invariants, 1011*c3739801SMiguel Ojeda { 1012*c3739801SMiguel Ojeda /// Casts this pointer-to-initialized into a pointer-to-bytes. 1013*c3739801SMiguel Ojeda #[allow(clippy::wrong_self_convention)] 1014*c3739801SMiguel Ojeda #[must_use] 1015*c3739801SMiguel Ojeda #[inline] 1016*c3739801SMiguel Ojeda pub fn as_bytes<R>(self) -> Ptr<'a, [u8], (I::Aliasing, Aligned, Valid)> 1017*c3739801SMiguel Ojeda where 1018*c3739801SMiguel Ojeda [u8]: TransmuteFromPtr<T, I::Aliasing, I::Validity, Valid, AsBytesCast, R>, 1019*c3739801SMiguel Ojeda { 1020*c3739801SMiguel Ojeda self.transmute_with::<[u8], Valid, AsBytesCast, _>().bikeshed_recall_aligned() 1021*c3739801SMiguel Ojeda } 1022*c3739801SMiguel Ojeda } 1023*c3739801SMiguel Ojeda 1024*c3739801SMiguel Ojeda impl<'a, T, I, const N: usize> Ptr<'a, [T; N], I> 1025*c3739801SMiguel Ojeda where 1026*c3739801SMiguel Ojeda T: 'a, 1027*c3739801SMiguel Ojeda I: Invariants, 1028*c3739801SMiguel Ojeda { 1029*c3739801SMiguel Ojeda /// Casts this pointer-to-array into a slice. 1030*c3739801SMiguel Ojeda #[allow(clippy::wrong_self_convention)] 1031*c3739801SMiguel Ojeda #[inline] 1032*c3739801SMiguel Ojeda #[must_use] 1033*c3739801SMiguel Ojeda pub fn as_slice(self) -> Ptr<'a, [T], I> { 1034*c3739801SMiguel Ojeda let slice = self.as_inner().as_slice(); 1035*c3739801SMiguel Ojeda // SAFETY: Note that, by post-condition on `PtrInner::as_slice`, 1036*c3739801SMiguel Ojeda // `slice` refers to the same byte range as `self.as_inner()`. 1037*c3739801SMiguel Ojeda // 1038*c3739801SMiguel Ojeda // 0. Thus, `slice` conforms to the aliasing invariant of 1039*c3739801SMiguel Ojeda // `I::Aliasing` because `self` does. 1040*c3739801SMiguel Ojeda // 1. By the above lemma, `slice` conforms to the alignment 1041*c3739801SMiguel Ojeda // invariant of `I::Alignment` because `self` does. 1042*c3739801SMiguel Ojeda // 2. Since `[T; N]` and `[T]` have the same bit validity [1][2], 1043*c3739801SMiguel Ojeda // and since `self` and the returned `Ptr` have the same validity 1044*c3739801SMiguel Ojeda // invariant, neither `self` nor the returned `Ptr` can be used 1045*c3739801SMiguel Ojeda // to write a value to the referent which violates the other's 1046*c3739801SMiguel Ojeda // validity invariant. 1047*c3739801SMiguel Ojeda // 1048*c3739801SMiguel Ojeda // [1] Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#array-layout: 1049*c3739801SMiguel Ojeda // 1050*c3739801SMiguel Ojeda // An array of `[T; N]` has a size of `size_of::<T>() * N` and the 1051*c3739801SMiguel Ojeda // same alignment of `T`. Arrays are laid out so that the 1052*c3739801SMiguel Ojeda // zero-based `nth` element of the array is offset from the start 1053*c3739801SMiguel Ojeda // of the array by `n * size_of::<T>()` bytes. 1054*c3739801SMiguel Ojeda // 1055*c3739801SMiguel Ojeda // ... 1056*c3739801SMiguel Ojeda // 1057*c3739801SMiguel Ojeda // Slices have the same layout as the section of the array they 1058*c3739801SMiguel Ojeda // slice. 1059*c3739801SMiguel Ojeda // 1060*c3739801SMiguel Ojeda // [2] Per https://doc.rust-lang.org/1.81.0/reference/types/array.html#array-types: 1061*c3739801SMiguel Ojeda // 1062*c3739801SMiguel Ojeda // All elements of arrays are always initialized 1063*c3739801SMiguel Ojeda unsafe { Ptr::from_inner(slice) } 1064*c3739801SMiguel Ojeda } 1065*c3739801SMiguel Ojeda } 1066*c3739801SMiguel Ojeda 1067*c3739801SMiguel Ojeda /// For caller convenience, these methods are generic over alignment 1068*c3739801SMiguel Ojeda /// invariant. In practice, the referent is always well-aligned, because the 1069*c3739801SMiguel Ojeda /// alignment of `[u8]` is 1. 1070*c3739801SMiguel Ojeda impl<'a, I> Ptr<'a, [u8], I> 1071*c3739801SMiguel Ojeda where 1072*c3739801SMiguel Ojeda I: Invariants<Validity = Valid>, 1073*c3739801SMiguel Ojeda { 1074*c3739801SMiguel Ojeda /// Attempts to cast `self` to a `U` using the given cast type. 1075*c3739801SMiguel Ojeda /// 1076*c3739801SMiguel Ojeda /// If `U` is a slice DST and pointer metadata (`meta`) is provided, 1077*c3739801SMiguel Ojeda /// then the cast will only succeed if it would produce an object with 1078*c3739801SMiguel Ojeda /// the given metadata. 1079*c3739801SMiguel Ojeda /// 1080*c3739801SMiguel Ojeda /// Returns `None` if the resulting `U` would be invalidly-aligned, if 1081*c3739801SMiguel Ojeda /// no `U` can fit in `self`, or if the provided pointer metadata 1082*c3739801SMiguel Ojeda /// describes an invalid instance of `U`. On success, returns a pointer 1083*c3739801SMiguel Ojeda /// to the largest-possible `U` which fits in `self`. 1084*c3739801SMiguel Ojeda /// 1085*c3739801SMiguel Ojeda /// # Safety 1086*c3739801SMiguel Ojeda /// 1087*c3739801SMiguel Ojeda /// The caller may assume that this implementation is correct, and may 1088*c3739801SMiguel Ojeda /// rely on that assumption for the soundness of their code. In 1089*c3739801SMiguel Ojeda /// particular, the caller may assume that, if `try_cast_into` returns 1090*c3739801SMiguel Ojeda /// `Some((ptr, remainder))`, then `ptr` and `remainder` refer to 1091*c3739801SMiguel Ojeda /// non-overlapping byte ranges within `self`, and that `ptr` and 1092*c3739801SMiguel Ojeda /// `remainder` entirely cover `self`. Finally: 1093*c3739801SMiguel Ojeda /// - If this is a prefix cast, `ptr` has the same address as `self`. 1094*c3739801SMiguel Ojeda /// - If this is a suffix cast, `remainder` has the same address as 1095*c3739801SMiguel Ojeda /// `self`. 1096*c3739801SMiguel Ojeda #[inline(always)] 1097*c3739801SMiguel Ojeda pub fn try_cast_into<U, R>( 1098*c3739801SMiguel Ojeda self, 1099*c3739801SMiguel Ojeda cast_type: CastType, 1100*c3739801SMiguel Ojeda meta: Option<U::PointerMetadata>, 1101*c3739801SMiguel Ojeda ) -> Result< 1102*c3739801SMiguel Ojeda (Ptr<'a, U, (I::Aliasing, Aligned, Initialized)>, Ptr<'a, [u8], I>), 1103*c3739801SMiguel Ojeda CastError<Self, U>, 1104*c3739801SMiguel Ojeda > 1105*c3739801SMiguel Ojeda where 1106*c3739801SMiguel Ojeda I::Aliasing: Reference, 1107*c3739801SMiguel Ojeda U: 'a + ?Sized + KnownLayout + Read<I::Aliasing, R>, 1108*c3739801SMiguel Ojeda { 1109*c3739801SMiguel Ojeda let (inner, remainder) = self.as_inner().try_cast_into(cast_type, meta).map_err( 1110*c3739801SMiguel Ojeda #[inline(always)] 1111*c3739801SMiguel Ojeda |err| { 1112*c3739801SMiguel Ojeda err.map_src( 1113*c3739801SMiguel Ojeda #[inline(always)] 1114*c3739801SMiguel Ojeda |inner| 1115*c3739801SMiguel Ojeda // SAFETY: `PtrInner::try_cast_into` promises to return its 1116*c3739801SMiguel Ojeda // original argument on error, which was originally produced 1117*c3739801SMiguel Ojeda // by `self.as_inner()`, which is guaranteed to satisfy 1118*c3739801SMiguel Ojeda // `Ptr`'s invariants. 1119*c3739801SMiguel Ojeda unsafe { Ptr::from_inner(inner) }, 1120*c3739801SMiguel Ojeda ) 1121*c3739801SMiguel Ojeda }, 1122*c3739801SMiguel Ojeda )?; 1123*c3739801SMiguel Ojeda 1124*c3739801SMiguel Ojeda // SAFETY: 1125*c3739801SMiguel Ojeda // 0. Since `U: Read<I::Aliasing, _>`, either: 1126*c3739801SMiguel Ojeda // - `I::Aliasing` is `Exclusive`, in which case both `src` and 1127*c3739801SMiguel Ojeda // `ptr` conform to `Exclusive` 1128*c3739801SMiguel Ojeda // - `I::Aliasing` is `Shared` and `U` is `Immutable` (we already 1129*c3739801SMiguel Ojeda // know that `[u8]: Immutable`). In this case, neither `U` nor 1130*c3739801SMiguel Ojeda // `[u8]` permit mutation, and so `Shared` aliasing is 1131*c3739801SMiguel Ojeda // satisfied. 1132*c3739801SMiguel Ojeda // 1. `ptr` conforms to the alignment invariant of `Aligned` because 1133*c3739801SMiguel Ojeda // it is derived from `try_cast_into`, which promises that the 1134*c3739801SMiguel Ojeda // object described by `target` is validly aligned for `U`. 1135*c3739801SMiguel Ojeda // 2. By trait bound, `self` - and thus `target` - is a bit-valid 1136*c3739801SMiguel Ojeda // `[u8]`. `Ptr<[u8], (_, _, Valid)>` and `Ptr<_, (_, _, 1137*c3739801SMiguel Ojeda // Initialized)>` have the same bit validity, and so neither 1138*c3739801SMiguel Ojeda // `self` nor `res` can be used to write a value to the referent 1139*c3739801SMiguel Ojeda // which violates the other's validity invariant. 1140*c3739801SMiguel Ojeda let res = unsafe { Ptr::from_inner(inner) }; 1141*c3739801SMiguel Ojeda 1142*c3739801SMiguel Ojeda // SAFETY: 1143*c3739801SMiguel Ojeda // 0. `self` and `remainder` both have the type `[u8]`. Thus, they 1144*c3739801SMiguel Ojeda // have `UnsafeCell`s at the same locations. Type casting does 1145*c3739801SMiguel Ojeda // not affect aliasing. 1146*c3739801SMiguel Ojeda // 1. `[u8]` has no alignment requirement. 1147*c3739801SMiguel Ojeda // 2. `self` has validity `Valid` and has type `[u8]`. Since 1148*c3739801SMiguel Ojeda // `remainder` references a subset of `self`'s referent, it is 1149*c3739801SMiguel Ojeda // also a bit-valid `[u8]`. Thus, neither `self` nor `remainder` 1150*c3739801SMiguel Ojeda // can be used to write a value to the referent which violates 1151*c3739801SMiguel Ojeda // the other's validity invariant. 1152*c3739801SMiguel Ojeda let remainder = unsafe { Ptr::from_inner(remainder) }; 1153*c3739801SMiguel Ojeda 1154*c3739801SMiguel Ojeda Ok((res, remainder)) 1155*c3739801SMiguel Ojeda } 1156*c3739801SMiguel Ojeda 1157*c3739801SMiguel Ojeda /// Attempts to cast `self` into a `U`, failing if all of the bytes of 1158*c3739801SMiguel Ojeda /// `self` cannot be treated as a `U`. 1159*c3739801SMiguel Ojeda /// 1160*c3739801SMiguel Ojeda /// In particular, this method fails if `self` is not validly-aligned 1161*c3739801SMiguel Ojeda /// for `U` or if `self`'s size is not a valid size for `U`. 1162*c3739801SMiguel Ojeda /// 1163*c3739801SMiguel Ojeda /// # Safety 1164*c3739801SMiguel Ojeda /// 1165*c3739801SMiguel Ojeda /// On success, the caller may assume that the returned pointer 1166*c3739801SMiguel Ojeda /// references the same byte range as `self`. 1167*c3739801SMiguel Ojeda #[allow(unused)] 1168*c3739801SMiguel Ojeda #[inline(always)] 1169*c3739801SMiguel Ojeda pub fn try_cast_into_no_leftover<U, R>( 1170*c3739801SMiguel Ojeda self, 1171*c3739801SMiguel Ojeda meta: Option<U::PointerMetadata>, 1172*c3739801SMiguel Ojeda ) -> Result<Ptr<'a, U, (I::Aliasing, Aligned, Initialized)>, CastError<Self, U>> 1173*c3739801SMiguel Ojeda where 1174*c3739801SMiguel Ojeda I::Aliasing: Reference, 1175*c3739801SMiguel Ojeda U: 'a + ?Sized + KnownLayout + Read<I::Aliasing, R>, 1176*c3739801SMiguel Ojeda [u8]: Read<I::Aliasing, R>, 1177*c3739801SMiguel Ojeda { 1178*c3739801SMiguel Ojeda // SAFETY: The provided closure returns the only copy of `slf`. 1179*c3739801SMiguel Ojeda unsafe { 1180*c3739801SMiguel Ojeda self.try_with_unchecked( 1181*c3739801SMiguel Ojeda #[inline(always)] 1182*c3739801SMiguel Ojeda |slf| match slf.try_cast_into(CastType::Prefix, meta) { 1183*c3739801SMiguel Ojeda Ok((slf, remainder)) => { 1184*c3739801SMiguel Ojeda if remainder.is_empty() { 1185*c3739801SMiguel Ojeda Ok(slf) 1186*c3739801SMiguel Ojeda } else { 1187*c3739801SMiguel Ojeda Err(CastError::Size(SizeError::<_, U>::new(()))) 1188*c3739801SMiguel Ojeda } 1189*c3739801SMiguel Ojeda } 1190*c3739801SMiguel Ojeda Err(err) => Err(err.map_src( 1191*c3739801SMiguel Ojeda #[inline(always)] 1192*c3739801SMiguel Ojeda |_slf| (), 1193*c3739801SMiguel Ojeda )), 1194*c3739801SMiguel Ojeda }, 1195*c3739801SMiguel Ojeda ) 1196*c3739801SMiguel Ojeda } 1197*c3739801SMiguel Ojeda } 1198*c3739801SMiguel Ojeda } 1199*c3739801SMiguel Ojeda 1200*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, UnsafeCell<T>, I> 1201*c3739801SMiguel Ojeda where 1202*c3739801SMiguel Ojeda T: 'a + ?Sized, 1203*c3739801SMiguel Ojeda I: Invariants<Aliasing = Exclusive>, 1204*c3739801SMiguel Ojeda { 1205*c3739801SMiguel Ojeda /// Converts this `Ptr` into a pointer to the underlying data. 1206*c3739801SMiguel Ojeda /// 1207*c3739801SMiguel Ojeda /// This call borrows the `UnsafeCell` mutably (at compile-time) which 1208*c3739801SMiguel Ojeda /// guarantees that we possess the only reference. 1209*c3739801SMiguel Ojeda /// 1210*c3739801SMiguel Ojeda /// This is like [`UnsafeCell::get_mut`], but for `Ptr`. 1211*c3739801SMiguel Ojeda /// 1212*c3739801SMiguel Ojeda /// [`UnsafeCell::get_mut`]: core::cell::UnsafeCell::get_mut 1213*c3739801SMiguel Ojeda #[must_use] 1214*c3739801SMiguel Ojeda #[inline(always)] 1215*c3739801SMiguel Ojeda pub fn get_mut(self) -> Ptr<'a, T, I> { 1216*c3739801SMiguel Ojeda // SAFETY: As described below, `UnsafeCell<T>` has the same size 1217*c3739801SMiguel Ojeda // as `T: ?Sized` (same static size or same DST layout). Thus, 1218*c3739801SMiguel Ojeda // `*const UnsafeCell<T> as *const T` is a size-preserving cast. 1219*c3739801SMiguel Ojeda define_cast!(unsafe { Cast<T: ?Sized> = UnsafeCell<T> => T }); 1220*c3739801SMiguel Ojeda 1221*c3739801SMiguel Ojeda // SAFETY: 1222*c3739801SMiguel Ojeda // - Aliasing is `Exclusive`, and so we are not required to promise 1223*c3739801SMiguel Ojeda // anything about the locations of `UnsafeCell`s. 1224*c3739801SMiguel Ojeda // - `UnsafeCell<T>` has the same bit validity as `T` [1]. 1225*c3739801SMiguel Ojeda // Technically the term "representation" doesn't guarantee this, 1226*c3739801SMiguel Ojeda // but the subsequent sentence in the documentation makes it clear 1227*c3739801SMiguel Ojeda // that this is the intention. 1228*c3739801SMiguel Ojeda // 1229*c3739801SMiguel Ojeda // By invariant on `Validity`, since `T` and `UnsafeCell<T>` have 1230*c3739801SMiguel Ojeda // the same bit validity, then the set of values which may appear 1231*c3739801SMiguel Ojeda // in the referent of a `Ptr<T, (_, _, V)>` is the same as the set 1232*c3739801SMiguel Ojeda // which may appear in the referent of a `Ptr<UnsafeCell<T>, (_, 1233*c3739801SMiguel Ojeda // _, V)>`. Thus, neither `self` nor `ptr` may be used to write a 1234*c3739801SMiguel Ojeda // value to the referent which would violate the other's validity 1235*c3739801SMiguel Ojeda // invariant. 1236*c3739801SMiguel Ojeda // 1237*c3739801SMiguel Ojeda // [1] Per https://doc.rust-lang.org/1.81.0/core/cell/struct.UnsafeCell.html#memory-layout: 1238*c3739801SMiguel Ojeda // 1239*c3739801SMiguel Ojeda // `UnsafeCell<T>` has the same in-memory representation as its 1240*c3739801SMiguel Ojeda // inner type `T`. A consequence of this guarantee is that it is 1241*c3739801SMiguel Ojeda // possible to convert between `T` and `UnsafeCell<T>`. 1242*c3739801SMiguel Ojeda let ptr = unsafe { self.project_transmute_unchecked::<_, _, Cast>() }; 1243*c3739801SMiguel Ojeda 1244*c3739801SMiguel Ojeda // SAFETY: `UnsafeCell<T>` has the same alignment as `T` [1], 1245*c3739801SMiguel Ojeda // and so if `self` is guaranteed to be aligned, then so is the 1246*c3739801SMiguel Ojeda // returned `Ptr`. 1247*c3739801SMiguel Ojeda // 1248*c3739801SMiguel Ojeda // [1] Per https://doc.rust-lang.org/1.81.0/core/cell/struct.UnsafeCell.html#memory-layout: 1249*c3739801SMiguel Ojeda // 1250*c3739801SMiguel Ojeda // `UnsafeCell<T>` has the same in-memory representation as 1251*c3739801SMiguel Ojeda // its inner type `T`. A consequence of this guarantee is that 1252*c3739801SMiguel Ojeda // it is possible to convert between `T` and `UnsafeCell<T>`. 1253*c3739801SMiguel Ojeda let ptr = unsafe { ptr.assume_alignment::<I::Alignment>() }; 1254*c3739801SMiguel Ojeda ptr.unify_invariants() 1255*c3739801SMiguel Ojeda } 1256*c3739801SMiguel Ojeda } 1257*c3739801SMiguel Ojeda } 1258*c3739801SMiguel Ojeda 1259*c3739801SMiguel Ojeda /// Projections through the referent. 1260*c3739801SMiguel Ojeda mod _project { 1261*c3739801SMiguel Ojeda use super::*; 1262*c3739801SMiguel Ojeda 1263*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, [T], I> 1264*c3739801SMiguel Ojeda where 1265*c3739801SMiguel Ojeda T: 'a, 1266*c3739801SMiguel Ojeda I: Invariants, 1267*c3739801SMiguel Ojeda I::Aliasing: Reference, 1268*c3739801SMiguel Ojeda { 1269*c3739801SMiguel Ojeda /// Iteratively projects the elements `Ptr<T>` from `Ptr<[T]>`. 1270*c3739801SMiguel Ojeda #[inline] 1271*c3739801SMiguel Ojeda pub fn iter(self) -> impl Iterator<Item = Ptr<'a, T, I>> { 1272*c3739801SMiguel Ojeda // SAFETY: 1273*c3739801SMiguel Ojeda // 0. `elem` conforms to the aliasing invariant of `I::Aliasing`: 1274*c3739801SMiguel Ojeda // - `Exclusive`: `self` is consumed by value, and therefore 1275*c3739801SMiguel Ojeda // cannot be used to access the slice while any yielded 1276*c3739801SMiguel Ojeda // element `Ptr` is live. Each non-zero-sized element is a 1277*c3739801SMiguel Ojeda // disjoint byte range within the slice, and zero-sized 1278*c3739801SMiguel Ojeda // elements address no bytes, so distinct yielded element 1279*c3739801SMiguel Ojeda // `Ptr`s do not alias each other. 1280*c3739801SMiguel Ojeda // - `Shared`: It is sound for multiple shared `Ptr`s to exist 1281*c3739801SMiguel Ojeda // simultaneously which reference the same memory. 1282*c3739801SMiguel Ojeda // 1. `elem`, conditionally, conforms to the validity invariant of 1283*c3739801SMiguel Ojeda // `I::Alignment`. If `elem` is projected from data well-aligned 1284*c3739801SMiguel Ojeda // for `[T]`, `elem` will be valid for `T`. 1285*c3739801SMiguel Ojeda // 2. `elem` conforms to the validity invariant of `I::Validity`. 1286*c3739801SMiguel Ojeda // Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#array-layout: 1287*c3739801SMiguel Ojeda // 1288*c3739801SMiguel Ojeda // Slices have the same layout as the section of the array they 1289*c3739801SMiguel Ojeda // slice. 1290*c3739801SMiguel Ojeda // 1291*c3739801SMiguel Ojeda // Arrays are laid out so that the zero-based `nth` element of 1292*c3739801SMiguel Ojeda // the array is offset from the start of the array by `n * 1293*c3739801SMiguel Ojeda // size_of::<T>()` bytes. Thus, `elem` addresses a valid `T` 1294*c3739801SMiguel Ojeda // within the slice. Since `self` satisfies `I::Validity`, `elem` 1295*c3739801SMiguel Ojeda // also satisfies `I::Validity`. 1296*c3739801SMiguel Ojeda self.as_inner().iter().map( 1297*c3739801SMiguel Ojeda #[inline(always)] 1298*c3739801SMiguel Ojeda |elem| unsafe { Ptr::from_inner(elem) }, 1299*c3739801SMiguel Ojeda ) 1300*c3739801SMiguel Ojeda } 1301*c3739801SMiguel Ojeda } 1302*c3739801SMiguel Ojeda 1303*c3739801SMiguel Ojeda #[allow(clippy::needless_lifetimes)] 1304*c3739801SMiguel Ojeda impl<'a, T, I> Ptr<'a, T, I> 1305*c3739801SMiguel Ojeda where 1306*c3739801SMiguel Ojeda T: 'a + ?Sized + KnownLayout<PointerMetadata = usize>, 1307*c3739801SMiguel Ojeda I: Invariants, 1308*c3739801SMiguel Ojeda { 1309*c3739801SMiguel Ojeda /// The number of slice elements in the object referenced by `self`. 1310*c3739801SMiguel Ojeda #[inline] 1311*c3739801SMiguel Ojeda #[must_use] 1312*c3739801SMiguel Ojeda pub fn len(&self) -> usize { 1313*c3739801SMiguel Ojeda self.as_inner().meta().get() 1314*c3739801SMiguel Ojeda } 1315*c3739801SMiguel Ojeda 1316*c3739801SMiguel Ojeda /// Returns `true` if the slice pointer has a length of 0. 1317*c3739801SMiguel Ojeda #[inline] 1318*c3739801SMiguel Ojeda #[must_use] 1319*c3739801SMiguel Ojeda pub fn is_empty(&self) -> bool { 1320*c3739801SMiguel Ojeda self.len() == 0 1321*c3739801SMiguel Ojeda } 1322*c3739801SMiguel Ojeda } 1323*c3739801SMiguel Ojeda } 1324*c3739801SMiguel Ojeda 1325*c3739801SMiguel Ojeda #[cfg(test)] 1326*c3739801SMiguel Ojeda mod tests { 1327*c3739801SMiguel Ojeda use core::mem::{self, MaybeUninit}; 1328*c3739801SMiguel Ojeda 1329*c3739801SMiguel Ojeda use super::*; 1330*c3739801SMiguel Ojeda #[allow(unused)] // Needed on our MSRV, but considered unused on later toolchains. 1331*c3739801SMiguel Ojeda use crate::util::AsAddress; 1332*c3739801SMiguel Ojeda use crate::{pointer::BecauseImmutable, util::testutil::AU64, FromBytes, Immutable}; 1333*c3739801SMiguel Ojeda 1334*c3739801SMiguel Ojeda mod test_ptr_try_cast_into_soundness { 1335*c3739801SMiguel Ojeda use super::*; 1336*c3739801SMiguel Ojeda 1337*c3739801SMiguel Ojeda // This test is designed so that if `Ptr::try_cast_into_xxx` are 1338*c3739801SMiguel Ojeda // buggy, it will manifest as unsoundness that Miri can detect. 1339*c3739801SMiguel Ojeda 1340*c3739801SMiguel Ojeda // - If `size_of::<T>() == 0`, `N == 4` 1341*c3739801SMiguel Ojeda // - Else, `N == 4 * size_of::<T>()` 1342*c3739801SMiguel Ojeda // 1343*c3739801SMiguel Ojeda // Each test will be run for each metadata in `metas`. 1344*c3739801SMiguel Ojeda fn test<T, I, const N: usize>(metas: I) 1345*c3739801SMiguel Ojeda where 1346*c3739801SMiguel Ojeda T: ?Sized + KnownLayout + Immutable + FromBytes, 1347*c3739801SMiguel Ojeda I: IntoIterator<Item = Option<T::PointerMetadata>> + Clone, 1348*c3739801SMiguel Ojeda { 1349*c3739801SMiguel Ojeda let mut bytes = [MaybeUninit::<u8>::uninit(); N]; 1350*c3739801SMiguel Ojeda let initialized = [MaybeUninit::new(0u8); N]; 1351*c3739801SMiguel Ojeda for start in 0..=bytes.len() { 1352*c3739801SMiguel Ojeda for end in start..=bytes.len() { 1353*c3739801SMiguel Ojeda // Set all bytes to uninitialized other than those in 1354*c3739801SMiguel Ojeda // the range we're going to pass to `try_cast_from`. 1355*c3739801SMiguel Ojeda // This allows Miri to detect out-of-bounds reads 1356*c3739801SMiguel Ojeda // because they read uninitialized memory. Without this, 1357*c3739801SMiguel Ojeda // some out-of-bounds reads would still be in-bounds of 1358*c3739801SMiguel Ojeda // `bytes`, and so might spuriously be accepted. 1359*c3739801SMiguel Ojeda bytes = [MaybeUninit::<u8>::uninit(); N]; 1360*c3739801SMiguel Ojeda let bytes = &mut bytes[start..end]; 1361*c3739801SMiguel Ojeda // Initialize only the byte range we're going to pass to 1362*c3739801SMiguel Ojeda // `try_cast_from`. 1363*c3739801SMiguel Ojeda bytes.copy_from_slice(&initialized[start..end]); 1364*c3739801SMiguel Ojeda 1365*c3739801SMiguel Ojeda let bytes = { 1366*c3739801SMiguel Ojeda let bytes: *const [MaybeUninit<u8>] = bytes; 1367*c3739801SMiguel Ojeda #[allow(clippy::as_conversions)] 1368*c3739801SMiguel Ojeda let bytes = bytes as *const [u8]; 1369*c3739801SMiguel Ojeda // SAFETY: We just initialized these bytes to valid 1370*c3739801SMiguel Ojeda // `u8`s. 1371*c3739801SMiguel Ojeda unsafe { &*bytes } 1372*c3739801SMiguel Ojeda }; 1373*c3739801SMiguel Ojeda 1374*c3739801SMiguel Ojeda // SAFETY: The bytes in `slf` must be initialized. 1375*c3739801SMiguel Ojeda unsafe fn validate_and_get_len< 1376*c3739801SMiguel Ojeda T: ?Sized + KnownLayout + FromBytes + Immutable, 1377*c3739801SMiguel Ojeda >( 1378*c3739801SMiguel Ojeda slf: Ptr<'_, T, (Shared, Aligned, Initialized)>, 1379*c3739801SMiguel Ojeda ) -> usize { 1380*c3739801SMiguel Ojeda let t = slf.recall_validity().as_ref(); 1381*c3739801SMiguel Ojeda 1382*c3739801SMiguel Ojeda let bytes = { 1383*c3739801SMiguel Ojeda let len = mem::size_of_val(t); 1384*c3739801SMiguel Ojeda let t: *const T = t; 1385*c3739801SMiguel Ojeda // SAFETY: 1386*c3739801SMiguel Ojeda // - We know `t`'s bytes are all initialized 1387*c3739801SMiguel Ojeda // because we just read it from `slf`, which 1388*c3739801SMiguel Ojeda // points to an initialized range of bytes. If 1389*c3739801SMiguel Ojeda // there's a bug and this doesn't hold, then 1390*c3739801SMiguel Ojeda // that's exactly what we're hoping Miri will 1391*c3739801SMiguel Ojeda // catch! 1392*c3739801SMiguel Ojeda // - Since `T: FromBytes`, `T` doesn't contain 1393*c3739801SMiguel Ojeda // any `UnsafeCell`s, so it's okay for `t: T` 1394*c3739801SMiguel Ojeda // and a `&[u8]` to the same memory to be 1395*c3739801SMiguel Ojeda // alive concurrently. 1396*c3739801SMiguel Ojeda unsafe { core::slice::from_raw_parts(t.cast::<u8>(), len) } 1397*c3739801SMiguel Ojeda }; 1398*c3739801SMiguel Ojeda 1399*c3739801SMiguel Ojeda // This assertion ensures that `t`'s bytes are read 1400*c3739801SMiguel Ojeda // and compared to another value, which in turn 1401*c3739801SMiguel Ojeda // ensures that Miri gets a chance to notice if any 1402*c3739801SMiguel Ojeda // of `t`'s bytes are uninitialized, which they 1403*c3739801SMiguel Ojeda // shouldn't be (see the comment above). 1404*c3739801SMiguel Ojeda assert_eq!(bytes, vec![0u8; bytes.len()]); 1405*c3739801SMiguel Ojeda 1406*c3739801SMiguel Ojeda mem::size_of_val(t) 1407*c3739801SMiguel Ojeda } 1408*c3739801SMiguel Ojeda 1409*c3739801SMiguel Ojeda for meta in metas.clone().into_iter() { 1410*c3739801SMiguel Ojeda for cast_type in [CastType::Prefix, CastType::Suffix] { 1411*c3739801SMiguel Ojeda if let Ok((slf, remaining)) = Ptr::from_ref(bytes) 1412*c3739801SMiguel Ojeda .try_cast_into::<T, BecauseImmutable>(cast_type, meta) 1413*c3739801SMiguel Ojeda { 1414*c3739801SMiguel Ojeda // SAFETY: All bytes in `bytes` have been 1415*c3739801SMiguel Ojeda // initialized. 1416*c3739801SMiguel Ojeda let len = unsafe { validate_and_get_len(slf) }; 1417*c3739801SMiguel Ojeda assert_eq!(remaining.len(), bytes.len() - len); 1418*c3739801SMiguel Ojeda #[allow(unstable_name_collisions)] 1419*c3739801SMiguel Ojeda let bytes_addr = bytes.as_ptr().addr(); 1420*c3739801SMiguel Ojeda #[allow(unstable_name_collisions)] 1421*c3739801SMiguel Ojeda let remaining_addr = remaining.as_inner().as_ptr().addr(); 1422*c3739801SMiguel Ojeda match cast_type { 1423*c3739801SMiguel Ojeda CastType::Prefix => { 1424*c3739801SMiguel Ojeda assert_eq!(remaining_addr, bytes_addr + len) 1425*c3739801SMiguel Ojeda } 1426*c3739801SMiguel Ojeda CastType::Suffix => assert_eq!(remaining_addr, bytes_addr), 1427*c3739801SMiguel Ojeda } 1428*c3739801SMiguel Ojeda 1429*c3739801SMiguel Ojeda if let Some(want) = meta { 1430*c3739801SMiguel Ojeda let got = 1431*c3739801SMiguel Ojeda KnownLayout::pointer_to_metadata(slf.as_inner().as_ptr()); 1432*c3739801SMiguel Ojeda assert_eq!(got, want); 1433*c3739801SMiguel Ojeda } 1434*c3739801SMiguel Ojeda } 1435*c3739801SMiguel Ojeda } 1436*c3739801SMiguel Ojeda 1437*c3739801SMiguel Ojeda if let Ok(slf) = Ptr::from_ref(bytes) 1438*c3739801SMiguel Ojeda .try_cast_into_no_leftover::<T, BecauseImmutable>(meta) 1439*c3739801SMiguel Ojeda { 1440*c3739801SMiguel Ojeda // SAFETY: All bytes in `bytes` have been 1441*c3739801SMiguel Ojeda // initialized. 1442*c3739801SMiguel Ojeda let len = unsafe { validate_and_get_len(slf) }; 1443*c3739801SMiguel Ojeda assert_eq!(len, bytes.len()); 1444*c3739801SMiguel Ojeda 1445*c3739801SMiguel Ojeda if let Some(want) = meta { 1446*c3739801SMiguel Ojeda let got = KnownLayout::pointer_to_metadata(slf.as_inner().as_ptr()); 1447*c3739801SMiguel Ojeda assert_eq!(got, want); 1448*c3739801SMiguel Ojeda } 1449*c3739801SMiguel Ojeda } 1450*c3739801SMiguel Ojeda } 1451*c3739801SMiguel Ojeda } 1452*c3739801SMiguel Ojeda } 1453*c3739801SMiguel Ojeda } 1454*c3739801SMiguel Ojeda 1455*c3739801SMiguel Ojeda #[derive(FromBytes, KnownLayout, Immutable)] 1456*c3739801SMiguel Ojeda #[repr(C)] 1457*c3739801SMiguel Ojeda struct SliceDst<T> { 1458*c3739801SMiguel Ojeda a: u8, 1459*c3739801SMiguel Ojeda trailing: [T], 1460*c3739801SMiguel Ojeda } 1461*c3739801SMiguel Ojeda 1462*c3739801SMiguel Ojeda // Each test case becomes its own `#[test]` function. We do this because 1463*c3739801SMiguel Ojeda // this test in particular takes far, far longer to execute under Miri 1464*c3739801SMiguel Ojeda // than all of our other tests combined. Previously, we had these 1465*c3739801SMiguel Ojeda // execute sequentially in a single test function. We run Miri tests in 1466*c3739801SMiguel Ojeda // parallel in CI, but this test being sequential meant that most of 1467*c3739801SMiguel Ojeda // that parallelism was wasted, as all other tests would finish in a 1468*c3739801SMiguel Ojeda // fraction of the total execution time, leaving this test to execute on 1469*c3739801SMiguel Ojeda // a single thread for the remainder of the test. By putting each test 1470*c3739801SMiguel Ojeda // case in its own function, we permit better use of available 1471*c3739801SMiguel Ojeda // parallelism. 1472*c3739801SMiguel Ojeda macro_rules! test { 1473*c3739801SMiguel Ojeda ($test_name:ident: $ty:ty) => { 1474*c3739801SMiguel Ojeda #[test] 1475*c3739801SMiguel Ojeda #[allow(non_snake_case)] 1476*c3739801SMiguel Ojeda fn $test_name() { 1477*c3739801SMiguel Ojeda const S: usize = core::mem::size_of::<$ty>(); 1478*c3739801SMiguel Ojeda const N: usize = if S == 0 { 4 } else { S * 4 }; 1479*c3739801SMiguel Ojeda test::<$ty, _, N>([None]); 1480*c3739801SMiguel Ojeda 1481*c3739801SMiguel Ojeda // If `$ty` is a ZST, then we can't pass `None` as the 1482*c3739801SMiguel Ojeda // pointer metadata, or else computing the correct trailing 1483*c3739801SMiguel Ojeda // slice length will panic. 1484*c3739801SMiguel Ojeda if S == 0 { 1485*c3739801SMiguel Ojeda test::<[$ty], _, N>([Some(0), Some(1), Some(2), Some(3)]); 1486*c3739801SMiguel Ojeda test::<SliceDst<$ty>, _, N>([Some(0), Some(1), Some(2), Some(3)]); 1487*c3739801SMiguel Ojeda } else { 1488*c3739801SMiguel Ojeda test::<[$ty], _, N>([None, Some(0), Some(1), Some(2), Some(3)]); 1489*c3739801SMiguel Ojeda test::<SliceDst<$ty>, _, N>([None, Some(0), Some(1), Some(2), Some(3)]); 1490*c3739801SMiguel Ojeda } 1491*c3739801SMiguel Ojeda } 1492*c3739801SMiguel Ojeda }; 1493*c3739801SMiguel Ojeda ($ty:ident) => { 1494*c3739801SMiguel Ojeda test!($ty: $ty); 1495*c3739801SMiguel Ojeda }; 1496*c3739801SMiguel Ojeda ($($ty:ident),*) => { $(test!($ty);)* } 1497*c3739801SMiguel Ojeda } 1498*c3739801SMiguel Ojeda 1499*c3739801SMiguel Ojeda test!(empty_tuple: ()); 1500*c3739801SMiguel Ojeda test!(u8, u16, u32, u64, usize, AU64); 1501*c3739801SMiguel Ojeda test!(i8, i16, i32, i64, isize); 1502*c3739801SMiguel Ojeda test!(f32, f64); 1503*c3739801SMiguel Ojeda } 1504*c3739801SMiguel Ojeda 1505*c3739801SMiguel Ojeda #[test] 1506*c3739801SMiguel Ojeda fn test_try_cast_into_explicit_count() { 1507*c3739801SMiguel Ojeda macro_rules! test { 1508*c3739801SMiguel Ojeda ($ty:ty, $bytes:expr, $elems:expr, $expect:expr) => {{ 1509*c3739801SMiguel Ojeda let bytes = [0u8; $bytes]; 1510*c3739801SMiguel Ojeda let ptr = Ptr::from_ref(&bytes[..]); 1511*c3739801SMiguel Ojeda let res = 1512*c3739801SMiguel Ojeda ptr.try_cast_into::<$ty, BecauseImmutable>(CastType::Prefix, Some($elems)); 1513*c3739801SMiguel Ojeda if let Some(expect) = $expect { 1514*c3739801SMiguel Ojeda let (ptr, _) = res.unwrap(); 1515*c3739801SMiguel Ojeda assert_eq!(KnownLayout::pointer_to_metadata(ptr.as_inner().as_ptr()), expect); 1516*c3739801SMiguel Ojeda } else { 1517*c3739801SMiguel Ojeda let _ = res.unwrap_err(); 1518*c3739801SMiguel Ojeda } 1519*c3739801SMiguel Ojeda }}; 1520*c3739801SMiguel Ojeda } 1521*c3739801SMiguel Ojeda 1522*c3739801SMiguel Ojeda #[derive(KnownLayout, Immutable)] 1523*c3739801SMiguel Ojeda #[repr(C)] 1524*c3739801SMiguel Ojeda struct ZstDst { 1525*c3739801SMiguel Ojeda u: [u8; 8], 1526*c3739801SMiguel Ojeda slc: [()], 1527*c3739801SMiguel Ojeda } 1528*c3739801SMiguel Ojeda 1529*c3739801SMiguel Ojeda test!(ZstDst, 8, 0, Some(0)); 1530*c3739801SMiguel Ojeda test!(ZstDst, 7, 0, None); 1531*c3739801SMiguel Ojeda 1532*c3739801SMiguel Ojeda test!(ZstDst, 8, usize::MAX, Some(usize::MAX)); 1533*c3739801SMiguel Ojeda test!(ZstDst, 7, usize::MAX, None); 1534*c3739801SMiguel Ojeda 1535*c3739801SMiguel Ojeda #[derive(KnownLayout, Immutable)] 1536*c3739801SMiguel Ojeda #[repr(C)] 1537*c3739801SMiguel Ojeda struct Dst { 1538*c3739801SMiguel Ojeda u: [u8; 8], 1539*c3739801SMiguel Ojeda slc: [u8], 1540*c3739801SMiguel Ojeda } 1541*c3739801SMiguel Ojeda 1542*c3739801SMiguel Ojeda test!(Dst, 8, 0, Some(0)); 1543*c3739801SMiguel Ojeda test!(Dst, 7, 0, None); 1544*c3739801SMiguel Ojeda 1545*c3739801SMiguel Ojeda test!(Dst, 9, 1, Some(1)); 1546*c3739801SMiguel Ojeda test!(Dst, 8, 1, None); 1547*c3739801SMiguel Ojeda 1548*c3739801SMiguel Ojeda // If we didn't properly check for overflow, this would cause the 1549*c3739801SMiguel Ojeda // metadata to overflow to 0, and thus the cast would spuriously 1550*c3739801SMiguel Ojeda // succeed. 1551*c3739801SMiguel Ojeda test!(Dst, 8, usize::MAX - 8 + 1, None); 1552*c3739801SMiguel Ojeda } 1553*c3739801SMiguel Ojeda 1554*c3739801SMiguel Ojeda #[test] 1555*c3739801SMiguel Ojeda fn test_try_cast_into_no_leftover_restores_original_slice() { 1556*c3739801SMiguel Ojeda let bytes = [0u8; 4]; 1557*c3739801SMiguel Ojeda let ptr = Ptr::from_ref(&bytes[..]); 1558*c3739801SMiguel Ojeda let res = ptr.try_cast_into_no_leftover::<[u8; 2], BecauseImmutable>(None); 1559*c3739801SMiguel Ojeda match res { 1560*c3739801SMiguel Ojeda Ok(_) => panic!("should have failed due to leftover bytes"), 1561*c3739801SMiguel Ojeda Err(CastError::Size(e)) => { 1562*c3739801SMiguel Ojeda assert_eq!(e.into_src().len(), 4, "Should return original slice length"); 1563*c3739801SMiguel Ojeda } 1564*c3739801SMiguel Ojeda Err(e) => panic!("wrong error type: {:?}", e), 1565*c3739801SMiguel Ojeda } 1566*c3739801SMiguel Ojeda } 1567*c3739801SMiguel Ojeda 1568*c3739801SMiguel Ojeda #[test] 1569*c3739801SMiguel Ojeda fn test_iter_exclusive_yields_disjoint_ptrs() { 1570*c3739801SMiguel Ojeda let mut arr = [0u8, 1, 2, 3]; 1571*c3739801SMiguel Ojeda 1572*c3739801SMiguel Ojeda { 1573*c3739801SMiguel Ojeda let mut iter = Ptr::from_mut(&mut arr[..]).iter(); 1574*c3739801SMiguel Ojeda let first = iter.next().unwrap().as_mut(); 1575*c3739801SMiguel Ojeda let second = iter.next().unwrap().as_mut(); 1576*c3739801SMiguel Ojeda 1577*c3739801SMiguel Ojeda *first = 10; 1578*c3739801SMiguel Ojeda *second = 20; 1579*c3739801SMiguel Ojeda *first = 30; 1580*c3739801SMiguel Ojeda } 1581*c3739801SMiguel Ojeda 1582*c3739801SMiguel Ojeda assert_eq!(arr, [30, 20, 2, 3]); 1583*c3739801SMiguel Ojeda } 1584*c3739801SMiguel Ojeda } 1585