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 #[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 pub fn exec_async<F>(&self, queue: &DispatchQueue, work: F)
22 where
23 F: Send + FnOnce() + 'static,
26 {
27 let work_boxed = Box::into_raw(Box::new(work)).cast::<c_void>();
28
29 unsafe { Self::exec_async_f(self, queue, work_boxed, function_wrapper::<F>) };
31 }
32
33 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 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 unsafe {
56 Self::notify_f(self, queue, work_boxed, function_wrapper::<F>);
57 }
58 }
59
60 pub fn enter(&self) -> DispatchGroupGuard {
62 unsafe { dispatch_group_enter(self) };
64
65 DispatchGroupGuard(self.retain())
66 }
67}
68
69#[derive(Debug)]
71pub struct DispatchGroupGuard(DispatchRetained<DispatchGroup>);
72
73impl DispatchGroupGuard {
74 pub fn leave(self) {
76 let _ = self;
78 }
79}
80
81impl Drop for DispatchGroupGuard {
82 fn drop(&mut self) {
83 unsafe { DispatchGroup::leave(&self.0) };
85 }
86}