1 use crate::convert::From;
3 use crate::marker::{PhantomData, Unsize};
4 use crate::ops::{CoerceUnsized, DispatchFromDyn};
5 use crate::ptr::NonNull;
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>`.
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.
17 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
18 /// consider using `NonNull`, which has weaker semantics.
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.
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.
28 feature = "ptr_internals",
30 reason = "use `NonNull` instead and consider `PhantomData<T>` \
31 (if you also use `#[may_dangle]`), `Send`, and/or `Sync`"
35 pub struct Unique<T: ?Sized> {
37 // NOTE: this marker has no consequences for variance, but is necessary
38 // for dropck to understand that we logically own a `T`.
41 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
42 _marker: PhantomData<T>,
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")]
50 unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
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")]
57 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
59 #[unstable(feature = "ptr_internals", issue = "none")]
60 impl<T: Sized> Unique<T> {
61 /// Creates a new `Unique` that is dangling, but well-aligned.
63 /// This is useful for initializing types which lazily allocate, like
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
72 pub const fn dangling() -> Self {
73 Self::from(NonNull::dangling())
77 #[unstable(feature = "ptr_internals", issue = "none")]
78 impl<T: ?Sized> Unique<T> {
79 /// Creates a new `Unique`.
83 /// `ptr` must be non-null.
85 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
86 // SAFETY: the caller must guarantee that `ptr` is non-null.
87 unsafe { Unique { pointer: NonNull::new_unchecked(ptr), _marker: PhantomData } }
90 /// Creates a new `Unique` if `ptr` is non-null.
92 pub const fn new(ptr: *mut T) -> Option<Self> {
93 if let Some(pointer) = NonNull::new(ptr) {
94 Some(Unique { pointer, _marker: PhantomData })
100 /// Acquires the underlying `*mut` pointer.
101 #[must_use = "`self` will be dropped if the result is not used"]
103 pub const fn as_ptr(self) -> *mut T {
104 self.pointer.as_ptr()
107 /// Dereferences the content.
109 /// The resulting lifetime is bound to self so this behaves "as if"
110 /// it were actually an instance of T that is getting borrowed. If a longer
111 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
114 pub const unsafe fn as_ref(&self) -> &T {
115 // SAFETY: the caller must guarantee that `self` meets all the
116 // requirements for a reference.
117 unsafe { self.pointer.as_ref() }
120 /// Mutably dereferences the content.
122 /// The resulting lifetime is bound to self so this behaves "as if"
123 /// it were actually an instance of T that is getting borrowed. If a longer
124 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
127 pub const unsafe fn as_mut(&mut self) -> &mut T {
128 // SAFETY: the caller must guarantee that `self` meets all the
129 // requirements for a mutable reference.
130 unsafe { self.pointer.as_mut() }
133 /// Casts to a pointer of another type.
134 #[must_use = "`self` will be dropped if the result is not used"]
136 pub const fn cast<U>(self) -> Unique<U> {
137 Unique::from(self.pointer.cast())
141 #[unstable(feature = "ptr_internals", issue = "none")]
142 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
143 impl<T: ?Sized> const Clone for Unique<T> {
145 fn clone(&self) -> Self {
150 #[unstable(feature = "ptr_internals", issue = "none")]
151 impl<T: ?Sized> Copy for Unique<T> {}
153 #[unstable(feature = "ptr_internals", issue = "none")]
154 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
156 #[unstable(feature = "ptr_internals", issue = "none")]
157 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized> fmt::Debug for Unique<T> {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 fmt::Pointer::fmt(&self.as_ptr(), f)
166 #[unstable(feature = "ptr_internals", issue = "none")]
167 impl<T: ?Sized> fmt::Pointer for Unique<T> {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 fmt::Pointer::fmt(&self.as_ptr(), f)
173 #[unstable(feature = "ptr_internals", issue = "none")]
174 impl<T: ?Sized> const From<&mut T> for Unique<T> {
175 /// Converts a `&mut T` to a `Unique<T>`.
177 /// This conversion is infallible since references cannot be null.
179 fn from(reference: &mut T) -> Self {
180 Self::from(NonNull::from(reference))
184 #[unstable(feature = "ptr_internals", issue = "none")]
185 impl<T: ?Sized> const From<NonNull<T>> for Unique<T> {
186 /// Converts a `NonNull<T>` to a `Unique<T>`.
188 /// This conversion is infallible since `NonNull` cannot be null.
190 fn from(pointer: NonNull<T>) -> Self {
191 Unique { pointer, _marker: PhantomData }