core/ptr/metadata.rs
1#![unstable(feature = "ptr_metadata", issue = "81513")]
2
3#[cfg(not(feature = "ferrocene_subset"))]
4use crate::clone::TrivialClone;
5#[cfg(not(feature = "ferrocene_subset"))]
6use crate::fmt;
7#[cfg(not(feature = "ferrocene_subset"))]
8use crate::hash::{Hash, Hasher};
9use crate::intrinsics::{aggregate_raw_ptr, ptr_metadata};
10use crate::marker::{Freeze, PointeeSized};
11use crate::ptr::NonNull;
12
13// Ferrocene addition: imports for certified subset
14#[cfg(feature = "ferrocene_subset")]
15#[rustfmt::skip]
16use crate::hash::Hash;
17
18/// Provides the pointer metadata type of any pointed-to type.
19///
20/// # Pointer metadata
21///
22/// Raw pointer types and reference types in Rust can be thought of as made of two parts:
23/// a data pointer that contains the memory address of the value, and some metadata.
24///
25/// For statically-sized types (that implement the `Sized` traits)
26/// as well as for `extern` types,
27/// pointers are said to be “thin”: metadata is zero-sized and its type is `()`.
28///
29/// Pointers to [dynamically-sized types][dst] are said to be “wide” or “fat”,
30/// they have non-zero-sized metadata:
31///
32/// * For structs whose last field is a DST, metadata is the metadata for the last field
33/// * For the `str` type, metadata is the length in bytes as `usize`
34/// * For slice types like `[T]`, metadata is the length in items as `usize`
35/// * For trait objects like `dyn SomeTrait`, metadata is [`DynMetadata<Self>`][DynMetadata]
36/// (e.g. `DynMetadata<dyn SomeTrait>`)
37///
38/// In the future, the Rust language may gain new kinds of types
39/// that have different pointer metadata.
40///
41/// [dst]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#dynamically-sized-types-dsts
42///
43///
44/// # The `Pointee` trait
45///
46/// The point of this trait is its `Metadata` associated type,
47/// which is `()` or `usize` or `DynMetadata<_>` as described above.
48/// It is automatically implemented for every type.
49/// It can be assumed to be implemented in a generic context, even without a corresponding bound.
50///
51///
52/// # Usage
53///
54/// Raw pointers can be decomposed into the data pointer and metadata components
55/// with their [`to_raw_parts`] method.
56///
57/// Alternatively, metadata alone can be extracted with the [`metadata`] function.
58/// A reference can be passed to [`metadata`] and implicitly coerced.
59///
60/// A (possibly-wide) pointer can be put back together from its data pointer and metadata
61/// with [`from_raw_parts`] or [`from_raw_parts_mut`].
62///
63/// [`to_raw_parts`]: *const::to_raw_parts
64#[lang = "pointee_trait"]
65#[rustc_deny_explicit_impl]
66#[rustc_do_not_implement_via_object]
67pub trait Pointee: PointeeSized {
68 /// The type for metadata in pointers and references to `Self`.
69 #[lang = "metadata_type"]
70 // NOTE: Keep trait bounds in `static_assert_expected_bounds_for_metadata`
71 // in `library/core/src/ptr/metadata.rs`
72 // in sync with those here:
73 // NOTE: The metadata of `dyn Trait + 'a` is `DynMetadata<dyn Trait + 'a>`
74 // so a `'static` bound must not be added.
75 #[cfg(not(feature = "ferrocene_subset"))]
76 type Metadata: fmt::Debug + Copy + Send + Sync + Ord + Hash + Unpin + Freeze;
77 /// The type for metadata in pointers and references to `Self`.
78 #[lang = "metadata_type"]
79 #[cfg(feature = "ferrocene_subset")]
80 #[rustfmt::skip]
81 type Metadata: /* fmt::Debug */ Copy + Send + Sync + Ord + Hash + Unpin + Freeze;
82}
83
84/// Pointers to types implementing this trait alias are “thin”.
85///
86/// This includes statically-`Sized` types and `extern` types.
87///
88/// # Example
89///
90/// ```rust
91/// #![feature(ptr_metadata)]
92///
93/// fn this_never_panics<T: std::ptr::Thin>() {
94/// assert_eq!(size_of::<&T>(), size_of::<usize>())
95/// }
96/// ```
97#[unstable(feature = "ptr_metadata", issue = "81513")]
98// NOTE: don’t stabilize this before trait aliases are stable in the language?
99pub trait Thin = Pointee<Metadata = ()> + PointeeSized;
100
101/// Extracts the metadata component of a pointer.
102///
103/// Values of type `*mut T`, `&T`, or `&mut T` can be passed directly to this function
104/// as they implicitly coerce to `*const T`.
105///
106/// # Example
107///
108/// ```
109/// #![feature(ptr_metadata)]
110///
111/// assert_eq!(std::ptr::metadata("foo"), 3_usize);
112/// ```
113#[inline]
114pub const fn metadata<T: PointeeSized>(ptr: *const T) -> <T as Pointee>::Metadata {
115 ptr_metadata(ptr)
116}
117
118/// Forms a (possibly-wide) raw pointer from a data pointer and metadata.
119///
120/// This function is safe but the returned pointer is not necessarily safe to dereference.
121/// For slices, see the documentation of [`slice::from_raw_parts`] for safety requirements.
122/// For trait objects, the metadata must come from a pointer to the same underlying erased type.
123///
124/// If you are attempting to deconstruct a DST in a generic context to be reconstructed later,
125/// a thin pointer can always be obtained by casting `*const T` to `*const ()`.
126///
127/// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
128#[unstable(feature = "ptr_metadata", issue = "81513")]
129#[inline]
130pub const fn from_raw_parts<T: PointeeSized>(
131 data_pointer: *const impl Thin,
132 metadata: <T as Pointee>::Metadata,
133) -> *const T {
134 aggregate_raw_ptr(data_pointer, metadata)
135}
136
137/// Performs the same functionality as [`from_raw_parts`], except that a
138/// raw `*mut` pointer is returned, as opposed to a raw `*const` pointer.
139///
140/// See the documentation of [`from_raw_parts`] for more details.
141#[unstable(feature = "ptr_metadata", issue = "81513")]
142#[inline]
143pub const fn from_raw_parts_mut<T: PointeeSized>(
144 data_pointer: *mut impl Thin,
145 metadata: <T as Pointee>::Metadata,
146) -> *mut T {
147 aggregate_raw_ptr(data_pointer, metadata)
148}
149
150/// The metadata for a `Dyn = dyn SomeTrait` trait object type.
151///
152/// It is a pointer to a vtable (virtual call table)
153/// that represents all the necessary information
154/// to manipulate the concrete type stored inside a trait object.
155/// The vtable notably contains:
156///
157/// * type size
158/// * type alignment
159/// * a pointer to the type’s `drop_in_place` impl (may be a no-op for plain-old-data)
160/// * pointers to all the methods for the type’s implementation of the trait
161///
162/// Note that the first three are special because they’re necessary to allocate, drop,
163/// and deallocate any trait object.
164///
165/// It is possible to name this struct with a type parameter that is not a `dyn` trait object
166/// (for example `DynMetadata<u64>`) but not to obtain a meaningful value of that struct.
167///
168/// Note that while this type implements `PartialEq`, comparing vtable pointers is unreliable:
169/// pointers to vtables of the same type for the same trait can compare inequal (because vtables are
170/// duplicated in multiple codegen units), and pointers to vtables of *different* types/traits can
171/// compare equal (since identical vtables can be deduplicated within a codegen unit).
172#[lang = "dyn_metadata"]
173pub struct DynMetadata<Dyn: PointeeSized> {
174 _vtable_ptr: NonNull<VTable>,
175 _phantom: crate::marker::PhantomData<Dyn>,
176}
177
178unsafe extern "C" {
179 /// Opaque type for accessing vtables.
180 ///
181 /// Private implementation detail of `DynMetadata::size_of` etc.
182 /// There is conceptually not actually any Abstract Machine memory behind this pointer.
183 type VTable;
184}
185
186#[cfg(not(feature = "ferrocene_subset"))]
187impl<Dyn: PointeeSized> DynMetadata<Dyn> {
188 /// When `DynMetadata` appears as the metadata field of a wide pointer, the rustc_middle layout
189 /// computation does magic and the resulting layout is *not* a `FieldsShape::Aggregate`, instead
190 /// it is a `FieldsShape::Primitive`. This means that the same type can have different layout
191 /// depending on whether it appears as the metadata field of a wide pointer or as a stand-alone
192 /// type, which understandably confuses codegen and leads to ICEs when trying to project to a
193 /// field of `DynMetadata`. To work around that issue, we use `transmute` instead of using a
194 /// field projection.
195 #[inline]
196 fn vtable_ptr(self) -> *const VTable {
197 // SAFETY: this layout assumption is hard-coded into the compiler.
198 // If it's somehow not a size match, the transmute will error.
199 unsafe { crate::mem::transmute::<Self, *const VTable>(self) }
200 }
201
202 /// Returns the size of the type associated with this vtable.
203 #[inline]
204 pub fn size_of(self) -> usize {
205 // Note that "size stored in vtable" is *not* the same as "result of size_of_val_raw".
206 // Consider a reference like `&(i32, dyn Send)`: the vtable will only store the size of the
207 // `Send` part!
208 // SAFETY: DynMetadata always contains a valid vtable pointer
209 unsafe { crate::intrinsics::vtable_size(self.vtable_ptr() as *const ()) }
210 }
211
212 /// Returns the alignment of the type associated with this vtable.
213 #[inline]
214 pub fn align_of(self) -> usize {
215 // SAFETY: DynMetadata always contains a valid vtable pointer
216 unsafe { crate::intrinsics::vtable_align(self.vtable_ptr() as *const ()) }
217 }
218
219 /// Returns the size and alignment together as a `Layout`
220 #[inline]
221 pub fn layout(self) -> crate::alloc::Layout {
222 // SAFETY: the compiler emitted this vtable for a concrete Rust type which
223 // is known to have a valid layout. Same rationale as in `Layout::for_value`.
224 unsafe { crate::alloc::Layout::from_size_align_unchecked(self.size_of(), self.align_of()) }
225 }
226}
227
228#[cfg(not(feature = "ferrocene_subset"))]
229unsafe impl<Dyn: PointeeSized> Send for DynMetadata<Dyn> {}
230#[cfg(not(feature = "ferrocene_subset"))]
231unsafe impl<Dyn: PointeeSized> Sync for DynMetadata<Dyn> {}
232
233#[cfg(not(feature = "ferrocene_subset"))]
234impl<Dyn: PointeeSized> fmt::Debug for DynMetadata<Dyn> {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 f.debug_tuple("DynMetadata").field(&self.vtable_ptr()).finish()
237 }
238}
239
240// Manual impls needed to avoid `Dyn: $Trait` bounds.
241
242#[cfg(not(feature = "ferrocene_subset"))]
243impl<Dyn: PointeeSized> Unpin for DynMetadata<Dyn> {}
244
245#[cfg(not(feature = "ferrocene_subset"))]
246impl<Dyn: PointeeSized> Copy for DynMetadata<Dyn> {}
247
248#[cfg(not(feature = "ferrocene_subset"))]
249impl<Dyn: PointeeSized> Clone for DynMetadata<Dyn> {
250 #[inline]
251 fn clone(&self) -> Self {
252 *self
253 }
254}
255
256#[cfg(not(feature = "ferrocene_subset"))]
257#[doc(hidden)]
258unsafe impl<Dyn: PointeeSized> TrivialClone for DynMetadata<Dyn> {}
259
260#[cfg(not(feature = "ferrocene_subset"))]
261impl<Dyn: PointeeSized> Eq for DynMetadata<Dyn> {}
262
263#[cfg(not(feature = "ferrocene_subset"))]
264impl<Dyn: PointeeSized> PartialEq for DynMetadata<Dyn> {
265 #[inline]
266 fn eq(&self, other: &Self) -> bool {
267 crate::ptr::eq::<VTable>(self.vtable_ptr(), other.vtable_ptr())
268 }
269}
270
271#[cfg(not(feature = "ferrocene_subset"))]
272impl<Dyn: PointeeSized> Ord for DynMetadata<Dyn> {
273 #[inline]
274 #[allow(ambiguous_wide_pointer_comparisons)]
275 fn cmp(&self, other: &Self) -> crate::cmp::Ordering {
276 <*const VTable>::cmp(&self.vtable_ptr(), &other.vtable_ptr())
277 }
278}
279
280#[cfg(not(feature = "ferrocene_subset"))]
281impl<Dyn: PointeeSized> PartialOrd for DynMetadata<Dyn> {
282 #[inline]
283 fn partial_cmp(&self, other: &Self) -> Option<crate::cmp::Ordering> {
284 Some(self.cmp(other))
285 }
286}
287
288#[cfg(not(feature = "ferrocene_subset"))]
289impl<Dyn: PointeeSized> Hash for DynMetadata<Dyn> {
290 #[inline]
291 fn hash<H: Hasher>(&self, hasher: &mut H) {
292 crate::ptr::hash::<VTable, _>(self.vtable_ptr(), hasher)
293 }
294}