1 use crate::convert::From;
2 use crate::ops::{CoerceUnsized, DispatchFromDyn};
4 use crate::marker::{PhantomData, Unsize};
6 use crate::ptr::NonNull;
8 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
9 /// of this wrapper owns the referent. Useful for building abstractions like
10 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
12 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
13 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
14 /// the kind of strong aliasing guarantees an instance of `T` can expect:
15 /// the referent of the pointer should not be modified without a unique path to
16 /// its owning Unique.
18 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
19 /// consider using `NonNull`, which has weaker semantics.
21 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
22 /// is never dereferenced. This is so that enums may use this forbidden value
23 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
24 /// However the pointer may still dangle if it isn't dereferenced.
26 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
27 /// for any type which upholds Unique's aliasing requirements.
28 #[unstable(feature = "ptr_internals", issue = "0",
29 reason = "use `NonNull` instead and consider `PhantomData<T>` \
30 (if you also use `#[may_dangle]`), `Send`, and/or `Sync`")]
33 #[rustc_layout_scalar_valid_range_start(1)]
34 pub struct Unique<T: ?Sized> {
36 // NOTE: this marker has no consequences for variance, but is necessary
37 // for dropck to understand that we logically own a `T`.
40 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
41 _marker: PhantomData<T>,
44 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
45 /// reference is unaliased. Note that this aliasing invariant is
46 /// unenforced by the type system; the abstraction using the
47 /// `Unique` must enforce it.
48 #[unstable(feature = "ptr_internals", issue = "0")]
49 unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
51 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
52 /// reference is unaliased. Note that this aliasing invariant is
53 /// unenforced by the type system; the abstraction using the
54 /// `Unique` must enforce it.
55 #[unstable(feature = "ptr_internals", issue = "0")]
56 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
58 #[unstable(feature = "ptr_internals", issue = "0")]
59 impl<T: Sized> Unique<T> {
60 /// Creates a new `Unique` that is dangling, but well-aligned.
62 /// This is useful for initializing types which lazily allocate, like
65 /// Note that the pointer value may potentially represent a valid pointer to
66 /// a `T`, which means this must not be used as a "not yet initialized"
67 /// sentinel value. Types that lazily allocate must track initialization by
69 // FIXME: rename to dangling() to match NonNull?
71 pub const fn empty() -> Self {
73 Unique::new_unchecked(mem::align_of::<T>() as *mut T)
78 #[unstable(feature = "ptr_internals", issue = "0")]
79 impl<T: ?Sized> Unique<T> {
80 /// Creates a new `Unique`.
84 /// `ptr` must be non-null.
86 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
87 Unique { pointer: ptr as _, _marker: PhantomData }
90 /// Creates a new `Unique` if `ptr` is non-null.
92 pub fn new(ptr: *mut T) -> Option<Self> {
94 Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
100 /// Acquires the underlying `*mut` pointer.
102 pub const fn as_ptr(self) -> *mut T {
103 self.pointer as *mut T
106 /// Dereferences the content.
108 /// The resulting lifetime is bound to self so this behaves "as if"
109 /// it were actually an instance of T that is getting borrowed. If a longer
110 /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
112 pub unsafe fn as_ref(&self) -> &T {
116 /// Mutably dereferences the content.
118 /// The resulting lifetime is bound to self so this behaves "as if"
119 /// it were actually an instance of T that is getting borrowed. If a longer
120 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
122 pub unsafe fn as_mut(&mut self) -> &mut T {
127 #[unstable(feature = "ptr_internals", issue = "0")]
128 impl<T: ?Sized> Clone for Unique<T> {
130 fn clone(&self) -> Self {
135 #[unstable(feature = "ptr_internals", issue = "0")]
136 impl<T: ?Sized> Copy for Unique<T> { }
138 #[unstable(feature = "ptr_internals", issue = "0")]
139 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
141 #[unstable(feature = "ptr_internals", issue = "0")]
142 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }
144 #[unstable(feature = "ptr_internals", issue = "0")]
145 impl<T: ?Sized> fmt::Debug for Unique<T> {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 fmt::Pointer::fmt(&self.as_ptr(), f)
151 #[unstable(feature = "ptr_internals", issue = "0")]
152 impl<T: ?Sized> fmt::Pointer for Unique<T> {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 fmt::Pointer::fmt(&self.as_ptr(), f)
158 #[unstable(feature = "ptr_internals", issue = "0")]
159 impl<T: ?Sized> From<&mut T> for Unique<T> {
161 fn from(reference: &mut T) -> Self {
162 unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
166 #[unstable(feature = "ptr_internals", issue = "0")]
167 impl<T: ?Sized> From<&T> for Unique<T> {
169 fn from(reference: &T) -> Self {
170 unsafe { Unique { pointer: reference as *const T, _marker: PhantomData } }
174 #[unstable(feature = "ptr_internals", issue = "0")]
175 impl<T: ?Sized> From<NonNull<T>> for Unique<T> {
177 fn from(p: NonNull<T>) -> Self {
178 unsafe { Unique::new_unchecked(p.as_ptr()) }