]> git.lizzy.rs Git - rust.git/blob - src/libcore/ptr/unique.rs
remove Unique::from for shared pointer types
[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     // FIXME: rename to dangling() to match NonNull?
74     #[inline]
75     pub const fn empty() -> Self {
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         Unique { pointer: ptr as _, _marker: PhantomData }
90     }
91
92     /// Creates a new `Unique` if `ptr` is non-null.
93     #[inline]
94     pub fn new(ptr: *mut T) -> Option<Self> {
95         if !ptr.is_null() {
96             Some(unsafe { Unique { pointer: ptr as _, _marker: PhantomData } })
97         } else {
98             None
99         }
100     }
101
102     /// Acquires the underlying `*mut` pointer.
103     #[inline]
104     pub const fn as_ptr(self) -> *mut T {
105         self.pointer as *mut T
106     }
107
108     /// Dereferences the content.
109     ///
110     /// The resulting lifetime is bound to self so this behaves "as if"
111     /// it were actually an instance of T that is getting borrowed. If a longer
112     /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
113     #[inline]
114     pub unsafe fn as_ref(&self) -> &T {
115         &*self.as_ptr()
116     }
117
118     /// Mutably 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 `&mut *my_ptr.as_ptr()`.
123     #[inline]
124     pub unsafe fn as_mut(&mut self) -> &mut T {
125         &mut *self.as_ptr()
126     }
127
128     /// Casts to a pointer of another type.
129     #[inline]
130     pub const fn cast<U>(self) -> Unique<U> {
131         unsafe { Unique::new_unchecked(self.as_ptr() as *mut U) }
132     }
133 }
134
135 #[unstable(feature = "ptr_internals", issue = "none")]
136 impl<T: ?Sized> Clone for Unique<T> {
137     #[inline]
138     fn clone(&self) -> Self {
139         *self
140     }
141 }
142
143 #[unstable(feature = "ptr_internals", issue = "none")]
144 impl<T: ?Sized> Copy for Unique<T> {}
145
146 #[unstable(feature = "ptr_internals", issue = "none")]
147 impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
148
149 #[unstable(feature = "ptr_internals", issue = "none")]
150 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> {}
151
152 #[unstable(feature = "ptr_internals", issue = "none")]
153 impl<T: ?Sized> fmt::Debug for Unique<T> {
154     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155         fmt::Pointer::fmt(&self.as_ptr(), f)
156     }
157 }
158
159 #[unstable(feature = "ptr_internals", issue = "none")]
160 impl<T: ?Sized> fmt::Pointer 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> From<&mut T> for Unique<T> {
168     #[inline]
169     fn from(reference: &mut T) -> Self {
170         unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
171     }
172 }