Skip to main content

anvil/
event.rs

1use std::ffi::{c_void, CStr};
2use std::fmt;
3use std::marker::PhantomData;
4use std::mem::{size_of, MaybeUninit};
5
6/// An event name with the type of its payload. [`Host::subscribe`] hands
7/// the handler a `&P`; [`Host::subscribe_raw`] takes any name.
8///
9/// [`Host::subscribe`]: crate::Host::subscribe
10/// [`Host::subscribe_raw`]: crate::Host::subscribe_raw
11pub struct Event<P: Payload> {
12    name: &'static CStr,
13    _payload: PhantomData<fn() -> P>,
14}
15
16impl<P: Payload> Event<P> {
17    /// The event `name`, whose publisher passes payloads that `P` reads.
18    ///
19    /// # Safety
20    /// Every payload published under `name` is one [`Payload::read`] of `P`
21    /// accepts.
22    pub const unsafe fn new(name: &'static CStr) -> Self {
23        Self {
24            name,
25            _payload: PhantomData,
26        }
27    }
28
29    /// The name, e.g. `anvil-game.session`.
30    pub const fn name(&self) -> &'static CStr {
31        self.name
32    }
33}
34
35impl<P: Payload> Clone for Event<P> {
36    fn clone(&self) -> Self {
37        *self
38    }
39}
40
41impl<P: Payload> Copy for Event<P> {}
42
43impl<P: Payload> fmt::Debug for Event<P> {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.debug_tuple("Event").field(&self.name).finish()
46    }
47}
48
49/// The payload of an event, read from the publisher's pointer during the
50/// handler.
51///
52/// # Safety
53/// `read` must accept exactly the payloads its events publish, and null (an
54/// event published without a payload, as [`Host::publish`] does), for which
55/// it reads nothing.
56///
57/// [`Host::publish`]: crate::Host::publish
58pub unsafe trait Payload: Sized + 'static {
59    /// The payload behind `raw`; `None` when it cannot be read (e.g. null).
60    ///
61    /// # Safety
62    /// `raw` is the payload of an event this type belongs to, valid during the call.
63    unsafe fn read(raw: *const c_void) -> Option<Self>;
64}
65
66// SAFETY: the payload is not read.
67unsafe impl Payload for () {
68    unsafe fn read(_raw: *const c_void) -> Option<Self> {
69        Some(())
70    }
71}
72
73/// A struct that starts with `uint32_t size` (the size its publisher knows):
74/// only that many bytes are read, the rest stays zero, so a payload of an
75/// older publisher is never read past its end.
76///
77/// # Safety
78/// `raw` is null or such a struct, valid during the call; `T` is plain data
79/// for which all zero bytes are a valid value.
80pub(crate) unsafe fn read_sized<T: Copy>(raw: *const c_void) -> Option<T> {
81    if raw.is_null() {
82        return None;
83    }
84    // SAFETY: the struct starts with its size, a u32.
85    let size = unsafe { raw.cast::<u32>().read_unaligned() } as usize;
86    let mut value = MaybeUninit::<T>::zeroed();
87    // SAFETY: at most `size` bytes of the publisher's struct, into a zeroed T.
88    unsafe {
89        std::ptr::copy_nonoverlapping(
90            raw.cast::<u8>(),
91            value.as_mut_ptr().cast::<u8>(),
92            size.min(size_of::<T>()),
93        );
94        Some(value.assume_init())
95    }
96}
97
98/// `anvil.plugins_loaded`: every plugin is processed. Payload none.
99// SAFETY: Anvil publishes it with a NULL payload.
100pub const PLUGINS_LOADED: Event<()> = unsafe { Event::new(c"anvil.plugins_loaded") };
101/// `anvil.suspended`: to the plugin itself, its changes are out of the game
102/// (ironman, multiplayer). Payload none.
103// SAFETY: as above.
104pub const SUSPENDED: Event<()> = unsafe { Event::new(c"anvil.suspended") };
105/// `anvil.resumed`: to the plugin itself, its changes are back in the game.
106/// Payload none.
107// SAFETY: as above.
108pub const RESUMED: Event<()> = unsafe { Event::new(c"anvil.resumed") };