1 use crate::convert::From;
3 use crate::marker::{PhantomData, Unsize};
5 use crate::ops::{CoerceUnsized, DispatchFromDyn};
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 #[rustc_layout_scalar_valid_range_start(1)]
36 pub struct Unique<T: ?Sized> {
38 // NOTE: this marker has no consequences for variance, but is necessary
39 // for dropck to understand that we logically own a `T`.
42 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
43 _marker: PhantomData<T>,
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")]
51 unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
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")]
58 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
60 #[unstable(feature = "ptr_internals", issue = "none")]
61 impl<T: Sized> Unique<T> {
62 /// Creates a new `Unique` that is dangling, but well-aligned.
64 /// This is useful for initializing types which lazily allocate, like
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
73 pub const fn dangling() -> Self {
74 // SAFETY: mem::align_of() returns a valid, non-null pointer. The
75 // conditions to call new_unchecked() are thus respected.
76 unsafe { Unique::new_unchecked(mem::align_of::<T>() as *mut T) }
80 #[unstable(feature = "ptr_internals", issue = "none")]
81 impl<T: ?Sized> Unique<T> {
82 /// Creates a new `Unique`.
86 /// `ptr` must be non-null.
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: ptr as _, _marker: PhantomData } }
93 /// Creates a new `Unique` if `ptr` is non-null.
95 pub fn new(ptr: *mut T) -> Option<Self> {
97 // SAFETY: The pointer has already been checked and is not null.
98 Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
104 /// Acquires the underlying `*mut` pointer.
105 #[must_use = "`self` will be dropped if the result is not used"]
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()`.
118 pub unsafe fn as_ref(&self) -> &T {
119 // SAFETY: the caller must guarantee that `self` meets all the
120 // requirements for a reference.
121 unsafe { &*self.as_ptr() }
124 /// Mutably dereferences the content.
126 /// The resulting lifetime is bound to self so this behaves "as if"
127 /// it were actually an instance of T that is getting borrowed. If a longer
128 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
131 pub unsafe fn as_mut(&mut self) -> &mut T {
132 // SAFETY: the caller must guarantee that `self` meets all the
133 // requirements for a mutable reference.
134 unsafe { &mut *self.as_ptr() }
137 /// Casts to a pointer of another type.
138 #[must_use = "`self` will be dropped if the result is not used"]
140 pub const fn cast<U>(self) -> Unique<U> {
141 // SAFETY: Unique::new_unchecked() creates a new unique and needs
142 // the given pointer to not be null.
143 // Since we are passing self as a pointer, it cannot be null.
144 unsafe { Unique::new_unchecked(self.as_ptr() as *mut U) }
148 #[unstable(feature = "ptr_internals", issue = "none")]
149 impl<T: ?Sized> Clone for Unique<T> {
151 fn clone(&self) -> Self {
156 #[unstable(feature = "ptr_internals", issue = "none")]
157 impl<T: ?Sized> Copy for Unique<T> {}
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
162 #[unstable(feature = "ptr_internals", issue = "none")]
163 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
165 #[unstable(feature = "ptr_internals", issue = "none")]
166 impl<T: ?Sized> fmt::Debug for Unique<T> {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 fmt::Pointer::fmt(&self.as_ptr(), f)
172 #[unstable(feature = "ptr_internals", issue = "none")]
173 impl<T: ?Sized> fmt::Pointer for Unique<T> {
174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 fmt::Pointer::fmt(&self.as_ptr(), f)
179 #[unstable(feature = "ptr_internals", issue = "none")]
180 impl<T: ?Sized> const From<&mut T> for Unique<T> {
182 fn from(reference: &mut T) -> Self {
183 // SAFETY: A mutable reference cannot be null
184 unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }