emf_core_base_rs/sys/
sync_handler.rs

1//! API of a sync handler.
2use crate::ffi::collections::NonNullConst;
3use crate::ffi::sys::sync_handler::{SyncHandlerBinding, SyncHandlerInterface};
4use crate::ffi::Bool;
5
6/// A borrowed sync handler.
7#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
8pub struct SyncHandler<'a> {
9    handler: &'a SyncHandlerInterface,
10}
11
12/// The API of a sync handler.
13pub trait SyncHandlerAPI<'a> {
14    /// Type of the sync handler.
15    type Handler;
16
17    /// Fetches a pointer that can be used with the interface.
18    fn to_interface(&self) -> NonNullConst<SyncHandlerInterface>;
19
20    /// Construct a new instance with the pointer.
21    ///
22    /// # Safety
23    ///
24    /// This function should not be used directly.
25    unsafe fn from_interface(handler: NonNullConst<SyncHandlerInterface>) -> Self::Handler;
26
27    /// Locks the synchronisation handler.
28    ///
29    /// The calling thread is stalled until the lock can be acquired.
30    /// Only one thread can hold the lock at a time.
31    ///
32    /// # Safety
33    ///
34    /// The function crosses the ffi boundary.
35    /// Direct usage of a [SyncHandlerAPI] may break some invariants
36    /// of the sys api, if not handled with care.
37    unsafe fn lock(&self);
38
39    /// Tries to lock the synchronisation handler.
40    ///
41    /// The function fails if another thread already holds the lock.
42    ///
43    /// # Return
44    ///
45    /// [true] on success and [false] otherwise.
46    ///
47    /// # Safety
48    ///
49    /// The function crosses the ffi boundary.
50    /// Direct usage of a [SyncHandlerAPI] may break some invariants
51    /// of the sys api, if not handled with care.
52    unsafe fn try_lock(&self) -> bool;
53
54    /// Unlocks the synchronisation handler.
55    ///
56    /// # Safety
57    ///
58    /// The function crosses the ffi boundary.
59    /// Trying to call this function without prior locking is undefined behaviour.
60    /// Direct usage of a [SyncHandlerAPI] may break some invariants
61    /// of the sys api, if not handled with care.
62    unsafe fn unlock(&self);
63}
64
65impl SyncHandlerAPI<'_> for SyncHandler<'_> {
66    type Handler = Self;
67
68    #[inline]
69    fn to_interface(&self) -> NonNullConst<SyncHandlerInterface> {
70        NonNullConst::from(self.handler)
71    }
72
73    #[inline]
74    unsafe fn from_interface(handler: NonNullConst<SyncHandlerInterface>) -> Self::Handler {
75        Self {
76            handler: &*handler.as_ptr(),
77        }
78    }
79
80    #[inline]
81    unsafe fn lock(&self) {
82        self.handler.lock()
83    }
84
85    #[inline]
86    unsafe fn try_lock(&self) -> bool {
87        self.handler.try_lock() == Bool::True
88    }
89
90    #[inline]
91    unsafe fn unlock(&self) {
92        self.handler.unlock()
93    }
94}