core/ptr/
metadata.rs

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