dispatch2/
group.rs

1use alloc::boxed::Box;
2use core::ffi::c_void;
3
4use crate::generated::{dispatch_group_enter, dispatch_group_wait};
5use crate::{DispatchObject, DispatchQueue, DispatchRetained, DispatchTime};
6
7use super::utils::function_wrapper;
8use super::WaitError;
9
10dispatch_object!(
11    /// Dispatch group.
12    #[doc(alias = "dispatch_group_t")]
13    #[doc(alias = "dispatch_group_s")]
14    pub struct DispatchGroup;
15);
16
17dispatch_object_not_data!(unsafe DispatchGroup);
18
19impl DispatchGroup {
20    /// Submit a function to a [`DispatchQueue`] and associates it with the [`DispatchGroup`].
21    pub fn exec_async<F>(&self, queue: &DispatchQueue, work: F)
22    where
23        // We need `'static` to make sure any referenced values are borrowed for
24        // long enough since `work` will be performed asynchronously.
25        F: Send + FnOnce() + 'static,
26    {
27        let work_boxed = Box::into_raw(Box::new(work)).cast::<c_void>();
28
29        // Safety: All parameters cannot be null.
30        unsafe { Self::exec_async_f(self, queue, work_boxed, function_wrapper::<F>) };
31    }
32
33    /// Wait synchronously for the previously submitted functions to finish.
34    ///
35    /// # Errors
36    ///
37    /// Return [WaitError::Timeout] in case of timeout.
38    pub fn wait(&self, timeout: DispatchTime) -> Result<(), WaitError> {
39        let result = dispatch_group_wait(self, timeout);
40
41        match result {
42            0 => Ok(()),
43            _ => Err(WaitError::Timeout),
44        }
45    }
46
47    /// Schedule a function to be submitted to a [`DispatchQueue`] when a group of previously submitted functions have completed.
48    pub fn notify<F>(&self, queue: &DispatchQueue, work: F)
49    where
50        F: Send + FnOnce(),
51    {
52        let work_boxed = Box::into_raw(Box::new(work)).cast::<c_void>();
53
54        // Safety: All parameters cannot be null.
55        unsafe {
56            Self::notify_f(self, queue, work_boxed, function_wrapper::<F>);
57        }
58    }
59
60    /// Explicitly indicates that the function has entered the [`DispatchGroup`].
61    pub fn enter(&self) -> DispatchGroupGuard {
62        // SAFETY: TODO: Is it a soundness requirement that this is paired with leave?
63        unsafe { dispatch_group_enter(self) };
64
65        DispatchGroupGuard(self.retain())
66    }
67}
68
69/// Dispatch group guard.
70#[derive(Debug)]
71pub struct DispatchGroupGuard(DispatchRetained<DispatchGroup>);
72
73impl DispatchGroupGuard {
74    /// Explicitly indicate that the function in the [`DispatchGroup`] finished executing.
75    pub fn leave(self) {
76        // Drop.
77        let _ = self;
78    }
79}
80
81impl Drop for DispatchGroupGuard {
82    fn drop(&mut self) {
83        // SAFETY: TODO: Is it a soundness requirement that this is paired with enter?
84        unsafe { DispatchGroup::leave(&self.0) };
85    }
86}