Skip to main content

clack_common/events/io/
implementation.rs

1use crate::events::io::TryPushError;
2use crate::events::spaces::CoreEventSpace;
3use crate::events::{Event, UnknownEvent};
4use crate::utils::{handle_panic, usize_to_clap_size};
5use clap_sys::events::{clap_event_header, clap_input_events, clap_output_events};
6
7/// A trait for all types which can act as an ordered, indexed list of [`UnknownEvent`]s.
8///
9/// This is the backing implementation of an [`InputEvents`](crate::events::io::InputEvents), which
10/// is how input events are shared from the CLAP host to the plugin.
11///
12/// Note that events are indexed using `u32` instead of the standard `usize`, to match the CLAP
13/// specification.
14#[allow(clippy::len_without_is_empty)] // This is not necessary, the trait is intended for FFI
15pub trait InputEventBuffer: Sized {
16    /// Returns the number of events in this list.
17    fn len(&self) -> u32;
18    /// Returns the event at the given `index`.
19    ///
20    /// If `index` is out of bounds, then this must return `None` instead.
21    fn get(&self, index: u32) -> Option<&UnknownEvent>;
22}
23
24/// A trait for all types which can act as an ordered queue for outbound [`UnknownEvent`]s.
25///
26/// This is the backing implementation of an [`OutputEvents`](crate::events::io::OutputEvents), which
27/// is how output events are shared from the CLAP plugin to the host.
28///
29/// Note that events are indexed using `u32` instead of the standard `usize`, to match the CLAP
30/// specification.
31pub trait OutputEventBuffer: Sized {
32    /// Attempts to push a given event to the queue.
33    ///
34    /// # Errors
35    ///
36    /// This may return a [`TryPushError`] if the event couldn't be pushed for any reason (e.g. the
37    /// underlying implementation ran out of buffer space).
38    fn try_push(&mut self, event: &UnknownEvent) -> Result<(), TryPushError>;
39}
40
41pub(crate) const fn raw_input_events<I: InputEventBuffer>(buffer: &I) -> clap_input_events {
42    clap_input_events {
43        ctx: buffer as *const I as *mut I as *mut _,
44        size: Some(size::<I>),
45        get: Some(get::<I>),
46    }
47}
48
49pub(crate) const fn raw_output_events<I: OutputEventBuffer>(buffer: &mut I) -> clap_output_events {
50    clap_output_events {
51        ctx: buffer as *mut _ as *mut _,
52        try_push: Some(try_push::<I>),
53    }
54}
55
56pub(crate) const fn void_output_events() -> clap_output_events {
57    clap_output_events {
58        ctx: core::ptr::null_mut(),
59        try_push: Some(void_push),
60    }
61}
62
63/// # Safety
64///
65/// The caller must guarantee that:
66///
67/// * `input_events` is valid for reads and points to a valid clap_input_events instance;
68/// * The `ctx` pointer it contains points to a value of type `I` and is created from a shared reference (`&`) to it.
69#[inline]
70unsafe fn get_input_buffer<'a, I: InputEventBuffer>(
71    input_events: *const clap_input_events,
72) -> &'a I {
73    // SAFETY: The caller must guarantee the given input_events points to a valid clap_input_events instance and must be valid for reads
74    let ctx = unsafe { (*input_events).ctx };
75    let buf_impl: *mut I = ctx.cast();
76    // SAFETY: The caller must guarantee the ctx pointer is of type I and valid for 'a
77    unsafe { &*buf_impl }
78}
79
80#[allow(clippy::missing_safety_doc)]
81unsafe extern "C" fn size<I: InputEventBuffer>(list: *const clap_input_events) -> u32 {
82    handle_panic(|| {
83        // SAFETY: We only use this function in instances that we created ourselves from an instance of `I`.
84        let buf = unsafe { get_input_buffer(list) };
85        I::len(buf)
86    })
87    .unwrap_or(0)
88}
89
90#[allow(clippy::missing_safety_doc)]
91unsafe extern "C" fn get<I: InputEventBuffer>(
92    list: *const clap_input_events,
93    index: u32,
94) -> *const clap_event_header {
95    handle_panic(|| {
96        // SAFETY: We only use this function in instances that we created ourselves from an instance of `I`.
97        let buf = unsafe { get_input_buffer(list) };
98        I::get(buf, index)
99            .map(|e| e.as_raw() as *const _)
100            .unwrap_or_else(core::ptr::null)
101    })
102    .unwrap_or(core::ptr::null())
103}
104
105/// # Safety
106///
107/// The caller must guarantee that:
108///
109/// * `output_events` is valid for reads and points to a valid clap_input_events instance;
110/// * The `ctx` pointer it contains points to a value of type `I` and is created from an exclusive reference (`&mut`) to it.
111#[inline]
112unsafe fn get_output_buffer<'a, O: OutputEventBuffer>(
113    output_events: *const clap_output_events,
114) -> &'a mut O {
115    // SAFETY: The caller must guarantee the given output_events points to a valid clap_output_events instance and must be valid for reads
116    let ctx = unsafe { (*output_events).ctx };
117    let buf_impl: *mut O = ctx.cast();
118    // SAFETY: The caller must guarantee the ctx pointer is of type I and valid for 'a
119    unsafe { &mut *buf_impl }
120}
121
122#[allow(clippy::missing_safety_doc)]
123unsafe extern "C" fn try_push<O: OutputEventBuffer>(
124    list: *const clap_output_events,
125    event: *const clap_event_header,
126) -> bool {
127    handle_panic(|| {
128        // SAFETY: We only use this function in instances that we created ourselves from an instance of `O`.
129        let buf = unsafe { get_output_buffer(list) };
130        // SAFETY: event is guaranteed to be valid by the CLAP spec
131        let event = unsafe { UnknownEvent::from_raw(event) };
132
133        O::try_push(buf, event).is_ok()
134    })
135    .unwrap_or(false)
136}
137
138#[allow(clippy::missing_safety_doc)]
139unsafe extern "C" fn void_push(
140    _list: *const clap_output_events,
141    _event: *const clap_event_header,
142) -> bool {
143    true
144}
145
146impl<T: Event> InputEventBuffer for T {
147    #[inline]
148    fn len(&self) -> u32 {
149        1
150    }
151
152    #[inline]
153    fn get(&self, index: u32) -> Option<&UnknownEvent> {
154        match index {
155            0 => Some(self.as_unknown()),
156            _ => None,
157        }
158    }
159}
160
161impl<T: InputEventBuffer, U: InputEventBuffer> InputEventBuffer for (&T, &U) {
162    #[inline]
163    fn len(&self) -> u32 {
164        self.0.len() + self.1.len()
165    }
166
167    #[inline]
168    fn get(&self, index: u32) -> Option<&UnknownEvent> {
169        let first_len = self.0.len();
170        if index < first_len {
171            self.0.get(index)
172        } else {
173            // No underflow possible: we checked if index was >= first_len above
174            self.1.get(index - first_len)
175        }
176    }
177}
178
179impl<T: Event, const N: usize> InputEventBuffer for [T; N] {
180    #[inline]
181    fn len(&self) -> u32 {
182        const { usize_to_clap_size(N) }
183    }
184
185    #[inline]
186    fn get(&self, index: u32) -> Option<&UnknownEvent> {
187        self.as_slice().get(index as usize).map(|e| e.as_unknown())
188    }
189}
190
191impl<T: Event> InputEventBuffer for &[T] {
192    #[inline]
193    fn len(&self) -> u32 {
194        let len = <[T]>::len(self);
195        usize_to_clap_size(len)
196    }
197
198    #[inline]
199    fn get(&self, index: u32) -> Option<&UnknownEvent> {
200        <[T]>::get(self, index as usize).map(|e| e.as_unknown())
201    }
202}
203
204impl<T: Event> InputEventBuffer for Vec<T> {
205    #[inline]
206    fn len(&self) -> u32 {
207        let len = <[T]>::len(self);
208        usize_to_clap_size(len)
209    }
210
211    #[inline]
212    fn get(&self, index: u32) -> Option<&UnknownEvent> {
213        <[T]>::get(self, index as usize).map(|e| e.as_unknown())
214    }
215}
216
217impl InputEventBuffer for &UnknownEvent {
218    #[inline]
219    fn len(&self) -> u32 {
220        1
221    }
222
223    #[inline]
224    fn get(&self, index: u32) -> Option<&UnknownEvent> {
225        match index {
226            0 => Some(self),
227            _ => None,
228        }
229    }
230}
231
232impl<const N: usize> InputEventBuffer for [&UnknownEvent; N] {
233    #[inline]
234    fn len(&self) -> u32 {
235        const { usize_to_clap_size(N) }
236    }
237
238    #[inline]
239    fn get(&self, index: u32) -> Option<&UnknownEvent> {
240        self.as_slice().get(index as usize).copied()
241    }
242}
243
244impl InputEventBuffer for &[&UnknownEvent] {
245    #[inline]
246    fn len(&self) -> u32 {
247        let len = <[&UnknownEvent]>::len(self);
248        usize_to_clap_size(len)
249    }
250
251    #[inline]
252    fn get(&self, index: u32) -> Option<&UnknownEvent> {
253        <[&UnknownEvent]>::get(self, index as usize).copied()
254    }
255}
256
257impl InputEventBuffer for Vec<&UnknownEvent> {
258    #[inline]
259    fn len(&self) -> u32 {
260        let len = <[&UnknownEvent]>::len(self);
261        usize_to_clap_size(len)
262    }
263
264    #[inline]
265    fn get(&self, index: u32) -> Option<&UnknownEvent> {
266        <[&UnknownEvent]>::get(self, index as usize).copied()
267    }
268}
269
270impl<T: InputEventBuffer> InputEventBuffer for Option<T> {
271    #[inline]
272    fn len(&self) -> u32 {
273        match self {
274            Some(b) => b.len(),
275            None => 0,
276        }
277    }
278
279    #[inline]
280    fn get(&self, index: u32) -> Option<&UnknownEvent> {
281        match self {
282            None => None,
283            Some(b) => b.get(index),
284        }
285    }
286}
287
288impl<'a, T: Event<EventSpace<'a> = CoreEventSpace<'a>> + Clone> OutputEventBuffer for Option<T> {
289    fn try_push(&mut self, event: &UnknownEvent) -> Result<(), TryPushError> {
290        if self.is_some() {
291            return Err(TryPushError);
292        };
293
294        if let Some(event) = event.as_event::<T>() {
295            *self = Some(event.clone());
296            Ok(())
297        } else {
298            Err(TryPushError)
299        }
300    }
301}
302
303impl<'a, T: Event<EventSpace<'a> = CoreEventSpace<'a>> + Clone> OutputEventBuffer for Vec<T> {
304    fn try_push(&mut self, event: &UnknownEvent) -> Result<(), TryPushError> {
305        if let Some(event) = event.as_event::<T>() {
306            self.push(event.clone());
307            Ok(())
308        } else {
309            Err(TryPushError)
310        }
311    }
312}