]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr/unique.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[rust.git] / src / libcore / ptr / unique.rs
1 use crate::convert::From;
2 use crate::ops::{CoerceUnsized, DispatchFromDyn};
3 use crate::fmt;
4 use crate::marker::{PhantomData, Unsize};
5 use crate::mem;
6 use crate::ptr::NonNull;
7
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>`.
11 ///
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.
17 ///
18 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
19 /// consider using `NonNull`, which has weaker semantics.
20 ///
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.
25 ///
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`")]
31 #[doc(hidden)]
32 #[repr(transparent)]
33 #[rustc_layout_scalar_valid_range_start(1)]
34 pub struct Unique<T: ?Sized> {
35     pointer: *const T,
36     // NOTE: this marker has no consequences for variance, but is necessary
37     // for dropck to understand that we logically own a `T`.
38     //
39     // For details, see:
40     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
41     _marker: PhantomData<T>,
42 }
43
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> { }
50
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> { }
57
58 #[unstable(feature = "ptr_internals", issue = "0")]
59 impl<T: Sized> Unique<T> {
60     /// Creates a new `Unique` that is dangling, but well-aligned.
61     ///
62     /// This is useful for initializing types which lazily allocate, like
63     /// `Vec::new` does.
64     ///
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
68     /// some other means.
69     // FIXME: rename to dangling() to match NonNull?
70     #[inline]
71     pub const fn empty() -> Self {
72         unsafe {
73             Unique::new_unchecked(mem::align_of::<T>() as *mut T)
74         }
75     }
76 }
77
78 #[unstable(feature = "ptr_internals", issue = "0")]
79 impl<T: ?Sized> Unique<T> {
80     /// Creates a new `Unique`.
81     ///
82     /// # Safety
83     ///
84     /// `ptr` must be non-null.
85     #[inline]
86     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
87         Unique { pointer: ptr as _, _marker: PhantomData }
88     }
89
90     /// Creates a new `Unique` if `ptr` is non-null.
91     #[inline]
92     pub fn new(ptr: *mut T) -> Option<Self> {
93         if !ptr.is_null() {
94             Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
95         } else {
96             None
97         }
98     }
99
100     /// Acquires the underlying `*mut` pointer.
101     #[inline]
102     pub const fn as_ptr(self) -> *mut T {
103         self.pointer as *mut T
104     }
105
106     /// Dereferences the content.
107     ///
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()`.
111     #[inline]
112     pub unsafe fn as_ref(&self) -> &T {
113         &*self.as_ptr()
114     }
115
116     /// Mutably dereferences the content.
117     ///
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()`.
121     #[inline]
122     pub unsafe fn as_mut(&mut self) -> &mut T {
123         &mut *self.as_ptr()
124     }
125 }
126
127 #[unstable(feature = "ptr_internals", issue = "0")]
128 impl<T: ?Sized> Clone for Unique<T> {
129     #[inline]
130     fn clone(&self) -> Self {
131         *self
132     }
133 }
134
135 #[unstable(feature = "ptr_internals", issue = "0")]
136 impl<T: ?Sized> Copy for Unique<T> { }
137
138 #[unstable(feature = "ptr_internals", issue = "0")]
139 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }
140
141 #[unstable(feature = "ptr_internals", issue = "0")]
142 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }
143
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)
148     }
149 }
150
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)
155     }
156 }
157
158 #[unstable(feature = "ptr_internals", issue = "0")]
159 impl<T: ?Sized> From<&mut T> for Unique<T> {
160     #[inline]
161     fn from(reference: &mut T) -> Self {
162         unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
163     }
164 }
165
166 #[unstable(feature = "ptr_internals", issue = "0")]
167 impl<T: ?Sized> From<&T> for Unique<T> {
168     #[inline]
169     fn from(reference: &T) -> Self {
170         unsafe { Unique { pointer: reference as *const T, _marker: PhantomData } }
171     }
172 }
173
174 #[unstable(feature = "ptr_internals", issue = "0")]
175 impl<T: ?Sized> From<NonNull<T>> for Unique<T> {
176     #[inline]
177     fn from(p: NonNull<T>) -> Self {
178         unsafe { Unique::new_unchecked(p.as_ptr()) }
179     }
180 }