]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/metadata.rs
f4fb37bbdb7ce01de5a1db37424f4c20836901bb
[rust.git] / library / core / src / ptr / metadata.rs
1 #![unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
2
3 use crate::fmt;
4 use crate::hash::{Hash, Hasher};
5
6 /// Provides the pointer metadata type of any pointed-to type.
7 ///
8 /// # Pointer metadata
9 ///
10 /// Raw pointer types and reference types in Rust can be thought of as made of two parts:
11 /// a data pointer that contains the memory address of the value, and some metadata.
12 ///
13 /// For statically-sized types (that implement the `Sized` traits)
14 /// as well as for `extern` types,
15 /// pointers are said to be “thin”: metadata is zero-sized and its type is `()`.
16 ///
17 /// Pointers to [dynamically-sized types][dst] are said to be “wide” or “fat”,
18 /// they have non-zero-sized metadata:
19 ///
20 /// * For structs whose last field is a DST, metadata is the metadata for the last field
21 /// * For the `str` type, metadata is the length in bytes as `usize`
22 /// * For slice types like `[T]`, metadata is the length in items as `usize`
23 /// * For trait objects like `dyn SomeTrait`, metadata is [`DynMetadata<Self>`][DynMetadata]
24 ///   (e.g. `DynMetadata<dyn SomeTrait>`)
25 ///
26 /// In the future, the Rust language may gain new kinds of types
27 /// that have different pointer metadata.
28 ///
29 /// [dst]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#dynamically-sized-types-dsts
30 ///
31 ///
32 /// # The `Pointee` trait
33 ///
34 /// The point of this trait is its `Metadata` associated type,
35 /// which is `()` or `usize` or `DynMetadata<_>` as described above.
36 /// It is automatically implemented for every type.
37 /// It can be assumed to be implemented in a generic context, even without a corresponding bound.
38 ///
39 ///
40 /// # Usage
41 ///
42 /// Raw pointers can be decomposed into the data address and metadata components
43 /// with their [`to_raw_parts`] method.
44 ///
45 /// Alternatively, metadata alone can be extracted with the [`metadata`] function.
46 /// A reference can be passed to [`metadata`] and implicitly coerced.
47 ///
48 /// A (possibly-wide) pointer can be put back together from its address and metadata
49 /// with [`from_raw_parts`] or [`from_raw_parts_mut`].
50 ///
51 /// [`to_raw_parts`]: *const::to_raw_parts
52 #[lang = "pointee_trait"]
53 pub trait Pointee {
54     /// The type for metadata in pointers and references to `Self`.
55     #[lang = "metadata_type"]
56     // NOTE: Keep trait bounds in `static_assert_expected_bounds_for_metadata`
57     // in `library/core/src/ptr/metadata.rs`
58     // in sync with those here:
59     type Metadata: Copy + Send + Sync + Ord + Hash + Unpin;
60 }
61
62 /// Pointers to types implementing this trait alias are “thin”.
63 ///
64 /// This includes statically-`Sized` types and `extern` types.
65 ///
66 /// # Example
67 ///
68 /// ```rust
69 /// #![feature(ptr_metadata)]
70 ///
71 /// fn this_never_panics<T: std::ptr::Thin>() {
72 ///     assert_eq!(std::mem::size_of::<&T>(), std::mem::size_of::<usize>())
73 /// }
74 /// ```
75 #[unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
76 // NOTE: don’t stabilize this before trait aliases are stable in the language?
77 pub trait Thin = Pointee<Metadata = ()>;
78
79 /// Extract the metadata component of a pointer.
80 ///
81 /// Values of type `*mut T`, `&T`, or `&mut T` can be passed directly to this function
82 /// as they implicitly coerce to `*const T`.
83 ///
84 /// # Example
85 ///
86 /// ```
87 /// #![feature(ptr_metadata)]
88 ///
89 /// assert_eq!(std::ptr::metadata("foo"), 3_usize);
90 /// ```
91 #[rustc_const_unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
92 #[inline]
93 pub const fn metadata<T: ?Sized>(ptr: *const T) -> <T as Pointee>::Metadata {
94     // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T
95     // and PtrComponents<T> have the same memory layouts. Only std can make this
96     // guarantee.
97     unsafe { PtrRepr { const_ptr: ptr }.components.metadata }
98 }
99
100 /// Forms a (possibly-wide) raw pointer from a data address and metadata.
101 ///
102 /// This function is safe but the returned pointer is not necessarily safe to dereference.
103 /// For slices, see the documentation of [`slice::from_raw_parts`] for safety requirements.
104 /// For trait objects, the metadata must come from a pointer to the same underlying ereased type.
105 ///
106 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
107 #[unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
108 #[rustc_const_unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
109 #[inline]
110 pub const fn from_raw_parts<T: ?Sized>(
111     data_address: *const (),
112     metadata: <T as Pointee>::Metadata,
113 ) -> *const T {
114     // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T
115     // and PtrComponents<T> have the same memory layouts. Only std can make this
116     // guarantee.
117     unsafe { PtrRepr { components: PtrComponents { data_address, metadata } }.const_ptr }
118 }
119
120 /// Performs the same functionality as [`from_raw_parts`], except that a
121 /// raw `*mut` pointer is returned, as opposed to a raw `*const` pointer.
122 ///
123 /// See the documentation of [`from_raw_parts`] for more details.
124 #[unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
125 #[rustc_const_unstable(feature = "ptr_metadata", issue = /* FIXME */ "none")]
126 #[inline]
127 pub const fn from_raw_parts_mut<T: ?Sized>(
128     data_address: *mut (),
129     metadata: <T as Pointee>::Metadata,
130 ) -> *mut T {
131     // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T
132     // and PtrComponents<T> have the same memory layouts. Only std can make this
133     // guarantee.
134     unsafe { PtrRepr { components: PtrComponents { data_address, metadata } }.mut_ptr }
135 }
136
137 #[repr(C)]
138 pub(crate) union PtrRepr<T: ?Sized> {
139     pub(crate) const_ptr: *const T,
140     pub(crate) mut_ptr: *mut T,
141     pub(crate) components: PtrComponents<T>,
142 }
143
144 #[repr(C)]
145 pub(crate) struct PtrComponents<T: ?Sized> {
146     pub(crate) data_address: *const (),
147     pub(crate) metadata: <T as Pointee>::Metadata,
148 }
149
150 // Manual impl needed to avoid `T: Copy` bound.
151 impl<T: ?Sized> Copy for PtrComponents<T> {}
152
153 // Manual impl needed to avoid `T: Clone` bound.
154 impl<T: ?Sized> Clone for PtrComponents<T> {
155     fn clone(&self) -> Self {
156         *self
157     }
158 }
159
160 /// The metadata for a `Dyn = dyn SomeTrait` trait object type.
161 ///
162 /// It is a pointer to a vtable (virtual call table)
163 /// that represents all the necessary information
164 /// to manipulate the concrete type stored inside a trait object.
165 /// The vtable notably it contains:
166 ///
167 /// * type size
168 /// * type alignment
169 /// * a pointer to the type’s `drop_in_place` impl (may be a no-op for plain-old-data)
170 /// * pointers to all the methods for the type’s implementation of the trait
171 ///
172 /// Note that the first three are special because they’re necessary to allocate, drop,
173 /// and deallocate any trait object.
174 ///
175 /// It is possible to name this struct with a type parameter that is not a `dyn` trait object
176 /// (for example `DynMetadata<u64>`) but not to obtain a meaningful value of that struct.
177 #[lang = "dyn_metadata"]
178 pub struct DynMetadata<Dyn: ?Sized> {
179     vtable_ptr: &'static VTable,
180     phantom: crate::marker::PhantomData<Dyn>,
181 }
182
183 /// The common prefix of all vtables. It is followed by function pointers for trait methods.
184 ///
185 /// Private implementation detail of `DynMetadata::size_of` etc.
186 #[repr(C)]
187 struct VTable {
188     drop_in_place: fn(*mut ()),
189     size_of: usize,
190     align_of: usize,
191 }
192
193 impl<Dyn: ?Sized> DynMetadata<Dyn> {
194     /// Returns the size of the type associated with this vtable.
195     #[inline]
196     pub fn size_of(self) -> usize {
197         self.vtable_ptr.size_of
198     }
199
200     /// Returns the alignment of the type associated with this vtable.
201     #[inline]
202     pub fn align_of(self) -> usize {
203         self.vtable_ptr.align_of
204     }
205
206     /// Returns the size and alignment together as a `Layout`
207     #[inline]
208     pub fn layout(self) -> crate::alloc::Layout {
209         // SAFETY: the compiler emitted this vtable for a concrete Rust type which
210         // is known to have a valid layout. Same rationale as in `Layout::for_value`.
211         unsafe { crate::alloc::Layout::from_size_align_unchecked(self.size_of(), self.align_of()) }
212     }
213 }
214
215 unsafe impl<Dyn: ?Sized> Send for DynMetadata<Dyn> {}
216 unsafe impl<Dyn: ?Sized> Sync for DynMetadata<Dyn> {}
217
218 impl<Dyn: ?Sized> fmt::Debug for DynMetadata<Dyn> {
219     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220         f.debug_tuple("DynMetadata").field(&(self.vtable_ptr as *const VTable)).finish()
221     }
222 }
223
224 // Manual impls needed to avoid `Dyn: $Trait` bounds.
225
226 impl<Dyn: ?Sized> Unpin for DynMetadata<Dyn> {}
227
228 impl<Dyn: ?Sized> Copy for DynMetadata<Dyn> {}
229
230 impl<Dyn: ?Sized> Clone for DynMetadata<Dyn> {
231     #[inline]
232     fn clone(&self) -> Self {
233         *self
234     }
235 }
236
237 impl<Dyn: ?Sized> Eq for DynMetadata<Dyn> {}
238
239 impl<Dyn: ?Sized> PartialEq for DynMetadata<Dyn> {
240     #[inline]
241     fn eq(&self, other: &Self) -> bool {
242         crate::ptr::eq::<VTable>(self.vtable_ptr, other.vtable_ptr)
243     }
244 }
245
246 impl<Dyn: ?Sized> Ord for DynMetadata<Dyn> {
247     #[inline]
248     fn cmp(&self, other: &Self) -> crate::cmp::Ordering {
249         (self.vtable_ptr as *const VTable).cmp(&(other.vtable_ptr as *const VTable))
250     }
251 }
252
253 impl<Dyn: ?Sized> PartialOrd for DynMetadata<Dyn> {
254     #[inline]
255     fn partial_cmp(&self, other: &Self) -> Option<crate::cmp::Ordering> {
256         Some(self.cmp(other))
257     }
258 }
259
260 impl<Dyn: ?Sized> Hash for DynMetadata<Dyn> {
261     #[inline]
262     fn hash<H: Hasher>(&self, hasher: &mut H) {
263         crate::ptr::hash::<VTable, _>(self.vtable_ptr, hasher)
264     }
265 }