1 use crate::convert::From;
3 use crate::marker::{PhantomData, Unsize};
5 use crate::ops::{CoerceUnsized, DispatchFromDyn};
7 // ignore-tidy-undocumented-unsafe
9 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
10 /// of this wrapper owns the referent. Useful for building abstractions like
11 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
13 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
14 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
15 /// the kind of strong aliasing guarantees an instance of `T` can expect:
16 /// the referent of the pointer should not be modified without a unique path to
17 /// its owning Unique.
19 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
20 /// consider using `NonNull`, which has weaker semantics.
22 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
23 /// is never dereferenced. This is so that enums may use this forbidden value
24 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
25 /// However the pointer may still dangle if it isn't dereferenced.
27 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
28 /// for any type which upholds Unique's aliasing requirements.
30 feature = "ptr_internals",
32 reason = "use `NonNull` instead and consider `PhantomData<T>` \
33 (if you also use `#[may_dangle]`), `Send`, and/or `Sync`"
37 #[rustc_layout_scalar_valid_range_start(1)]
38 pub struct Unique<T: ?Sized> {
40 // NOTE: this marker has no consequences for variance, but is necessary
41 // for dropck to understand that we logically own a `T`.
44 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
45 _marker: PhantomData<T>,
48 /// `Unique` pointers are `Send` if `T` is `Send` 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.
52 #[unstable(feature = "ptr_internals", issue = "none")]
53 unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
55 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
56 /// reference is unaliased. Note that this aliasing invariant is
57 /// unenforced by the type system; the abstraction using the
58 /// `Unique` must enforce it.
59 #[unstable(feature = "ptr_internals", issue = "none")]
60 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
62 #[unstable(feature = "ptr_internals", issue = "none")]
63 impl<T: Sized> Unique<T> {
64 /// Creates a new `Unique` that is dangling, but well-aligned.
66 /// This is useful for initializing types which lazily allocate, like
69 /// Note that the pointer value may potentially represent a valid pointer to
70 /// a `T`, which means this must not be used as a "not yet initialized"
71 /// sentinel value. Types that lazily allocate must track initialization by
74 pub const fn dangling() -> Self {
75 // SAFETY: mem::align_of() returns a valid, non-null pointer. The
76 // conditions to call new_unchecked() are thus respected.
77 unsafe { Unique::new_unchecked(mem::align_of::<T>() as *mut T) }
81 #[unstable(feature = "ptr_internals", issue = "none")]
82 impl<T: ?Sized> Unique<T> {
83 /// Creates a new `Unique`.
87 /// `ptr` must be non-null.
89 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
90 // SAFETY: the caller must guarantee that `ptr` is non-null.
91 unsafe { Unique { pointer: ptr as _, _marker: PhantomData } }
94 /// Creates a new `Unique` if `ptr` is non-null.
96 pub fn new(ptr: *mut T) -> Option<Self> {
98 // SAFETY: The pointer has already been checked and is not null.
99 Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
105 /// Acquires the underlying `*mut` pointer.
107 pub const fn as_ptr(self) -> *mut T {
108 self.pointer as *mut T
111 /// Dereferences the content.
113 /// The resulting lifetime is bound to self so this behaves "as if"
114 /// it were actually an instance of T that is getting borrowed. If a longer
115 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
117 pub unsafe fn as_ref(&self) -> &T {
118 // SAFETY: the caller must guarantee that `self` meets all the
119 // requirements for a reference.
120 unsafe { &*self.as_ptr() }
123 /// Mutably dereferences the content.
125 /// The resulting lifetime is bound to self so this behaves "as if"
126 /// it were actually an instance of T that is getting borrowed. If a longer
127 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
129 pub 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 { &mut *self.as_ptr() }
135 /// Casts to a pointer of another type.
137 pub const fn cast<U>(self) -> Unique<U> {
138 // SAFETY: Unique::new_unchecked() creates a new unique and needs
139 // the given pointer to not be null.
140 // Since we are passing self as a pointer, it cannot be null.
141 unsafe { Unique::new_unchecked(self.as_ptr() as *mut U) }
145 #[unstable(feature = "ptr_internals", issue = "none")]
146 impl<T: ?Sized> Clone for Unique<T> {
148 fn clone(&self) -> Self {
153 #[unstable(feature = "ptr_internals", issue = "none")]
154 impl<T: ?Sized> Copy for Unique<T> {}
156 #[unstable(feature = "ptr_internals", issue = "none")]
157 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
162 #[unstable(feature = "ptr_internals", issue = "none")]
163 impl<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)
169 #[unstable(feature = "ptr_internals", issue = "none")]
170 impl<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)
176 #[unstable(feature = "ptr_internals", issue = "none")]
177 impl<T: ?Sized> From<&mut T> for Unique<T> {
179 fn from(reference: &mut T) -> Self {
180 // SAFETY: A mutable reference cannot be null
181 unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }