Skip to main content

anvil/
table.rs

1use std::fmt;
2use std::marker::PhantomData;
3use std::mem::size_of;
4use std::ptr::NonNull;
5
6/// A C table that starts with `uint32_t size`: Anvil's host table or a
7/// service's. Its provider may be older than this crate, so its table may be
8/// shorter than `T`. `Table` keeps the pointer and the provider's `size` and
9/// never makes a `&T` that reaches past them: the crate reads a field only
10/// when `size` covers it (the `ANVIL_*_HAS` macros of the C headers), and
11/// [`get`](Table::get) hands out `&T` only for a table at least as long as `T`.
12pub struct Table<T: 'static> {
13    ptr: NonNull<T>,
14    size: u32,
15}
16
17// SAFETY: a table is immutable and lives for the process (Anvil's ADR 0001:
18// nothing is unloaded in API 2); only copies of its fields leave it, and its
19// functions may be called from any thread, as the headers say.
20unsafe impl<T> Send for Table<T> {}
21// SAFETY: as for Send.
22unsafe impl<T> Sync for Table<T> {}
23
24impl<T> Clone for Table<T> {
25    fn clone(&self) -> Self {
26        *self
27    }
28}
29
30impl<T> Copy for Table<T> {}
31
32impl<T> fmt::Debug for Table<T> {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.debug_struct("Table")
35            .field("ptr", &self.ptr)
36            .field("size", &self.size)
37            .finish()
38    }
39}
40
41impl<T> Table<T> {
42    /// The table behind `ptr`; `None` for null. Only its first four bytes,
43    /// the `size`, are read here.
44    ///
45    /// # Safety
46    /// `ptr` is null or points to a table of `T`'s layout (or an older,
47    /// shorter version of it) whose first field is `u32 size`, with at least
48    /// `size` bytes readable, unchanged and valid for the process; `T` is
49    /// plain data without interior mutability (a C table of `size`, values
50    /// and function pointers), so that sharing it between threads is sound.
51    pub unsafe fn from_raw(ptr: *const T) -> Option<Self> {
52        let ptr = NonNull::new(ptr.cast_mut())?;
53        // SAFETY: the caller's contract: the table starts with its size.
54        let size = unsafe { ptr.cast::<u32>().read() };
55        Some(Self { ptr, size })
56    }
57
58    /// The provider's `size`: how many bytes of `T` its table has.
59    pub fn size(&self) -> u32 {
60        self.size
61    }
62
63    /// The table's address.
64    pub fn as_ptr(&self) -> *const T {
65        self.ptr.as_ptr()
66    }
67
68    /// The whole table as `T`, when the provider's is at least as long as
69    /// `T`; `None` from an older provider, whose table is shorter.
70    pub fn get(&self) -> Option<&'static T> {
71        if (self.size as usize) < size_of::<T>() {
72            return None;
73        }
74        // SAFETY: `size` bytes are readable for the process (from_raw), and
75        // they cover all of T.
76        Some(unsafe { self.ptr.as_ref() })
77    }
78
79    /// The field of type `F` at `offset`, when the provider's `size` covers
80    /// it; `None` otherwise. No reference to the table is made.
81    ///
82    /// # Safety
83    /// `offset` and `F` are the offset and type of a field of `T`.
84    pub(crate) unsafe fn read_field<F: Copy>(&self, offset: usize, _: PhantomData<F>) -> Option<F> {
85        let end = offset.checked_add(size_of::<F>())?;
86        if (self.size as usize) < end || end > size_of::<T>() {
87            return None;
88        }
89        // SAFETY: inside the provider's `size` bytes, at a field of T of type F.
90        Some(unsafe {
91            self.ptr
92                .as_ptr()
93                .cast::<u8>()
94                .add(offset)
95                .cast::<F>()
96                .read()
97        })
98    }
99}
100
101/// The type of a field, from a closure that is never called: `field!` names
102/// it without making a reference to the table.
103pub(crate) fn field_type<T, F>(_: fn(&T) -> &F) -> PhantomData<F> {
104    PhantomData
105}