Debian Codegraph @

third_party/rust/coreaudio-sys-utils/src/dispatch.rs

raw
1 use coreaudio_sys::*;
2
3 use std::ffi::CString;
4 use std::mem;
5 use std::os::raw::c_void;
6 use std::panic;
7 use std::ptr;
8 use std::sync::atomic::{AtomicBool, Ordering};
9 use std::sync::{Mutex, OnceLock};
10 #[cfg(test)]
11 use std::thread;
12 #[cfg(test)]
13 use std::time::Duration;
14 use std::time::Instant;
15
16 pub const DISPATCH_QUEUE_LABEL: &str = "org.mozilla.cubeb";
17
18 pub fn get_serial_queue_singleton() -> &'static Queue {
19 static SERIAL_QUEUE: OnceLock<Queue> = OnceLock::new();
20 SERIAL_QUEUE.get_or_init(|| Queue::new(DISPATCH_QUEUE_LABEL))
21 }
22
23 pub fn debug_assert_running_serially() {
24 get_serial_queue_singleton().debug_assert_is_current();
25 }
26
27 pub fn debug_assert_not_running_serially() {
28 get_serial_queue_singleton().debug_assert_is_not_current();
29 }
30
31 pub fn run_serially<F, B>(work: F) -> B
32 where
33 F: FnOnce() -> B,
34 {
35 get_serial_queue_singleton().run_sync(|| work()).unwrap()
36 }
37
38 pub fn run_serially_forward_panics<F, B>(work: F) -> B
39 where
40 F: panic::UnwindSafe + FnOnce() -> B,
41 {
42 match run_serially(|| panic::catch_unwind(|| work())) {
43 Ok(res) => res,
44 Err(e) => panic::resume_unwind(e),
45 }
46 }
47
48 // Queue: A wrapper around `dispatch_queue_t` that is always serial.
49 // ------------------------------------------------------------------------------------------------
50 #[derive(Debug)]
51 pub struct Queue {
52 queue: Mutex<dispatch_queue_t>,
53 owned: AtomicBool,
54 }
55
56 impl Queue {
57 pub fn new_with_target(label: &str, target: &Queue) -> Self {
58 const DISPATCH_QUEUE_SERIAL: dispatch_queue_attr_t =
59 ptr::null_mut::<dispatch_queue_attr_s>();
60 let label = CString::new(label).unwrap();
61 let c_string = label.as_ptr();
62 let queue = {
63 let target_guard = target.queue.lock().unwrap();
64 Self {
65 queue: Mutex::new(unsafe {
66 dispatch_queue_create_with_target(
67 c_string,
68 DISPATCH_QUEUE_SERIAL,
69 *target_guard,
70 )
71 }),
72 owned: AtomicBool::new(true),
73 }
74 };
75 queue.set_should_cancel(Box::new(AtomicBool::new(false)));
76 queue
77 }
78
79 pub fn new(label: &str) -> Self {
80 Queue::new_with_target(label, &Queue::get_global_queue())
81 }
82
83 pub fn get_global_queue() -> Self {
84 Self {
85 queue: Mutex::new(unsafe { dispatch_get_global_queue(QOS_CLASS_DEFAULT as isize, 0) }),
86 owned: AtomicBool::new(false),
87 }
88 }
89
90 #[cfg(debug_assertions)]
91 pub fn debug_assert_is_current(&self) {
92 let guard = self.queue.lock().unwrap();
93 unsafe {
94 dispatch_assert_queue(*guard);
95 }
96 }
97
98 #[cfg(not(debug_assertions))]
99 pub fn debug_assert_is_current(&self) {}
100
101 #[cfg(debug_assertions)]
102 pub fn debug_assert_is_not_current(&self) {
103 let guard = self.queue.lock().unwrap();
104 unsafe {
105 dispatch_assert_queue_not(*guard);
106 }
107 }
108
109 #[cfg(not(debug_assertions))]
110 pub fn debug_assert_is_not_current(&self) {}
111
112 pub fn run_async<F>(&self, work: F)
113 where
114 F: Send + FnOnce(),
115 {
116 let guard = self.queue.lock().unwrap();
117 let should_cancel = self.get_should_cancel(*guard);
118 let (closure, executor) = Self::create_closure_and_executor(|| {
119 if should_cancel.map_or(false, |v| v.load(Ordering::SeqCst)) {
120 return;
121 }
122 work();
123 });
124 unsafe {
125 dispatch_async_f(*guard, closure, executor);
126 }
127 }
128
129 pub fn run_after<F>(&self, when: Instant, work: F)
130 where
131 F: Send + FnOnce(),
132 {
133 let now = Instant::now();
134 if when <= now {
135 return self.run_async(work);
136 }
137 let nanos = (when - now).as_nanos() as i64;
138 let when = unsafe { dispatch_time(DISPATCH_TIME_NOW.into(), nanos) };
139 let guard = self.queue.lock().unwrap();
140 let should_cancel = self.get_should_cancel(*guard);
141 let (closure, executor) = Self::create_closure_and_executor(|| {
142 if should_cancel.map_or(false, |v| v.load(Ordering::SeqCst)) {
143 return;
144 }
145 work();
146 });
147 unsafe {
148 dispatch_after_f(when, *guard, closure, executor);
149 }
150 }
151
152 pub fn run_sync<F, B>(&self, work: F) -> Option<B>
153 where
154 F: FnOnce() -> B,
155 {
156 let queue: Option<dispatch_queue_t>;
157 let mut res: Option<B> = None;
158 let cex: Option<(*mut c_void, dispatch_function_t)>;
159 {
160 let guard = self.queue.lock().unwrap();
161 queue = Some(*guard);
162 let should_cancel = self.get_should_cancel(*guard);
163 cex = Some(Self::create_closure_and_executor(|| {
164 if should_cancel.map_or(false, |v| v.load(Ordering::SeqCst)) {
165 return;
166 }
167 res = Some(work());
168 }));
169 }
170 let (closure, executor) = cex.unwrap();
171 unsafe {
172 dispatch_sync_f(queue.unwrap(), closure, executor);
173 }
174 res
175 }
176
177 pub fn run_final<F, B>(&self, work: F) -> Option<B>
178 where
179 F: FnOnce() -> B,
180 {
181 assert!(
182 self.owned.load(Ordering::SeqCst),
183 "Doesn't make sense to finalize global queue"
184 );
185 let queue: Option<dispatch_queue_t>;
186 let mut res: Option<B> = None;
187 let cex: Option<(*mut c_void, dispatch_function_t)>;
188 {
189 let guard = self.queue.lock().unwrap();
190 queue = Some(*guard);
191 let should_cancel = self.get_should_cancel(*guard);
192 debug_assert!(
193 should_cancel.is_some(),
194 "dispatch context should be allocated!"
195 );
196 cex = Some(Self::create_closure_and_executor(|| {
197 res = Some(work());
198 should_cancel
199 .expect("dispatch context should be allocated!")
200 .store(true, Ordering::SeqCst);
201 }));
202 }
203 let (closure, executor) = cex.unwrap();
204 unsafe {
205 dispatch_sync_f(queue.unwrap(), closure, executor);
206 }
207 res
208 }
209
210 fn get_should_cancel(&self, queue: dispatch_queue_t) -> Option<&mut AtomicBool> {
211 if !self.owned.load(Ordering::SeqCst) {
212 return None;
213 }
214 unsafe {
215 let context =
216 dispatch_get_context(mem::transmute::<dispatch_queue_t, dispatch_object_t>(queue))
217 as *mut AtomicBool;
218 context.as_mut()
219 }
220 }
221
222 fn set_should_cancel(&self, context: Box<AtomicBool>) {
223 assert!(self.owned.load(Ordering::SeqCst));
224 unsafe {
225 let guard = self.queue.lock().unwrap();
226 let queue = mem::transmute::<dispatch_queue_t, dispatch_object_t>(*guard);
227 // Leak the context from Box.
228 dispatch_set_context(queue, Box::into_raw(context) as *mut c_void);
229
230 extern "C" fn finalizer(context: *mut c_void) {
231 // Retake the leaked context into box and then drop it.
232 let _ = unsafe { Box::from_raw(context as *mut AtomicBool) };
233 }
234
235 // The `finalizer` is only run if the `context` in `queue` is set by `dispatch_set_context`.
236 dispatch_set_finalizer_f(queue, Some(finalizer));
237 }
238 }
239
240 fn release(&self) {
241 let guard = self.queue.lock().unwrap();
242 let queue = *guard;
243 unsafe {
244 // This will release the inner `dispatch_queue_t` asynchronously.
245 // TODO: It's incredibly unsafe to call `transmute` directly.
246 // Find another way to release the queue.
247 dispatch_release(mem::transmute::<dispatch_queue_t, dispatch_object_t>(queue));
248 }
249 }
250
251 fn create_closure_and_executor<F>(closure: F) -> (*mut c_void, dispatch_function_t)
252 where
253 F: FnOnce(),
254 {
255 extern "C" fn closure_executer<F>(unboxed_closure: *mut c_void)
256 where
257 F: FnOnce(),
258 {
259 // Retake the leaked closure.
260 let closure = unsafe { Box::from_raw(unboxed_closure as *mut F) };
261 // Execute the closure.
262 (*closure)();
263 // closure is released after finishing this function call.
264 }
265
266 let closure = Box::new(closure); // Allocate closure on heap.
267 let executor: dispatch_function_t = Some(closure_executer::<F>);
268
269 (
270 Box::into_raw(closure) as *mut c_void, // Leak the closure.
271 executor,
272 )
273 }
274 }
275
276 impl Drop for Queue {
277 fn drop(&mut self) {
278 if self.owned.load(Ordering::SeqCst) {
279 self.release();
280 }
281 }
282 }
283
284 impl Clone for Queue {
285 fn clone(&self) -> Self {
286 assert!(
287 self.owned.load(Ordering::SeqCst),
288 "No need to clone a static queue"
289 );
290 let guard = self.queue.lock().unwrap();
291 let queue = *guard;
292 // TODO: It's incredibly unsafe to call `transmute` directly.
293 // Find another way to release the queue.
294 unsafe {
295 dispatch_retain(mem::transmute::<dispatch_queue_t, dispatch_object_t>(queue));
296 }
297 Self {
298 queue: Mutex::new(queue),
299 owned: AtomicBool::new(true),
300 }
301 }
302 }
303
304 unsafe impl Send for Queue {}
305 unsafe impl Sync for Queue {}
306
307 #[test]
308 fn run_tasks_in_order() {
309 let mut visited = Vec::<u32>::new();
310
311 // Rust compilter doesn't allow a pointer to be passed across threads.
312 // A hacky way to do that is to cast the pointer into a value, then
313 // the value, which is actually an address, can be copied into threads.
314 let ptr = &mut visited as *mut Vec<u32> as usize;
315
316 fn visit(v: u32, visited_ptr: usize) {
317 let visited = unsafe { &mut *(visited_ptr as *mut Vec<u32>) };
318 visited.push(v);
319 }
320
321 let queue = Queue::new("Run tasks in order");
322
323 queue.run_sync(|| visit(1, ptr));
324 queue.run_sync(|| visit(2, ptr));
325 queue.run_async(|| visit(3, ptr));
326 queue.run_async(|| visit(4, ptr));
327 // Call sync here to block the current thread and make sure all the tasks are done.
328 queue.run_sync(|| visit(5, ptr));
329
330 assert_eq!(visited, vec![1, 2, 3, 4, 5]);
331 }
332
333 #[test]
334 fn run_final_task() {
335 let mut visited = Vec::<u32>::new();
336
337 {
338 // Rust compilter doesn't allow a pointer to be passed across threads.
339 // A hacky way to do that is to cast the pointer into a value, then
340 // the value, which is actually an address, can be copied into threads.
341 let ptr = &mut visited as *mut Vec<u32> as usize;
342
343 fn visit(v: u32, visited_ptr: usize) {
344 let visited = unsafe { &mut *(visited_ptr as *mut Vec<u32>) };
345 visited.push(v);
346 }
347
348 let queue = Queue::new("Task after run_final will be cancelled");
349
350 queue.run_sync(|| visit(1, ptr));
351 queue.run_async(|| visit(2, ptr));
352 queue.run_final(|| visit(3, ptr));
353 queue.run_async(|| visit(4, ptr));
354 queue.run_sync(|| visit(5, ptr));
355 }
356 // `queue` will be dropped asynchronously and then the `finalizer` of the `queue`
357 // should be fired to clean up the `context` set in the `queue`.
358
359 assert_eq!(visited, vec![1, 2, 3]);
360 }
361
362 #[test]
363 fn sync_return_value() {
364 let q = Queue::new("Test queue");
365 assert_eq!(q.run_sync(|| 42), Some(42));
366 assert_eq!(q.run_final(|| "foo"), Some("foo"));
367 assert_eq!(q.run_sync(|| Ok::<(), u32>(())), None);
368 }
369
370 #[test]
371 fn run_after() {
372 let mut visited = Vec::<u32>::new();
373
374 {
375 // Rust compilter doesn't allow a pointer to be passed across threads.
376 // A hacky way to do that is to cast the pointer into a value, then
377 // the value, which is actually an address, can be copied into threads.
378 let ptr = &mut visited as *mut Vec<u32> as usize;
379
380 fn visit(v: u32, visited_ptr: usize) {
381 let visited = unsafe { &mut *(visited_ptr as *mut Vec<u32>) };
382 visited.push(v);
383 }
384
385 let queue = Queue::new("Task after run_final will be cancelled");
386
387 queue.run_async(|| visit(1, ptr));
388 queue.run_after(Instant::now() + Duration::from_millis(10), || visit(2, ptr));
389 queue.run_after(Instant::now() + Duration::from_secs(1), || visit(3, ptr));
390 queue.run_async(|| visit(4, ptr));
391 thread::sleep(Duration::from_millis(100));
392 queue.run_final(|| visit(5, ptr));
393 }
394 // `queue` will be dropped asynchronously and then the `finalizer` of the `queue`
395 // should be fired to clean up the `context` set in the `queue`.
396
397 assert_eq!(visited, vec![1, 4, 2, 5]);
398 }