]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/unique.rs
Auto merge of #91776 - matthiaskrgr:rollup-tlb4bw1, r=matthiaskrgr
[rust.git] / library / core / src / ptr / unique.rs
1 use crate::convert::From;
2 use crate::fmt;
3 use crate::marker::{PhantomData, Unsize};
4 use crate::mem;
5 use crate::ops::{CoerceUnsized, DispatchFromDyn};
6
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>`.
10 ///
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.
16 ///
17 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
18 /// consider using `NonNull`, which has weaker semantics.
19 ///
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.
24 ///
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.
27 #[unstable(
28     feature = "ptr_internals",
29     issue = "none",
30     reason = "use `NonNull` instead and consider `PhantomData<T>` \
31               (if you also use `#[may_dangle]`), `Send`, and/or `Sync`"
32 )]
33 #[doc(hidden)]
34 #[repr(transparent)]
35 #[rustc_layout_scalar_valid_range_start(1)]
36 pub struct Unique<T: ?Sized> {
37     pointer: *const T,
38     // NOTE: this marker has no consequences for variance, but is necessary
39     // for dropck to understand that we logically own a `T`.
40     //
41     // For details, see:
42     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
43     _marker: PhantomData<T>,
44 }
45
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> {}
52
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> {}
59
60 #[unstable(feature = "ptr_internals", issue = "none")]
61 impl<T: Sized> Unique<T> {
62     /// Creates a new `Unique` that is dangling, but well-aligned.
63     ///
64     /// This is useful for initializing types which lazily allocate, like
65     /// `Vec::new` does.
66     ///
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
70     /// some other means.
71     #[must_use]
72     #[inline]
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) }
77     }
78 }
79
80 #[unstable(feature = "ptr_internals", issue = "none")]
81 impl<T: ?Sized> Unique<T> {
82     /// Creates a new `Unique`.
83     ///
84     /// # Safety
85     ///
86     /// `ptr` must be non-null.
87     #[inline]
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 } }
91     }
92
93     /// Creates a new `Unique` if `ptr` is non-null.
94     #[inline]
95     pub fn new(ptr: *mut T) -> Option<Self> {
96         if !ptr.is_null() {
97             // SAFETY: The pointer has already been checked and is not null.
98             Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
99         } else {
100             None
101         }
102     }
103
104     /// Acquires the underlying `*mut` pointer.
105     #[must_use = "`self` will be dropped if the result is not used"]
106     #[inline]
107     pub const fn as_ptr(self) -> *mut T {
108         self.pointer as *mut T
109     }
110
111     /// Dereferences the content.
112     ///
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()`.
116     #[must_use]
117     #[inline]
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() }
122     }
123
124     /// Mutably dereferences the content.
125     ///
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()`.
129     #[must_use]
130     #[inline]
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() }
135     }
136
137     /// Casts to a pointer of another type.
138     #[must_use = "`self` will be dropped if the result is not used"]
139     #[inline]
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) }
145     }
146 }
147
148 #[unstable(feature = "ptr_internals", issue = "none")]
149 impl<T: ?Sized> Clone for Unique<T> {
150     #[inline]
151     fn clone(&self) -> Self {
152         *self
153     }
154 }
155
156 #[unstable(feature = "ptr_internals", issue = "none")]
157 impl<T: ?Sized> Copy for Unique<T> {}
158
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
161
162 #[unstable(feature = "ptr_internals", issue = "none")]
163 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
164
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)
169     }
170 }
171
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)
176     }
177 }
178
179 #[unstable(feature = "ptr_internals", issue = "none")]
180 impl<T: ?Sized> const From<&mut T> for Unique<T> {
181     #[inline]
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 } }
185     }
186 }