]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/unique.rs
Rollup merge of #95979 - lcnr:coherence-docs, r=compiler-errors
[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::ops::{CoerceUnsized, DispatchFromDyn};
5 use crate::ptr::NonNull;
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 pub struct Unique<T: ?Sized> {
36     pointer: NonNull<T>,
37     // NOTE: this marker has no consequences for variance, but is necessary
38     // for dropck to understand that we logically own a `T`.
39     //
40     // For details, see:
41     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
42     _marker: PhantomData<T>,
43 }
44
45 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
46 /// reference is unaliased. Note that this aliasing invariant is
47 /// unenforced by the type system; the abstraction using the
48 /// `Unique` must enforce it.
49 #[unstable(feature = "ptr_internals", issue = "none")]
50 unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
51
52 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
53 /// reference is unaliased. Note that this aliasing invariant is
54 /// unenforced by the type system; the abstraction using the
55 /// `Unique` must enforce it.
56 #[unstable(feature = "ptr_internals", issue = "none")]
57 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
58
59 #[unstable(feature = "ptr_internals", issue = "none")]
60 impl<T: Sized> Unique<T> {
61     /// Creates a new `Unique` that is dangling, but well-aligned.
62     ///
63     /// This is useful for initializing types which lazily allocate, like
64     /// `Vec::new` does.
65     ///
66     /// Note that the pointer value may potentially represent a valid pointer to
67     /// a `T`, which means this must not be used as a "not yet initialized"
68     /// sentinel value. Types that lazily allocate must track initialization by
69     /// some other means.
70     #[must_use]
71     #[inline]
72     pub const fn dangling() -> Self {
73         Self::from(NonNull::dangling())
74     }
75 }
76
77 #[unstable(feature = "ptr_internals", issue = "none")]
78 impl<T: ?Sized> Unique<T> {
79     /// Creates a new `Unique`.
80     ///
81     /// # Safety
82     ///
83     /// `ptr` must be non-null.
84     #[inline]
85     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
86         // SAFETY: the caller must guarantee that `ptr` is non-null.
87         unsafe { Unique { pointer: NonNull::new_unchecked(ptr), _marker: PhantomData } }
88     }
89
90     /// Creates a new `Unique` if `ptr` is non-null.
91     #[inline]
92     pub const fn new(ptr: *mut T) -> Option<Self> {
93         if let Some(pointer) = NonNull::new(ptr) {
94             Some(Unique { pointer, _marker: PhantomData })
95         } else {
96             None
97         }
98     }
99
100     /// Acquires the underlying `*mut` pointer.
101     #[must_use = "`self` will be dropped if the result is not used"]
102     #[inline]
103     pub const fn as_ptr(self) -> *mut T {
104         self.pointer.as_ptr()
105     }
106
107     /// Dereferences the content.
108     ///
109     /// The resulting lifetime is bound to self so this behaves "as if"
110     /// it were actually an instance of T that is getting borrowed. If a longer
111     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
112     #[must_use]
113     #[inline]
114     pub const unsafe fn as_ref(&self) -> &T {
115         // SAFETY: the caller must guarantee that `self` meets all the
116         // requirements for a reference.
117         unsafe { self.pointer.as_ref() }
118     }
119
120     /// Mutably dereferences the content.
121     ///
122     /// The resulting lifetime is bound to self so this behaves "as if"
123     /// it were actually an instance of T that is getting borrowed. If a longer
124     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
125     #[must_use]
126     #[inline]
127     pub const unsafe fn as_mut(&mut self) -> &mut T {
128         // SAFETY: the caller must guarantee that `self` meets all the
129         // requirements for a mutable reference.
130         unsafe { self.pointer.as_mut() }
131     }
132
133     /// Casts to a pointer of another type.
134     #[must_use = "`self` will be dropped if the result is not used"]
135     #[inline]
136     pub const fn cast<U>(self) -> Unique<U> {
137         Unique::from(self.pointer.cast())
138     }
139 }
140
141 #[unstable(feature = "ptr_internals", issue = "none")]
142 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
143 impl<T: ?Sized> const Clone for Unique<T> {
144     #[inline]
145     fn clone(&self) -> Self {
146         *self
147     }
148 }
149
150 #[unstable(feature = "ptr_internals", issue = "none")]
151 impl<T: ?Sized> Copy for Unique<T> {}
152
153 #[unstable(feature = "ptr_internals", issue = "none")]
154 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
155
156 #[unstable(feature = "ptr_internals", issue = "none")]
157 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
158
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized> fmt::Debug for Unique<T> {
161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162         fmt::Pointer::fmt(&self.as_ptr(), f)
163     }
164 }
165
166 #[unstable(feature = "ptr_internals", issue = "none")]
167 impl<T: ?Sized> fmt::Pointer for Unique<T> {
168     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169         fmt::Pointer::fmt(&self.as_ptr(), f)
170     }
171 }
172
173 #[unstable(feature = "ptr_internals", issue = "none")]
174 impl<T: ?Sized> const From<&mut T> for Unique<T> {
175     /// Converts a `&mut T` to a `Unique<T>`.
176     ///
177     /// This conversion is infallible since references cannot be null.
178     #[inline]
179     fn from(reference: &mut T) -> Self {
180         Self::from(NonNull::from(reference))
181     }
182 }
183
184 #[unstable(feature = "ptr_internals", issue = "none")]
185 impl<T: ?Sized> const From<NonNull<T>> for Unique<T> {
186     /// Converts a `NonNull<T>` to a `Unique<T>`.
187     ///
188     /// This conversion is infallible since `NonNull` cannot be null.
189     #[inline]
190     fn from(pointer: NonNull<T>) -> Self {
191         Unique { pointer, _marker: PhantomData }
192     }
193 }