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