stdx\ptr/
unique.rs

1// Unstable Rust code
2//
3// SPDX-FileCopyrightText: (c) The Rust Project Contributors
4// SPDX-License-Identifier: Apache-2.0 OR MIT
5// - https://github.com/rust-lang/rust/blob/master/LICENSE-MIT
6use core::fmt;
7use core::marker::PhantomData;
8use core::ptr::NonNull;
9
10/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
11/// of this wrapper owns the referent. Useful for building abstractions like
12/// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
13///
14/// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
15/// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
16/// the kind of strong aliasing guarantees an instance of `T` can expect:
17/// the referent of the pointer should not be modified without a unique path to
18/// its owning Unique.
19///
20/// If you're uncertain of whether it's correct to use `Unique` for your purposes,
21/// consider using `NonNull`, which has weaker semantics.
22///
23/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
24/// is never dereferenced. This is so that enums may use this forbidden value
25/// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
26/// However the pointer may still dangle if it isn't dereferenced.
27///
28/// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
29/// for any type which upholds Unique's aliasing requirements.
30#[repr(transparent)]
31// Lang item used experimentally by Miri to define the semantics of `Unique`.
32pub struct Unique<T: ?Sized> {
33    pointer: NonNull<T>,
34    // NOTE: this marker has no consequences for variance, but is necessary
35    // for dropck to understand that we logically own a `T`.
36    //
37    // For details, see:
38    // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
39    _marker: PhantomData<T>,
40}
41
42/// `Unique` pointers are `Send` if `T` is `Send` because the data they
43/// reference is unaliased. Note that this aliasing invariant is
44/// unenforced by the type system; the abstraction using the
45/// `Unique` must enforce it.
46unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
47
48/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
49/// reference is unaliased. Note that this aliasing invariant is
50/// unenforced by the type system; the abstraction using the
51/// `Unique` must enforce it.
52unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
53
54impl<T: Sized> Unique<T> {
55    /// Creates a new `Unique` that is dangling, but well-aligned.
56    ///
57    /// This is useful for initializing types which lazily allocate, like
58    /// `Vec::new` does.
59    ///
60    /// Note that the pointer value may potentially represent a valid pointer to
61    /// a `T`, which means this must not be used as a "not yet initialized"
62    /// sentinel value. Types that lazily allocate must track initialization by
63    /// some other means.
64    #[must_use]
65    #[inline]
66    pub const fn dangling() -> Self {
67        // FIXME(const-hack) replace with `From`
68        Unique { pointer: NonNull::dangling(), _marker: PhantomData }
69    }
70}
71
72impl<T: ?Sized> Unique<T> {
73    /// Creates a new `Unique`.
74    ///
75    /// # Safety
76    ///
77    /// `ptr` must be non-null.
78    #[inline]
79    pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
80        // SAFETY: the caller must guarantee that `ptr` is non-null.
81        unsafe { Unique { pointer: NonNull::new_unchecked(ptr), _marker: PhantomData } }
82    }
83
84    /// Creates a new `Unique` if `ptr` is non-null.
85    #[inline]
86    pub const fn new(ptr: *mut T) -> Option<Self> {
87        if let Some(pointer) = NonNull::new(ptr) {
88            Some(Unique { pointer, _marker: PhantomData })
89        } else {
90            None
91        }
92    }
93
94    /// Acquires the underlying `*mut` pointer.
95    #[must_use = "`self` will be dropped if the result is not used"]
96    #[inline]
97    pub const fn as_ptr(self) -> *mut T {
98        self.pointer.as_ptr()
99    }
100
101    /// Acquires the underlying `*mut` pointer.
102    #[must_use = "`self` will be dropped if the result is not used"]
103    #[inline]
104    pub const fn as_non_null_ptr(self) -> NonNull<T> {
105        self.pointer
106    }
107
108    /// Dereferences the content.
109    ///
110    /// The resulting lifetime is bound to self so this behaves "as if"
111    /// it were actually an instance of T that is getting borrowed. If a longer
112    /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
113    ///
114    /// # Safety
115    ///
116    /// When calling this method, you have to ensure that
117    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
118    #[must_use]
119    #[inline]
120    pub const unsafe fn as_ref(&self) -> &T {
121        // SAFETY: the caller must guarantee that `self` meets all the
122        // requirements for a reference.
123        unsafe { self.pointer.as_ref() }
124    }
125
126    /// Mutably dereferences the content.
127    ///
128    /// The resulting lifetime is bound to self so this behaves "as if"
129    /// it were actually an instance of T that is getting borrowed. If a longer
130    /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
131    ///
132    /// # Safety
133    ///
134    /// When calling this method, you have to ensure that
135    /// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
136    #[must_use]
137    #[inline]
138    pub const unsafe fn as_mut(&mut self) -> &mut T {
139        // SAFETY: the caller must guarantee that `self` meets all the
140        // requirements for a mutable reference.
141        unsafe { self.pointer.as_mut() }
142    }
143
144    /// Casts to a pointer of another type.
145    #[must_use = "`self` will be dropped if the result is not used"]
146    #[inline]
147    pub const fn cast<U>(self) -> Unique<U> {
148        // FIXME(const-hack): replace with `From`
149        // SAFETY: is `NonNull`
150        Unique { pointer: self.pointer.cast(), _marker: PhantomData }
151    }
152}
153
154impl<T: ?Sized> Clone for Unique<T> {
155    #[inline]
156    fn clone(&self) -> Self {
157        *self
158    }
159}
160
161impl<T: ?Sized> Copy for Unique<T> {}
162
163impl<T: ?Sized> fmt::Debug for Unique<T> {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        fmt::Pointer::fmt(&self.as_ptr(), f)
166    }
167}
168
169impl<T: ?Sized> fmt::Pointer for Unique<T> {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        fmt::Pointer::fmt(&self.as_ptr(), f)
172    }
173}
174
175impl<T: ?Sized> From<&mut T> for Unique<T> {
176    /// Converts a `&mut T` to a `Unique<T>`.
177    ///
178    /// This conversion is infallible since references cannot be null.
179    #[inline]
180    fn from(reference: &mut T) -> Self {
181        Self::from(NonNull::from(reference))
182    }
183}
184
185impl<T: ?Sized> From<NonNull<T>> for Unique<T> {
186    /// Converts a `NonNull<T>` to a `Unique<T>`.
187    ///
188    /// This conversion is infallible since `NonNull` cannot be null.
189    #[inline]
190    fn from(pointer: NonNull<T>) -> Self {
191        Unique { pointer, _marker: PhantomData }
192    }
193}