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
73 // FIXME: rename to dangling() to match NonNull?
75 pub const fn empty() -> Self {
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 Unique { pointer: ptr as _, _marker: PhantomData }
92 /// Creates a new `Unique` if `ptr` is non-null.
94 pub fn new(ptr: *mut T) -> Option<Self> {
96 Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
102 /// Acquires the underlying `*mut` pointer.
104 pub const fn as_ptr(self) -> *mut T {
105 self.pointer as *mut T
108 /// Dereferences the content.
110 /// The resulting lifetime is bound to self so this behaves "as if"
111 /// it were actually an instance of T that is getting borrowed. If a longer
112 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
114 pub unsafe fn as_ref(&self) -> &T {
118 /// Mutably dereferences the content.
120 /// The resulting lifetime is bound to self so this behaves "as if"
121 /// it were actually an instance of T that is getting borrowed. If a longer
122 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
124 pub unsafe fn as_mut(&mut self) -> &mut T {
128 /// Casts to a pointer of another type.
130 pub const fn cast<U>(self) -> Unique<U> {
131 unsafe { Unique::new_unchecked(self.as_ptr() as *mut U) }
135 #[unstable(feature = "ptr_internals", issue = "none")]
136 impl<T: ?Sized> Clone for Unique<T> {
138 fn clone(&self) -> Self {
143 #[unstable(feature = "ptr_internals", issue = "none")]
144 impl<T: ?Sized> Copy for Unique<T> {}
146 #[unstable(feature = "ptr_internals", issue = "none")]
147 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
149 #[unstable(feature = "ptr_internals", issue = "none")]
150 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
152 #[unstable(feature = "ptr_internals", issue = "none")]
153 impl<T: ?Sized> fmt::Debug for Unique<T> {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 fmt::Pointer::fmt(&self.as_ptr(), f)
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized> fmt::Pointer 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> From<&mut T> for Unique<T> {
169 fn from(reference: &mut T) -> Self {
170 unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }