typst_utils/
fat.rs

1//! Fat pointer handling.
2//!
3//! This assumes the memory representation of fat pointers. Although it is not
4//! guaranteed by Rust, it's improbable that it will change. Still, when the
5//! pointer metadata APIs are stable, we should definitely move to them:
6//! <https://github.com/rust-lang/rust/issues/81513>
7
8use std::alloc::Layout;
9use std::mem;
10use std::ptr::NonNull;
11
12/// Create a fat pointer from a data address and a vtable address.
13///
14/// # Safety
15/// Must only be called when `T` is a `dyn Trait`. The data address must point
16/// to a value whose type implements the trait of `T` and the `vtable` must have
17/// been extracted with [`vtable`].
18#[track_caller]
19pub unsafe fn from_raw_parts<T: ?Sized>(data: *const (), vtable: *const ()) -> *const T {
20    let fat = FatPointer { data, vtable };
21    debug_assert_eq!(Layout::new::<*const T>(), Layout::new::<FatPointer>());
22    mem::transmute_copy::<FatPointer, *const T>(&fat)
23}
24
25/// Create a mutable fat pointer from a data address and a vtable address.
26///
27/// # Safety
28/// Must only be called when `T` is a `dyn Trait`. The data address must point
29/// to a value whose type implements the trait of `T` and the `vtable` must have
30/// been extracted with [`vtable`].
31#[track_caller]
32pub unsafe fn from_raw_parts_mut<T: ?Sized>(data: *mut (), vtable: *const ()) -> *mut T {
33    let fat = FatPointer { data, vtable };
34    debug_assert_eq!(Layout::new::<*mut T>(), Layout::new::<FatPointer>());
35    mem::transmute_copy::<FatPointer, *mut T>(&fat)
36}
37
38/// Extract the address to a trait object's vtable.
39///
40/// # Safety
41/// Must only be called when `T` is a `dyn Trait`.
42#[track_caller]
43pub unsafe fn vtable<T: ?Sized>(ptr: *const T) -> NonNull<()> {
44    debug_assert_eq!(Layout::new::<*const T>(), Layout::new::<FatPointer>());
45    NonNull::new_unchecked(
46        mem::transmute_copy::<*const T, FatPointer>(&ptr).vtable as *mut (),
47    )
48}
49
50/// The memory representation of a trait object pointer.
51///
52/// Although this is not guaranteed by Rust, it's improbable that it will
53/// change.
54#[repr(C)]
55struct FatPointer {
56    data: *const (),
57    vtable: *const (),
58}