core/ptr/
unique.rs

1use crate::fmt;
2use crate::marker::{PhantomData, 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)]
35// Lang item used experimentally by Miri to define the semantics of `Unique`.
36#[lang = "ptr_unique"]
37pub struct Unique<T: ?Sized> {
38    pointer: NonNull<T>,
39    // NOTE: this marker has no consequences for variance, but is necessary
40    // for dropck to understand that we logically own a `T`.
41    //
42    // For details, see:
43    // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
44    _marker: PhantomData<T>,
45}
46
47/// `Unique` pointers are `Send` if `T` is `Send` because the data they
48/// reference is unaliased. Note that this aliasing invariant is
49/// unenforced by the type system; the abstraction using the
50/// `Unique` must enforce it.
51#[unstable(feature = "ptr_internals", issue = "none")]
52unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
53
54/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
55/// reference is unaliased. Note that this aliasing invariant is
56/// unenforced by the type system; the abstraction using the
57/// `Unique` must enforce it.
58#[unstable(feature = "ptr_internals", issue = "none")]
59unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
60
61#[unstable(feature = "ptr_internals", issue = "none")]
62impl<T: Sized> Unique<T> {
63    /// Creates a new `Unique` that is dangling, but well-aligned.
64    ///
65    /// This is useful for initializing types which lazily allocate, like
66    /// `Vec::new` does.
67    ///
68    /// Note that the pointer value may potentially represent a valid pointer to
69    /// a `T`, which means this must not be used as a "not yet initialized"
70    /// sentinel value. Types that lazily allocate must track initialization by
71    /// some other means.
72    #[must_use]
73    #[inline]
74    pub const fn dangling() -> Self {
75        // FIXME(const-hack) replace with `From`
76        Unique { pointer: NonNull::dangling(), _marker: PhantomData }
77    }
78}
79
80#[unstable(feature = "ptr_internals", issue = "none")]
81impl<T: ?Sized> Unique<T> {
82    /// Creates a new `Unique`.
83    ///
84    /// # Safety
85    ///
86    /// `ptr` must be non-null.
87    #[inline]
88    pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
89        // SAFETY: the caller must guarantee that `ptr` is non-null.
90        unsafe { Unique { pointer: NonNull::new_unchecked(ptr), _marker: PhantomData } }
91    }
92
93    /// Creates a new `Unique` if `ptr` is non-null.
94    #[inline]
95    pub const fn new(ptr: *mut T) -> Option<Self> {
96        if let Some(pointer) = NonNull::new(ptr) {
97            Some(Unique { pointer, _marker: PhantomData })
98        } else {
99            None
100        }
101    }
102
103    /// Acquires the underlying `*mut` pointer.
104    #[must_use = "`self` will be dropped if the result is not used"]
105    #[inline]
106    pub const fn as_ptr(self) -> *mut T {
107        self.pointer.as_ptr()
108    }
109
110    /// Acquires the underlying `*mut` pointer.
111    #[must_use = "`self` will be dropped if the result is not used"]
112    #[inline]
113    pub const fn as_non_null_ptr(self) -> NonNull<T> {
114        self.pointer
115    }
116
117    /// Dereferences the content.
118    ///
119    /// The resulting lifetime is bound to self so this behaves "as if"
120    /// it were actually an instance of T that is getting borrowed. If a longer
121    /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
122    #[must_use]
123    #[inline]
124    pub const unsafe fn as_ref(&self) -> &T {
125        // SAFETY: the caller must guarantee that `self` meets all the
126        // requirements for a reference.
127        unsafe { self.pointer.as_ref() }
128    }
129
130    /// Mutably dereferences the content.
131    ///
132    /// The resulting lifetime is bound to self so this behaves "as if"
133    /// it were actually an instance of T that is getting borrowed. If a longer
134    /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
135    #[must_use]
136    #[inline]
137    pub const unsafe fn as_mut(&mut self) -> &mut T {
138        // SAFETY: the caller must guarantee that `self` meets all the
139        // requirements for a mutable reference.
140        unsafe { self.pointer.as_mut() }
141    }
142
143    /// Casts to a pointer of another type.
144    #[must_use = "`self` will be dropped if the result is not used"]
145    #[inline]
146    pub const fn cast<U>(self) -> Unique<U> {
147        // FIXME(const-hack): replace with `From`
148        // SAFETY: is `NonNull`
149        Unique { pointer: self.pointer.cast(), _marker: PhantomData }
150    }
151}
152
153#[unstable(feature = "ptr_internals", issue = "none")]
154impl<T: ?Sized> Clone for Unique<T> {
155    #[inline]
156    fn clone(&self) -> Self {
157        *self
158    }
159}
160
161#[unstable(feature = "ptr_internals", issue = "none")]
162impl<T: ?Sized> Copy for Unique<T> {}
163
164#[unstable(feature = "ptr_internals", issue = "none")]
165impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
166
167#[unstable(feature = "ptr_internals", issue = "none")]
168impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
169
170#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
171unsafe impl<T: ?Sized> PinCoerceUnsized for Unique<T> {}
172
173#[unstable(feature = "ptr_internals", issue = "none")]
174impl<T: ?Sized> fmt::Debug for Unique<T> {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        fmt::Pointer::fmt(&self.as_ptr(), f)
177    }
178}
179
180#[unstable(feature = "ptr_internals", issue = "none")]
181impl<T: ?Sized> fmt::Pointer for Unique<T> {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        fmt::Pointer::fmt(&self.as_ptr(), f)
184    }
185}
186
187#[unstable(feature = "ptr_internals", issue = "none")]
188impl<T: ?Sized> From<&mut T> for Unique<T> {
189    /// Converts a `&mut T` to a `Unique<T>`.
190    ///
191    /// This conversion is infallible since references cannot be null.
192    #[inline]
193    fn from(reference: &mut T) -> Self {
194        Self::from(NonNull::from(reference))
195    }
196}
197
198#[unstable(feature = "ptr_internals", issue = "none")]
199impl<T: ?Sized> From<NonNull<T>> for Unique<T> {
200    /// Converts a `NonNull<T>` to a `Unique<T>`.
201    ///
202    /// This conversion is infallible since `NonNull` cannot be null.
203    #[inline]
204    fn from(pointer: NonNull<T>) -> Self {
205        Unique { pointer, _marker: PhantomData }
206    }
207}