1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
#![warn(missing_docs)]
use std::cell::UnsafeCell;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::{c_long, c_void};
use std::ptr;
use std::str;
use std::time::Duration;
use ffi::*;
pub mod ffi;
#[derive(Clone, Debug, Hash, PartialEq)]
pub enum QueueAttribute {
Serial,
Concurrent,
}
impl QueueAttribute {
#[cfg(not(all(test, target_os = "linux")))]
fn as_raw(&self) -> dispatch_queue_attr_t {
match *self {
QueueAttribute::Serial => DISPATCH_QUEUE_SERIAL,
QueueAttribute::Concurrent => DISPATCH_QUEUE_CONCURRENT,
}
}
#[cfg(all(test, target_os = "linux"))]
fn as_raw(&self) -> dispatch_queue_attr_t {
ptr::null()
}
}
#[derive(Clone, Debug, Hash, PartialEq)]
pub enum QueuePriority {
High,
Default,
Low,
Background,
}
impl QueuePriority {
fn as_raw(&self) -> c_long {
match *self {
QueuePriority::High => DISPATCH_QUEUE_PRIORITY_HIGH,
QueuePriority::Default => DISPATCH_QUEUE_PRIORITY_DEFAULT,
QueuePriority::Low => DISPATCH_QUEUE_PRIORITY_LOW,
QueuePriority::Background => DISPATCH_QUEUE_PRIORITY_BACKGROUND,
}
}
}
pub struct Queue {
ptr: dispatch_queue_t,
}
fn time_after_delay(delay: Duration) -> dispatch_time_t {
delay.as_secs().checked_mul(1_000_000_000).and_then(|i| {
i.checked_add(delay.subsec_nanos() as u64)
}).and_then(|i| {
if i < (i64::max_value() as u64) { Some(i as i64) } else { None }
}).map_or(DISPATCH_TIME_FOREVER, |i| unsafe {
dispatch_time(DISPATCH_TIME_NOW, i)
})
}
fn context_and_function<F>(closure: F) -> (*mut c_void, dispatch_function_t)
where F: FnOnce() {
extern fn work_execute_closure<F>(context: Box<F>) where F: FnOnce() {
(*context)();
}
let closure = Box::new(closure);
let func: extern fn(Box<F>) = work_execute_closure::<F>;
unsafe {
(mem::transmute(closure), mem::transmute(func))
}
}
fn context_and_sync_function<F>(closure: &mut Option<F>) ->
(*mut c_void, dispatch_function_t)
where F: FnOnce() {
extern fn work_read_closure<F>(context: &mut Option<F>) where F: FnOnce() {
let closure = context.take().unwrap();
closure();
}
let context: *mut Option<F> = closure;
let func: extern fn(&mut Option<F>) = work_read_closure::<F>;
unsafe {
(context as *mut c_void, mem::transmute(func))
}
}
fn context_and_apply_function<F>(closure: &F) ->
(*mut c_void, extern fn(*mut c_void, usize))
where F: Fn(usize) {
extern fn work_apply_closure<F>(context: &F, iter: usize)
where F: Fn(usize) {
context(iter);
}
let context: *const F = closure;
let func: extern fn(&F, usize) = work_apply_closure::<F>;
unsafe {
(context as *mut c_void, mem::transmute(func))
}
}
impl Queue {
pub fn main() -> Self {
let queue = dispatch_get_main_queue();
unsafe {
dispatch_retain(queue);
}
Queue { ptr: queue }
}
pub fn global(priority: QueuePriority) -> Self {
unsafe {
let queue = dispatch_get_global_queue(priority.as_raw(), 0);
dispatch_retain(queue);
Queue { ptr: queue }
}
}
pub fn create(label: &str, attr: QueueAttribute) -> Self {
let label = CString::new(label).unwrap();
let queue = unsafe {
dispatch_queue_create(label.as_ptr(), attr.as_raw())
};
Queue { ptr: queue }
}
pub fn with_target_queue(label: &str, attr: QueueAttribute, target: &Queue)
-> Self {
let queue = Queue::create(label, attr);
unsafe {
dispatch_set_target_queue(queue.ptr, target.ptr);
}
queue
}
pub fn label(&self) -> &str {
let label = unsafe {
let label_ptr = dispatch_queue_get_label(self.ptr);
if label_ptr.is_null() {
return "";
}
CStr::from_ptr(label_ptr)
};
str::from_utf8(label.to_bytes()).unwrap()
}
pub fn sync<T, F>(&self, work: F) -> T
where F: Send + FnOnce() -> T, T: Send {
let mut result = None;
{
let result_ref = &mut result;
let work = move || {
*result_ref = Some(work());
};
let mut work = Some(work);
let (context, work) = context_and_sync_function(&mut work);
unsafe {
dispatch_sync_f(self.ptr, context, work);
}
}
result.unwrap()
}
pub fn async<F>(&self, work: F) where F: 'static + Send + FnOnce() {
let (context, work) = context_and_function(work);
unsafe {
dispatch_async_f(self.ptr, context, work);
}
}
pub fn after_ms<F>(&self, ms: u32, work: F)
where F: 'static + Send + FnOnce() {
self.after(Duration::from_millis(ms as u64), work);
}
pub fn after<F>(&self, delay: Duration, work: F)
where F: 'static + Send + FnOnce() {
let when = time_after_delay(delay);
let (context, work) = context_and_function(work);
unsafe {
dispatch_after_f(when, self.ptr, context, work);
}
}
pub fn apply<F>(&self, iterations: usize, work: F)
where F: Sync + Fn(usize) {
let (context, work) = context_and_apply_function(&work);
unsafe {
dispatch_apply_f(iterations, self.ptr, context, work);
}
}
pub fn foreach<T, F>(&self, slice: &mut [T], work: F)
where F: Sync + Fn(&mut T), T: Send {
let slice_ptr = slice.as_mut_ptr();
let work = move |i| unsafe {
work(&mut *slice_ptr.offset(i as isize));
};
let (context, work) = context_and_apply_function(&work);
unsafe {
dispatch_apply_f(slice.len(), self.ptr, context, work);
}
}
pub fn map<T, U, F>(&self, vec: Vec<T>, work: F) -> Vec<U>
where F: Sync + Fn(T) -> U, T: Send, U: Send {
let mut src = vec;
let len = src.len();
let src_ptr = src.as_ptr();
let mut dest: Vec<U> = Vec::with_capacity(len);
let dest_ptr = dest.as_mut_ptr();
let work = move |i| unsafe {
let result = work(ptr::read(src_ptr.offset(i as isize)));
ptr::write(dest_ptr.offset(i as isize), result);
};
let (context, work) = context_and_apply_function(&work);
unsafe {
src.set_len(0);
dispatch_apply_f(len, self.ptr, context, work);
dest.set_len(len);
}
dest
}
pub fn barrier_sync<T, F>(&self, work: F) -> T
where F: Send + FnOnce() -> T, T: Send {
let mut result = None;
{
let result_ref = &mut result;
let work = move || {
*result_ref = Some(work());
};
let mut work = Some(work);
let (context, work) = context_and_sync_function(&mut work);
unsafe {
dispatch_barrier_sync_f(self.ptr, context, work);
}
}
result.unwrap()
}
pub fn barrier_async<F>(&self, work: F)
where F: 'static + Send + FnOnce() {
let (context, work) = context_and_function(work);
unsafe {
dispatch_barrier_async_f(self.ptr, context, work);
}
}
pub fn suspend(&self) -> SuspendGuard {
SuspendGuard::new(self)
}
}
unsafe impl Sync for Queue { }
unsafe impl Send for Queue { }
impl Clone for Queue {
fn clone(&self) -> Self {
unsafe {
dispatch_retain(self.ptr);
}
Queue { ptr: self.ptr }
}
}
impl Drop for Queue {
fn drop(&mut self) {
unsafe {
dispatch_release(self.ptr);
}
}
}
pub struct SuspendGuard {
queue: Queue,
}
impl SuspendGuard {
fn new(queue: &Queue) -> SuspendGuard {
unsafe {
dispatch_suspend(queue.ptr);
}
SuspendGuard { queue: queue.clone() }
}
pub fn resume(self) { }
}
impl Clone for SuspendGuard {
fn clone(&self) -> Self {
SuspendGuard::new(&self.queue)
}
}
impl Drop for SuspendGuard {
fn drop(&mut self) {
unsafe {
dispatch_resume(self.queue.ptr);
}
}
}
pub struct Group {
ptr: dispatch_group_t,
}
impl Group {
pub fn create() -> Group {
unsafe {
Group { ptr: dispatch_group_create() }
}
}
pub fn enter(&self) -> GroupGuard {
GroupGuard::new(self)
}
pub fn async<F>(&self, queue: &Queue, work: F)
where F: 'static + Send + FnOnce() {
let (context, work) = context_and_function(work);
unsafe {
dispatch_group_async_f(self.ptr, queue.ptr, context, work);
}
}
pub fn notify<F>(&self, queue: &Queue, work: F)
where F: 'static + Send + FnOnce() {
let (context, work) = context_and_function(work);
unsafe {
dispatch_group_notify_f(self.ptr, queue.ptr, context, work);
}
}
pub fn wait(&self) {
let result = unsafe {
dispatch_group_wait(self.ptr, DISPATCH_TIME_FOREVER)
};
assert!(result == 0, "Dispatch group wait errored");
}
pub fn wait_timeout_ms(&self, ms: u32) -> bool {
self.wait_timeout(Duration::from_millis(ms as u64))
}
pub fn wait_timeout(&self, timeout: Duration) -> bool {
let when = time_after_delay(timeout);
let result = unsafe {
dispatch_group_wait(self.ptr, when)
};
result == 0
}
pub fn is_empty(&self) -> bool {
let result = unsafe {
dispatch_group_wait(self.ptr, DISPATCH_TIME_NOW)
};
result == 0
}
}
unsafe impl Sync for Group { }
unsafe impl Send for Group { }
impl Clone for Group {
fn clone(&self) -> Self {
unsafe {
dispatch_retain(self.ptr);
}
Group { ptr: self.ptr }
}
}
impl Drop for Group {
fn drop(&mut self) {
unsafe {
dispatch_release(self.ptr);
}
}
}
pub struct GroupGuard {
group: Group,
}
impl GroupGuard {
fn new(group: &Group) -> GroupGuard {
unsafe {
dispatch_group_enter(group.ptr);
}
GroupGuard { group: group.clone() }
}
pub fn leave(self) { }
}
impl Clone for GroupGuard {
fn clone(&self) -> Self {
GroupGuard::new(&self.group)
}
}
impl Drop for GroupGuard {
fn drop(&mut self) {
unsafe {
dispatch_group_leave(self.group.ptr);
}
}
}
#[allow(dead_code)]
struct Once {
predicate: UnsafeCell<dispatch_once_t>,
}
#[allow(dead_code)]
impl Once {
pub fn new() -> Once {
Once { predicate: UnsafeCell::new(0) }
}
#[inline(always)]
pub fn call_once<F>(&'static self, work: F) where F: FnOnce() {
#[cold]
#[inline(never)]
fn once<F>(predicate: *mut dispatch_once_t, work: F)
where F: FnOnce() {
let mut work = Some(work);
let (context, work) = context_and_sync_function(&mut work);
unsafe {
dispatch_once_f(predicate, context, work);
}
}
unsafe {
let predicate = self.predicate.get();
if *predicate != !0 {
once(predicate, work);
}
}
}
}
unsafe impl Sync for Once { }
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::*;
fn async_increment(queue: &Queue, num: &Arc<Mutex<i32>>) {
let num = num.clone();
queue.async(move || {
let mut num = num.lock().unwrap();
*num += 1;
});
}
#[test]
fn test_serial_queue() {
let q = Queue::create("", QueueAttribute::Serial);
let mut num = 0;
q.sync(|| num = 1);
assert_eq!(num, 1);
assert_eq!(q.sync(|| num), 1);
}
#[test]
fn test_sync_owned() {
let q = Queue::create("", QueueAttribute::Serial);
let s = "Hello, world!".to_string();
let len = q.sync(move || s.len());
assert_eq!(len, 13);
}
#[test]
fn test_serial_queue_async() {
let q = Queue::create("", QueueAttribute::Serial);
let num = Arc::new(Mutex::new(0));
async_increment(&q, &num);
q.sync(|| ());
assert_eq!(*num.lock().unwrap(), 1);
}
#[test]
fn test_after() {
let q = Queue::create("", QueueAttribute::Serial);
let group = Group::create();
let num = Arc::new(Mutex::new(0));
let delay = Duration::from_millis(5);
let num2 = num.clone();
let guard = group.enter();
let start = Instant::now();
q.after(delay, move || {
let mut num = num2.lock().unwrap();
*num = 1;
guard.leave();
});
assert!(group.wait_timeout(Duration::from_millis(5000)));
assert!(start.elapsed() >= delay);
assert_eq!(*num.lock().unwrap(), 1);
}
#[test]
fn test_queue_label() {
let q = Queue::create("com.example.rust", QueueAttribute::Serial);
assert_eq!(q.label(), "com.example.rust");
}
#[test]
fn test_apply() {
let q = Queue::create("", QueueAttribute::Serial);
let num = Arc::new(Mutex::new(0));
q.apply(5, |_| *num.lock().unwrap() += 1);
assert_eq!(*num.lock().unwrap(), 5);
}
#[test]
fn test_foreach() {
let q = Queue::create("", QueueAttribute::Serial);
let mut nums = [0, 1];
q.foreach(&mut nums, |x| *x += 1);
assert_eq!(nums, [1, 2]);
}
#[test]
fn test_map() {
let q = Queue::create("", QueueAttribute::Serial);
let nums = vec![0, 1];
let result = q.map(nums, |x| x + 1);
assert_eq!(result, [1, 2]);
}
#[test]
fn test_barrier_sync() {
let q = Queue::create("", QueueAttribute::Concurrent);
let num = Arc::new(Mutex::new(0));
async_increment(&q, &num);
async_increment(&q, &num);
let num2 = num.clone();
let result = q.barrier_sync(move || {
let mut num = num2.lock().unwrap();
if *num == 2 {
*num = 10;
}
*num
});
assert_eq!(result, 10);
async_increment(&q, &num);
async_increment(&q, &num);
q.barrier_sync(|| ());
assert_eq!(*num.lock().unwrap(), 12);
}
#[test]
fn test_barrier_async() {
let q = Queue::create("", QueueAttribute::Concurrent);
let num = Arc::new(Mutex::new(0));
async_increment(&q, &num);
async_increment(&q, &num);
let num2 = num.clone();
q.barrier_async(move || {
let mut num = num2.lock().unwrap();
if *num == 2 {
*num = 10;
}
});
async_increment(&q, &num);
async_increment(&q, &num);
q.barrier_sync(|| ());
assert_eq!(*num.lock().unwrap(), 12);
}
#[test]
fn test_suspend() {
let q = Queue::create("", QueueAttribute::Serial);
let num = Arc::new(Mutex::new(0));
let guard = q.suspend();
async_increment(&q, &num);
::std::thread::sleep(Duration::from_millis(5));
assert_eq!(*num.lock().unwrap(), 0);
guard.resume();
q.sync(|| ());
assert_eq!(*num.lock().unwrap(), 1);
}
#[test]
fn test_group() {
let group = Group::create();
let q = Queue::create("", QueueAttribute::Serial);
let num = Arc::new(Mutex::new(0));
let num2 = num.clone();
group.async(&q, move || {
let mut num = num2.lock().unwrap();
*num += 1;
});
let guard = group.enter();
assert!(!group.is_empty());
let num3 = num.clone();
q.async(move || {
let mut num = num3.lock().unwrap();
*num += 1;
guard.leave();
});
let notify_group = Group::create();
let guard = notify_group.enter();
let num4 = num.clone();
group.notify(&q, move || {
let mut num = num4.lock().unwrap();
*num *= 5;
guard.leave();
});
notify_group.wait();
assert!(group.is_empty());
assert_eq!(*num.lock().unwrap(), 10);
}
}