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