rune_alloc/ptr/unique.rs
1use core::fmt;
2use core::marker::PhantomData;
3
4use crate::ptr::NonNull;
5
6/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
7/// of this wrapper owns the referent. Useful for building abstractions like
8/// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
9///
10/// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
11/// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
12/// the kind of strong aliasing guarantees an instance of `T` can expect:
13/// the referent of the pointer should not be modified without a unique path to
14/// its owning Unique.
15///
16/// If you're uncertain of whether it's correct to use `Unique` for your purposes,
17/// consider using `NonNull`, which has weaker semantics.
18///
19/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
20/// is never dereferenced. This is so that enums may use this forbidden value
21/// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
22/// However the pointer may still dangle if it isn't dereferenced.
23///
24/// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
25/// for any type which upholds Unique's aliasing requirements.
26#[doc(hidden)]
27#[repr(transparent)]
28pub struct Unique<T: ?Sized> {
29 pointer: NonNull<T>,
30 // NOTE: this marker has no consequences for variance, but is necessary
31 // for dropck to understand that we logically own a `T`.
32 //
33 // For details, see:
34 // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
35 _marker: PhantomData<T>,
36}
37
38/// `Unique` pointers are `Send` if `T` is `Send` because the data they
39/// reference is unaliased. Note that this aliasing invariant is
40/// unenforced by the type system; the abstraction using the
41/// `Unique` must enforce it.
42unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
43
44/// `Unique` pointers are `Sync` if `T` is `Sync` 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.
48unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
49
50impl<T: Sized> Unique<T> {
51 /// Creates a new `Unique` that is dangling, but well-aligned.
52 ///
53 /// This is useful for initializing types which lazily allocate, like
54 /// `Vec::new` does.
55 ///
56 /// Note that the pointer value may potentially represent a valid pointer to
57 /// a `T`, which means this must not be used as a "not yet initialized"
58 /// sentinel value. Types that lazily allocate must track initialization by
59 /// some other means.
60 #[must_use]
61 #[inline]
62 pub const fn dangling() -> Self {
63 // FIXME(const-hack) replace with `From`
64 Unique {
65 pointer: NonNull::dangling(),
66 _marker: PhantomData,
67 }
68 }
69}
70
71impl<T> Unique<[T]> {
72 /// Unique pointer for an empty slice.
73 #[must_use]
74 #[inline]
75 pub(crate) fn dangling_empty_slice() -> Self {
76 let pointer = NonNull::<T>::dangling();
77
78 Unique {
79 pointer: NonNull::slice_from_raw_parts(pointer, 0),
80 _marker: PhantomData,
81 }
82 }
83}
84
85impl<T: ?Sized> Unique<T> {
86 /// Creates a new `Unique`.
87 ///
88 /// # Safety
89 ///
90 /// `ptr` must be non-null.
91 #[inline]
92 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
93 // SAFETY: the caller must guarantee that `ptr` is non-null.
94 unsafe {
95 Unique {
96 pointer: NonNull::new_unchecked(ptr),
97 _marker: PhantomData,
98 }
99 }
100 }
101
102 /// Creates a new `Unique` if `ptr` is non-null.
103 #[inline]
104 pub fn new(ptr: *mut T) -> Option<Self> {
105 NonNull::new(ptr).map(|pointer| Unique {
106 pointer,
107 _marker: PhantomData,
108 })
109 }
110
111 /// Acquires the underlying `*mut` pointer.
112 #[must_use = "`self` will be dropped if the result is not used"]
113 #[inline]
114 pub const fn as_ptr(self) -> *mut T {
115 self.pointer.as_ptr()
116 }
117
118 /// Dereferences the content.
119 ///
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 `&*my_ptr.as_ptr()`.
123 #[must_use]
124 #[inline]
125 pub unsafe fn as_ref(&self) -> &T {
126 // SAFETY: the caller must guarantee that `self` meets all the
127 // requirements for a reference.
128 unsafe { self.pointer.as_ref() }
129 }
130
131 /// Mutably dereferences the content.
132 ///
133 /// The resulting lifetime is bound to self so this behaves "as if"
134 /// it were actually an instance of T that is getting borrowed. If a longer
135 /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
136 #[must_use]
137 #[inline]
138 pub unsafe fn as_mut(&mut self) -> &mut T {
139 // SAFETY: the caller must guarantee that `self` meets all the
140 // requirements for a mutable reference.
141 unsafe { self.pointer.as_mut() }
142 }
143
144 /// Casts to a pointer of another type.
145 #[must_use = "`self` will be dropped if the result is not used"]
146 #[inline]
147 pub const fn cast<U>(self) -> Unique<U> {
148 // FIXME(const-hack): replace with `From`
149 // SAFETY: is `NonNull`
150 unsafe { Unique::new_unchecked(self.pointer.cast().as_ptr()) }
151 }
152}
153
154impl<T: ?Sized> Clone for Unique<T> {
155 #[inline]
156 fn clone(&self) -> Self {
157 *self
158 }
159}
160
161impl<T: ?Sized> Copy for Unique<T> {}
162
163impl<T: ?Sized> fmt::Debug for Unique<T> {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 fmt::Pointer::fmt(&self.as_ptr(), f)
166 }
167}
168
169impl<T: ?Sized> fmt::Pointer for Unique<T> {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 fmt::Pointer::fmt(&self.as_ptr(), f)
172 }
173}
174
175impl<T: ?Sized> From<&mut T> for Unique<T> {
176 /// Converts a `&mut T` to a `Unique<T>`.
177 ///
178 /// This conversion is infallible since references cannot be null.
179 #[inline]
180 fn from(reference: &mut T) -> Self {
181 Self::from(NonNull::from(reference))
182 }
183}
184
185impl<T: ?Sized> 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 {
192 pointer,
193 _marker: PhantomData,
194 }
195 }
196}
197
198impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
199 #[inline]
200 fn from(unique: Unique<T>) -> Self {
201 // SAFETY: A Unique pointer cannot be null, so the conditions for
202 // new_unchecked() are respected.
203 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
204 }
205}