1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! A radioactive stabilization of the [`ptr_meta` RFC][rfc].
//!
//! [rfc]: https://rust-lang.github.io/rfcs/2580-ptr-meta.html
//!
//! ## Usage
//!
//! ### Sized types
//!
//! Sized types already have `Pointee` implemented for them, so most of the time you won't have to worry
//! about them. However, trying to derive `Pointee` for a struct that may or may not have a DST as its
//! last field will cause an implementation conflict with the automatic sized implementation.
//!
//! ### `slice`s and `str`s
//!
//! These core types have implementations built in.
//!
//! ### Structs with a DST as its last field
//!
//! You can derive `Pointee` for last-field DSTs:
//!
//! ```
//! use ptr_meta::Pointee;
//!
//! #[derive(Pointee)]
//! struct Block<H, T> {
//!     header: H,
//!     elements: [T],
//! }
//! ```
//!
//! ### Trait objects
//!
//! You can generate a `Pointee` for trait objects:
//!
//! ```
//! use ptr_meta::pointee;
//!
//! // Generates Pointee for dyn Stringy
//! #[pointee]
//! trait Stringy {
//!     fn as_string(&self) -> String;
//! }
//! ```

#![cfg_attr(not(feature = "std"), no_std)]

mod impls;

use core::{
    alloc::Layout,
    cmp,
    fmt,
    hash,
    marker::PhantomData,
    ptr,
};

pub use ptr_meta_derive::{pointee, Pointee};

/// Provides the pointer metadata type of any pointed-to type.
///
/// # Pointer metadata
///
/// Raw pointer types and reference types in Rust can be thought of as made of two parts:
/// a data pointer that contains the memory address of the value, and some metadata.
///
/// For statically-sized types (that implement the `Sized` traits)
/// as well as for `extern` types,
/// pointers are said to be “thin”: metadata is zero-sized and its type is `()`.
///
/// Pointers to [dynamically-sized types][dst] are said to be “wide” or “fat”,
/// they have non-zero-sized metadata:
///
/// * For structs whose last field is a DST, metadata is the metadata for the last field
/// * For the `str` type, metadata is the length in bytes as `usize`
/// * For slice types like `[T]`, metadata is the length in items as `usize`
/// * For trait objects like `dyn SomeTrait`, metadata is [`DynMetadata<Self>`][DynMetadata]
///   (e.g. `DynMetadata<dyn SomeTrait>`)
///
/// In the future, the Rust language may gain new kinds of types
/// that have different pointer metadata.
///
/// [dst]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#dynamically-sized-types-dsts
///
///
/// # The `Pointee` trait
///
/// The point of this trait is its `Metadata` associated type,
/// which is `()` or `usize` or `DynMetadata<_>` as described above.
/// It is automatically implemented for every type.
/// It can be assumed to be implemented in a generic context, even without a corresponding bound.
///
///
/// # Usage
///
/// Raw pointers can be decomposed into the data address and metadata components
/// with their [`to_raw_parts`] method.
///
/// Alternatively, metadata alone can be extracted with the [`metadata`] function.
/// A reference can be passed to [`metadata`] and implicitly coerced.
///
/// A (possibly-wide) pointer can be put back together from its address and metadata
/// with [`from_raw_parts`] or [`from_raw_parts_mut`].
///
/// [`to_raw_parts`]: PtrExt::to_raw_parts
pub trait Pointee {
    /// The type for metadata in pointers and references to `Self`.
    type Metadata: Copy + Send + Sync + Ord + hash::Hash + Unpin;
}

impl<T> Pointee for T {
    type Metadata = ();
}

impl<T> Pointee for [T] {
    type Metadata = usize;
}

impl Pointee for str {
    type Metadata = usize;
}

#[cfg(feature = "std")]
impl Pointee for ::std::ffi::CStr {
    type Metadata = usize;
}

#[cfg(feature = "std")]
impl Pointee for ::std::ffi::OsStr {
    type Metadata = usize;
}

#[repr(C)]
pub(crate) union PtrRepr<T: Pointee + ?Sized> {
    pub(crate) const_ptr: *const T,
    pub(crate) mut_ptr: *mut T,
    pub(crate) components: PtrComponents<T>,
}

#[repr(C)]
pub(crate) struct PtrComponents<T: Pointee + ?Sized> {
    pub(crate) data_address: *const (),
    pub(crate) metadata: <T as Pointee>::Metadata,
}

impl<T: Pointee + ?Sized> Clone for PtrComponents<T> {
    fn clone(&self) -> Self {
        Self {
            data_address: self.data_address.clone(),
            metadata: self.metadata.clone(),
        }
    }
}

impl<T: Pointee + ?Sized> Copy for PtrComponents<T> {}

/// Extract the metadata component of a pointer.
///
/// Values of type `*mut T`, `&T`, or `&mut T` can be passed directly to this function
/// as they implicitly coerce to `*const T`.
///
/// # Example
///
/// ```
/// use ptr_meta::metadata;
///
/// assert_eq!(metadata("foo"), 3_usize);
/// ```
pub fn metadata<T: Pointee + ?Sized>(ptr: *const T) -> <T as Pointee>::Metadata {
    unsafe { PtrRepr { const_ptr: ptr }.components.metadata }
}

/// Forms a (possibly-wide) raw pointer from a data address and metadata.
///
/// This function is safe but the returned pointer is not necessarily safe to dereference.
/// For slices, see the documentation of [`slice::from_raw_parts`] for safety requirements.
/// For trait objects, the metadata must come from a pointer to the same underlying ereased type.
///
/// [`slice::from_raw_parts`]: core::slice::from_raw_parts
pub fn from_raw_parts<T: Pointee + ?Sized>(data_address: *const (), metadata: <T as Pointee>::Metadata) -> *const T {
    unsafe { PtrRepr { components: PtrComponents { data_address, metadata } }.const_ptr }
}

/// Performs the same functionality as [`from_raw_parts`], except that a
/// raw `*mut` pointer is returned, as opposed to a raw `*const` pointer.
///
/// See the documentation of [`from_raw_parts`] for more details.
pub fn from_raw_parts_mut<T: Pointee + ?Sized>(data_address: *mut (), metadata: <T as Pointee>::Metadata) -> *mut T {
    unsafe { PtrRepr { components: PtrComponents { data_address, metadata } }.mut_ptr }
}

/// Extension methods for [`NonNull`](core::ptr::NonNull).
pub trait NonNullExt<T: Pointee + ?Sized> {
    /// The type's raw pointer (`NonNull<()>`).
    type Raw;

    /// Creates a new non-null pointer from its raw parts.
    fn from_raw_parts(raw: Self::Raw, meta: <T as Pointee>::Metadata) -> Self;
    /// Converts a non-null pointer to its raw parts.
    fn to_raw_parts(self) -> (Self::Raw, <T as Pointee>::Metadata);
}

impl<T: Pointee + ?Sized> NonNullExt<T> for ptr::NonNull<T> {
    type Raw = ptr::NonNull<()>;

    fn from_raw_parts(raw: Self::Raw, meta: <T as Pointee>::Metadata) -> Self {
        unsafe { Self::new_unchecked(from_raw_parts_mut(raw.as_ptr(), meta)) }
    }

    fn to_raw_parts(self) -> (Self::Raw, <T as Pointee>::Metadata) {
        let (raw, meta) = PtrExt::to_raw_parts(self.as_ptr());
        unsafe { (ptr::NonNull::new_unchecked(raw), meta) }
    }
}

/// Extension methods for pointers.
pub trait PtrExt<T: Pointee + ?Sized> {
    /// The type's raw pointer (`*const ()` or `*mut ()`).
    type Raw;

    /// Decompose a (possibly wide) pointer into its address and metadata
    /// components.
    ///
    /// The pointer can be later reconstructed with [`from_raw_parts`].
    fn to_raw_parts(self) -> (Self::Raw, <T as Pointee>::Metadata);
}

impl<T: Pointee + ?Sized> PtrExt<T> for *const T {
    type Raw = *const ();

    fn to_raw_parts(self) -> (Self::Raw, <T as Pointee>::Metadata) {
        unsafe { (&self as *const Self).cast::<(Self::Raw, <T as Pointee>::Metadata)>().read() }
    }
}

impl<T: Pointee + ?Sized> PtrExt<T> for *mut T {
    type Raw = *mut ();

    fn to_raw_parts(self) -> (Self::Raw, <T as Pointee>::Metadata) {
        unsafe { (&self as *const Self).cast::<(Self::Raw, <T as Pointee>::Metadata)>().read() }
    }
}

/// The metadata for a `Dyn = dyn SomeTrait` trait object type.
///
/// It is a pointer to a vtable (virtual call table)
/// that represents all the necessary information
/// to manipulate the concrete type stored inside a trait object.
/// The vtable notably it contains:
///
/// * type size
/// * type alignment
/// * a pointer to the type’s `drop_in_place` impl (may be a no-op for plain-old-data)
/// * pointers to all the methods for the type’s implementation of the trait
///
/// Note that the first three are special because they’re necessary to allocate, drop,
/// and deallocate any trait object.
///
/// It is possible to name this struct with a type parameter that is not a `dyn` trait object
/// (for example `DynMetadata<u64>`) but not to obtain a meaningful value of that struct.
#[repr(transparent)]
pub struct DynMetadata<Dyn: ?Sized> {
    vtable_ptr: &'static VTable,
    phantom: PhantomData<Dyn>,
}

#[repr(C)]
struct VTable {
    drop_in_place: fn(*mut ()),
    size_of: usize,
    align_of: usize,
}

impl<Dyn: ?Sized> DynMetadata<Dyn> {
    /// Returns the size of the type associated with this vtable.
    pub fn size_of(self) -> usize {
        self.vtable_ptr.size_of
    }

    /// Returns the alignment of the type associated with this vtable.
    pub fn align_of(self) -> usize {
        self.vtable_ptr.align_of
    }

    /// Returns the size and alignment together as a `Layout`.
    pub fn layout(self) -> Layout {
        unsafe { Layout::from_size_align_unchecked(self.size_of(), self.align_of()) }
    }
}

unsafe impl<Dyn: ?Sized> Send for DynMetadata<Dyn> {}
unsafe impl<Dyn: ?Sized> Sync for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> fmt::Debug for DynMetadata<Dyn> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("DynMetadata").field(&(self.vtable_ptr as *const VTable)).finish()
    }
}
impl<Dyn: ?Sized> Unpin for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Copy for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Clone for DynMetadata<Dyn> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}
impl<Dyn: ?Sized> cmp::Eq for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> cmp::PartialEq for DynMetadata<Dyn> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ptr::eq(self.vtable_ptr, other.vtable_ptr)
    }
}
impl<Dyn: ?Sized> cmp::Ord for DynMetadata<Dyn> {
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        (self.vtable_ptr as *const VTable).cmp(&(other.vtable_ptr as *const VTable))
    }
}
impl<Dyn: ?Sized> cmp::PartialOrd for DynMetadata<Dyn> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl<Dyn: ?Sized> hash::Hash for DynMetadata<Dyn> {
    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
        ptr::hash(self.vtable_ptr, hasher)
    }
}

#[cfg(test)]
mod tests {
    use crate as ptr_meta;
    use super::{from_raw_parts, pointee, Pointee, PtrExt};

    fn test_pointee<T: Pointee + ?Sized>(value: &T) {
        let ptr = value as *const T;
        let (raw, meta) = PtrExt::to_raw_parts(ptr);
        let re_ptr = from_raw_parts::<T>(raw, meta);
        assert_eq!(ptr, re_ptr);
    }

    #[test]
    fn sized_types() {
        test_pointee(&());
        test_pointee(&42);
        test_pointee(&true);
        test_pointee(&[1, 2, 3, 4]);

        struct TestUnit;

        test_pointee(&TestUnit);

        #[allow(dead_code)]
        struct TestStruct {
            a: (),
            b: i32,
            c: bool,
        }

        test_pointee(&TestStruct { a: (), b: 42, c: true });

        struct TestTuple((), i32, bool);

        test_pointee(&TestTuple((), 42, true));

        struct TestGeneric<T>(T);

        test_pointee(&TestGeneric(42));
    }

    #[test]
    fn unsized_types() {
        test_pointee("hello world");
        test_pointee(&[1, 2, 3, 4] as &[i32]);
    }

    #[test]
    fn trait_objects() {
        #[pointee]
        trait TestTrait {
            fn foo(&self);
        }

        struct A;

        impl TestTrait for A {
            fn foo(&self) {}
        }

        let trait_object = &A as &dyn TestTrait;

        test_pointee(trait_object);

        let (_, meta) = PtrExt::to_raw_parts(trait_object as *const dyn TestTrait);

        assert_eq!(meta.size_of(), 0);
        assert_eq!(meta.align_of(), 1);

        struct B(i32);

        impl TestTrait for B {
            fn foo(&self) {}
        }

        let b = B(42);
        let trait_object = &b as &dyn TestTrait;

        test_pointee(trait_object);

        let (_, meta) = PtrExt::to_raw_parts(trait_object as *const dyn TestTrait);

        assert_eq!(meta.size_of(), 4);
        assert_eq!(meta.align_of(), 4);
    }

    #[test]
    fn last_field_dst() {
        #[allow(dead_code)]
        #[derive(Pointee)]
        struct Test<H, T> {
            head: H,
            tail: [T],
        }

        #[allow(dead_code)]
        #[derive(Pointee)]
        struct TestDyn {
            tail: dyn core::any::Any,
        }

        #[pointee]
        trait TestTrait {}

        #[allow(dead_code)]
        #[derive(Pointee)]
        struct TestCustomDyn {
            tail: dyn TestTrait,
        }
    }
}