]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr/unique.rs
Deny unsafe ops in unsafe fns, part 6
[rust.git] / src / libcore / 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 // ignore-tidy-undocumented-unsafe
8
9 /// A wrapper around a raw non-null `*mut T` that indicates that the possessor
10 /// of this wrapper owns the referent. Useful for building abstractions like
11 /// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
12 ///
13 /// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
14 /// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
15 /// the kind of strong aliasing guarantees an instance of `T` can expect:
16 /// the referent of the pointer should not be modified without a unique path to
17 /// its owning Unique.
18 ///
19 /// If you're uncertain of whether it's correct to use `Unique` for your purposes,
20 /// consider using `NonNull`, which has weaker semantics.
21 ///
22 /// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
23 /// is never dereferenced. This is so that enums may use this forbidden value
24 /// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
25 /// However the pointer may still dangle if it isn't dereferenced.
26 ///
27 /// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
28 /// for any type which upholds Unique's aliasing requirements.
29 #[unstable(
30     feature = "ptr_internals",
31     issue = "none",
32     reason = "use `NonNull` instead and consider `PhantomData<T>` \
33               (if you also use `#[may_dangle]`), `Send`, and/or `Sync`"
34 )]
35 #[doc(hidden)]
36 #[repr(transparent)]
37 #[rustc_layout_scalar_valid_range_start(1)]
38 pub struct Unique<T: ?Sized> {
39     pointer: *const T,
40     // NOTE: this marker has no consequences for variance, but is necessary
41     // for dropck to understand that we logically own a `T`.
42     //
43     // For details, see:
44     // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
45     _marker: PhantomData<T>,
46 }
47
48 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
49 /// reference is unaliased. Note that this aliasing invariant is
50 /// unenforced by the type system; the abstraction using the
51 /// `Unique` must enforce it.
52 #[unstable(feature = "ptr_internals", issue = "none")]
53 unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
54
55 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
56 /// reference is unaliased. Note that this aliasing invariant is
57 /// unenforced by the type system; the abstraction using the
58 /// `Unique` must enforce it.
59 #[unstable(feature = "ptr_internals", issue = "none")]
60 unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
61
62 #[unstable(feature = "ptr_internals", issue = "none")]
63 impl<T: Sized> Unique<T> {
64     /// Creates a new `Unique` that is dangling, but well-aligned.
65     ///
66     /// This is useful for initializing types which lazily allocate, like
67     /// `Vec::new` does.
68     ///
69     /// Note that the pointer value may potentially represent a valid pointer to
70     /// a `T`, which means this must not be used as a "not yet initialized"
71     /// sentinel value. Types that lazily allocate must track initialization by
72     /// some other means.
73     #[inline]
74     pub const fn dangling() -> Self {
75         // SAFETY: mem::align_of() returns a valid, non-null pointer. The
76         // conditions to call new_unchecked() are thus respected.
77         unsafe { Unique::new_unchecked(mem::align_of::<T>() as *mut T) }
78     }
79 }
80
81 #[unstable(feature = "ptr_internals", issue = "none")]
82 impl<T: ?Sized> Unique<T> {
83     /// Creates a new `Unique`.
84     ///
85     /// # Safety
86     ///
87     /// `ptr` must be non-null.
88     #[inline]
89     pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
90         // SAFETY: the caller must guarantee that `ptr` is non-null.
91         unsafe { Unique { pointer: ptr as _, _marker: PhantomData } }
92     }
93
94     /// Creates a new `Unique` if `ptr` is non-null.
95     #[inline]
96     pub fn new(ptr: *mut T) -> Option<Self> {
97         if !ptr.is_null() {
98             // SAFETY: The pointer has already been checked and is not null.
99             Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
100         } else {
101             None
102         }
103     }
104
105     /// Acquires the underlying `*mut` pointer.
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     #[inline]
117     pub unsafe fn as_ref(&self) -> &T {
118         // SAFETY: the caller must guarantee that `self` meets all the
119         // requirements for a reference.
120         unsafe { &*self.as_ptr() }
121     }
122
123     /// Mutably dereferences the content.
124     ///
125     /// The resulting lifetime is bound to self so this behaves "as if"
126     /// it were actually an instance of T that is getting borrowed. If a longer
127     /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
128     #[inline]
129     pub unsafe fn as_mut(&mut self) -> &mut T {
130         // SAFETY: the caller must guarantee that `self` meets all the
131         // requirements for a mutable reference.
132         unsafe { &mut *self.as_ptr() }
133     }
134
135     /// Casts to a pointer of another type.
136     #[inline]
137     pub const fn cast<U>(self) -> Unique<U> {
138         // SAFETY: Unique::new_unchecked() creates a new unique and needs
139         // the given pointer to not be null.
140         // Since we are passing self as a pointer, it cannot be null.
141         unsafe { Unique::new_unchecked(self.as_ptr() as *mut U) }
142     }
143 }
144
145 #[unstable(feature = "ptr_internals", issue = "none")]
146 impl<T: ?Sized> Clone for Unique<T> {
147     #[inline]
148     fn clone(&self) -> Self {
149         *self
150     }
151 }
152
153 #[unstable(feature = "ptr_internals", issue = "none")]
154 impl<T: ?Sized> Copy for Unique<T> {}
155
156 #[unstable(feature = "ptr_internals", issue = "none")]
157 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
158
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
161
162 #[unstable(feature = "ptr_internals", issue = "none")]
163 impl<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
169 #[unstable(feature = "ptr_internals", issue = "none")]
170 impl<T: ?Sized> fmt::Pointer for Unique<T> {
171     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172         fmt::Pointer::fmt(&self.as_ptr(), f)
173     }
174 }
175
176 #[unstable(feature = "ptr_internals", issue = "none")]
177 impl<T: ?Sized> From<&mut T> for Unique<T> {
178     #[inline]
179     fn from(reference: &mut T) -> Self {
180         // SAFETY: A mutable reference cannot be null
181         unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
182     }
183 }