core/ptr/
metadata.rs

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