cidre 0.11.4

Apple frameworks bindings for rust
Documentation
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
// https://opensource.apple.com/source/libclosure/libclosure-79/BlockImplementation.txt.auto.html
// https://github.com/apple-oss-distributions/libclosure/blob/main/BlockImplementation.txt
// https://developer.apple.com/documentation/swift/calling-objective-c-apis-asynchronously
// https://github.com/apple/swift-corelibs-foundation/blob/main/Sources/BlocksRuntime/runtime.c

use std::{
    ffi::c_void, marker::PhantomData, marker::Send as MarkerSend, marker::Sync as MarkerSync, mem,
};

use crate::{arc, define_opts, ns, objc};

#[cfg(feature = "custom-allocator")]
use crate::cf;

// block attributes

#[derive(Debug)]
pub struct NoEsc;
#[derive(Debug)]
pub struct Esc;
#[derive(Debug)]
pub struct Send;
#[derive(Debug)]
pub struct Sync;

// attributted blocks

pub type NoEscBlock<F> = Block<F, NoEsc>;
pub type EscBlock<F> = Block<F, Esc>;
pub type SendBlock<F> = Block<F, Send>;
pub type SyncBlock<F> = Block<F, Sync>;

pub type CompletionBlock = EscBlock<fn()>;
pub type WorkBlock<Attr = Sync> = Block<fn(), Attr>;

/// Error Completion Handler
pub type ErrCh<E = ns::Error> = EscBlock<fn(error: Option<&E>)>;

/// Result Completion Handler
pub type ResultCh<T> = EscBlock<fn(Option<&T>, Option<&ns::Error>)>;

#[derive(Debug)]
#[repr(transparent)]
pub struct Block<Sig, Attr = NoEsc>(ns::Id, PhantomData<(Sig, Attr)>);

#[derive(Debug)]
#[repr(transparent)]
pub struct StackBlock<'a, Closure, Sig>(Layout1Mut<'a, Closure>, PhantomData<Sig>);

#[derive(Debug)]
#[repr(transparent)]
pub struct StaticBlock<Sig>(Layout1, PhantomData<Sig>);

impl<Sig> std::ops::Deref for Block<Sig, NoEsc> {
    type Target = ns::Id;

    fn deref(&self) -> &Self::Target {
        unsafe { std::mem::transmute(self) }
    }
}

impl<Sig, Attr> objc::Obj for Block<Sig, Attr> {
    #[inline]
    unsafe fn retain(id: &Self) -> arc::R<Self> {
        unsafe { std::mem::transmute(_Block_copy(std::mem::transmute(id))) }
    }

    #[inline]
    unsafe fn release(id: &mut Self) {
        unsafe { _Block_release(std::mem::transmute(id)) }
    }
}

impl<'a, Closure, Sig> std::ops::Deref for StackBlock<'a, Closure, Sig> {
    type Target = Block<Sig, NoEsc>;

    fn deref(&self) -> &Self::Target {
        unsafe { std::mem::transmute(self) }
    }
}

impl<'a, Closure, Sig> std::ops::DerefMut for StackBlock<'a, Closure, Sig> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { std::mem::transmute(self) }
    }
}

macro_rules! call {
    ($($a:ident: $t:ident),*) => {
        impl<$($t,)* R, Attr> Block<fn($($t,)*) -> R, Attr> {
            pub fn call(&mut self, $($a: $t),*) -> R {
                let layout: &Layout1 = unsafe { std::mem::transmute(&self.0) };
                let f: extern "C" fn(literal: &mut Self $(, $t)*) -> R = unsafe { std::mem::transmute(layout.invoke) };
                f(self $(, $a)*)
            }
        }
    };
}

macro_rules! invoke {
    ($name:ident: $($a:ident: $t:ident),*) => {
        extern "C" fn $name<$($t,)* R>(&mut self, $($a: $t),*) -> R
        where
            Closure: FnMut($($t,)*) -> R,
        {
            (self.closure)($($a,)*)
        }
    };
}

macro_rules! new {
    ($name:ident, $invoke:ident: $($t:ident),* $(+ $l:lifetime)* $(+ $trait:ident)*) => {
        pub fn $name<$($t,)* R, Closure>(closure: Closure) -> arc::R<Self>
        where
            Sig: Fn($($t,)*) -> R, // guard for Block Sig
            for<'c> Closure: FnMut($($t,)*) -> R $(+ $l)* $(+ $trait)*,
        {
            let res = Layout2Mut::new(Layout2Mut::<Closure>::$invoke as _, closure);
            unsafe { std::mem::transmute(res) }
        }
    };
}

macro_rules! with_fn {
    ($name:ident: $($t:ident),* ) => {
        pub const fn $name<$($t,)* R>(func: extern "C" fn (*const c_void, $($t,)*) -> R) -> StaticBlock<Sig>
        {
            let res = Layout1::with(func as _);
            StaticBlock(res, PhantomData)
        }
    };
}

macro_rules! stack {
    ($name:ident, $invoke:ident: $($t:ident),*) => {
        #[inline]
        pub const unsafe fn $name<$($t,)* R, Closure>(closure: &mut Closure) -> StackBlock<'_, Closure, Sig>
        where
            Sig: Fn($($t,)*) -> R, // guard for Block Sig
            for<'c> Closure: FnMut($($t,)*) -> R
        {
            let layout = Layout1Mut::new(Layout1Mut::<Closure>::$invoke as _, closure);
            StackBlock(layout, PhantomData)
        }
    };
}

impl<Sig, Attr> Block<Sig, Attr> {
    with_fn!(with_fn0:);
    with_fn!(with_fn1: A);
    with_fn!(with_fn2: A, B);
    with_fn!(with_fn3: A, B, C);
    with_fn!(with_fn4: A, B, C, D);
    with_fn!(with_fn5: A, B, C, D, E);
    with_fn!(with_fn6: A, B, C, D, E, F);
}

impl<Sig> Block<Sig, NoEsc> {
    stack!(stack0, invoke0:);
    stack!(stack1, invoke1: A);
    stack!(stack2, invoke2: A, B);
    stack!(stack3, invoke3: A, B, C);
    stack!(stack4, invoke4: A, B, C, D);
    stack!(stack5, invoke5: A, B, C, D, E);
    stack!(stack6, invoke6: A, B, C, D, E, F);

    new!(new0, invoke0:);
    new!(new1, invoke1: A);
    new!(new2, invoke2: A, B);
    new!(new3, invoke3: A, B, C);
    new!(new4, invoke4: A, B, C, D);
    new!(new5, invoke5: A, B, C, D, E);
    new!(new6, invoke6: A, B, C, D, E, F);
}

impl<Sig> Block<Sig, Esc> {
    new!(new0, invoke0: + 'static);
    new!(new1, invoke1: A + 'static);
    new!(new2, invoke2: A, B + 'static);
    new!(new3, invoke3: A, B, C + 'static);
    new!(new4, invoke4: A, B, C, D + 'static);
    new!(new5, invoke5: A, B, C, D, E + 'static);
    new!(new6, invoke6: A, B, C, D, E, F + 'static);

    pub fn as_noesc_mut(&mut self) -> &mut Block<Sig, NoEsc> {
        unsafe { std::mem::transmute(self) }
    }
}

impl<Sig> Block<Sig, Send> {
    new!(new0, invoke0: + 'static + MarkerSend);
    new!(new1, invoke1: A + 'static + MarkerSend);
    new!(new2, invoke2: A, B + 'static + MarkerSend);
    new!(new3, invoke3: A, B, C + 'static + MarkerSend);
    new!(new4, invoke4: A, B, C, D + 'static + MarkerSend);
    new!(new5, invoke5: A, B, C, D, E + 'static + MarkerSend);
    new!(new6, invoke6: A, B, C, D, E, F + 'static + MarkerSend);

    pub fn as_esc_mut(&mut self) -> &mut Block<Sig, Esc> {
        unsafe { std::mem::transmute(self) }
    }

    pub fn as_noesc_mut(&mut self) -> &mut Block<Sig, NoEsc> {
        unsafe { std::mem::transmute(self) }
    }
}

impl<Sig> Block<Sig, Sync> {
    new!(new0, invoke0: + 'static + MarkerSync);
    new!(new1, invoke1: A + 'static + MarkerSync);
    new!(new2, invoke2: A, B + 'static + MarkerSync);
    new!(new3, invoke3: A, B, C + 'static + MarkerSync);
    new!(new4, invoke4: A, B, C, D + 'static + MarkerSync);
    new!(new5, invoke5: A, B, C, D, E + 'static + MarkerSync);
    new!(new6, invoke6: A, B, C, D, E, F + 'static + MarkerSync);

    pub fn as_send_mut(&mut self) -> &mut Block<Sig, Send> {
        unsafe { std::mem::transmute(self) }
    }

    pub fn as_esc_mut(&mut self) -> &mut Block<Sig, Esc> {
        unsafe { std::mem::transmute(self) }
    }

    pub fn as_noesc_mut(&mut self) -> &mut Block<Sig, NoEsc> {
        unsafe { std::mem::transmute(self) }
    }
}

impl<Sig> StaticBlock<Sig> {
    with_fn!(new0:);
    with_fn!(new1: A);
    with_fn!(new2: A, B);
    with_fn!(new3: A, B, C);
    with_fn!(new4: A, B, C, D);
    with_fn!(new5: A, B, C, D, E);
    with_fn!(new6: A, B, C, D, E, F);

    pub fn as_sync_mut(&mut self) -> &mut Block<Sig, Sync> {
        unsafe { std::mem::transmute(self) }
    }

    pub fn as_send_mut(&mut self) -> &mut Block<Sig, Send> {
        unsafe { std::mem::transmute(self) }
    }

    pub fn as_esc_mut(&mut self) -> &mut Block<Sig, Esc> {
        unsafe { std::mem::transmute(self) }
    }

    pub fn as_noesc_mut(&mut self) -> &mut Block<Sig, NoEsc> {
        unsafe { std::mem::transmute(self) }
    }
}

call!();
call!(a:A);
call!(a:A, b: B);
call!(a:A, b: B, c: C);
call!(a:A, b: B, c: C, d: D);
call!(a:A, b: B, c: C, d: D, e: E);
call!(a:A, b: B, c: C, d: D, e: E, f: F);
call!(a:A, b: B, c: C, d: D, e: E, f: F, g: G);
call!(a:A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
call!(a:A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
call!(a:A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
call!(a:A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K);

//         // TODO: revisit
//         unsafe impl<'a, $($t,)* R> Send for $bl_name<'a$(, $t)*, R> {}
//         unsafe impl<'a, $($t,)* R> Sync for $bl_name<'a$(, $t)*, R> {}

define_opts!(pub Flags(i32));

impl Flags {
    pub const NONE: Self = Self(0);

    // runtime
    pub const DEALLOCATING: Self = Self(1);

    // runtime
    pub const REFCOUNT_MASK: Self = Self(0xfffei32);

    // compiler
    // Set to true on blocks that have captures (and thus are not true
    // global blocks) but are known not to escape for various other
    // reasons. For backward compatibility with old runtimes, whenever
    // IS_NOESCAPE is set, IS_GLOBAL is set too. Copying a
    // non-escaping block returns the original block and releasing such a
    // block is a no-op, which is exactly how global blocks are handled.
    // pub const IS_NOESCAPE: Self = Self(1 << 23);

    // runtime
    pub const NEEDS_FREE: Self = Self(1 << 24);
    // compiler
    pub const HAS_COPY_DISPOSE: Self = Self(1 << 25);
    // pub const HAS_CTOR: Self = Self(1 << 26);
    // pub const IS_GC: Self = Self(1 << 27);
    // pub const IS_GLOBAL: Self = Self(1 << 28);
    // pub const USE_STRET: Self = Self(1 << 29);
    // pub const HAS_SIGNATURE: Self = Self(1 << 30);
    // pub const HAS_EXTENDED_LAYOUT: Self = Self(1 << 31);

    const RETAINED_NEEDS_FREE: Self = Self(2 | Self::NEEDS_FREE.0);
    const RETAINED_NEEDS_DROP: Self = Self(2 | Self::NEEDS_FREE.0 | Self::HAS_COPY_DISPOSE.0);
}

#[derive(Debug)]
#[repr(C)]
pub struct Desc1 {
    reserved: usize,
    size: usize,
}

#[derive(Debug)]
#[repr(C)]
pub struct Desc2<T: Sized> {
    descriptor1: Desc1,
    copy: extern "C" fn(dest: *mut c_void, src: *mut c_void),
    dispose: extern "C" fn(literal: &mut T),
}

#[derive(Debug)]
#[repr(C)]
pub struct Layout1 {
    isa: &'static objc::Class<ns::Id>,
    flags: Flags,
    reserved: i32,
    invoke: *const c_void,
    descriptor: &'static Desc1,
}

#[derive(Debug)]
#[repr(C)]
pub struct Layout1Mut<'a, Closure> {
    isa: &'static objc::Class<ns::Id>,
    flags: Flags,
    reserved: i32,
    invoke: *const c_void,
    descriptor: &'a Desc1,
    closure: &'a mut Closure,
}

#[derive(Debug)]
#[repr(C)]
struct Layout2Mut<'a, F: Sized + 'a> {
    isa: &'static objc::Class<ns::Id>,
    flags: Flags,
    reserved: i32,
    invoke: *const c_void,
    descriptor: &'a Desc2<Self>,
    closure: mem::ManuallyDrop<F>,
}

impl Layout1 {
    const DESCRIPTOR: Desc1 = Desc1 {
        reserved: 0,
        size: std::mem::size_of::<Self>(),
    };

    pub const fn with(invoke: *const c_void) -> Self {
        Self {
            isa: unsafe { &_NSConcreteStackBlock },
            flags: Flags::NONE,
            reserved: 0,
            invoke,
            descriptor: &Self::DESCRIPTOR,
        }
    }
}

impl<'a, Closure> Layout1Mut<'a, Closure> {
    const DESCRIPTOR_1: Desc1 = Desc1 {
        reserved: 0,
        size: std::mem::size_of::<&'static objc::Class<ns::Id>>()
            + std::mem::size_of::<Flags>()
            + std::mem::size_of::<i32>()
            + std::mem::size_of::<*const c_void>()
            + std::mem::size_of::<&'static Desc1>()
            + std::mem::size_of::<&'static c_void>(), // emulating &mut F
    };

    invoke! {invoke0: }
    invoke! {invoke1: a: A}
    invoke! {invoke2: a: A, b: B}
    invoke! {invoke3: a: A, b: B, c: C}
    invoke! {invoke4: a: A, b: B, c: C, d: D}
    invoke! {invoke5: a: A, b: B, c: C, d: D, e: E}
    invoke! {invoke6: a: A, b: B, c: C, d: D, e: E, f: F}

    const fn new(invoke: *const c_void, f: &'a mut Closure) -> Self {
        Self {
            isa: unsafe { &_NSConcreteStackBlock },
            flags: Flags::NONE,
            reserved: 0,
            invoke,
            descriptor: &Self::DESCRIPTOR_1,
            closure: f,
        }
    }
}

extern "C" fn no_copy(_dest: *mut c_void, _src: *mut c_void) {
    panic!("copy should not be called");
}

impl<'a, Closure: 'a + Sized> Layout2Mut<'a, Closure> {
    const DESCRIPTOR_2: Desc2<Self> = Desc2 {
        descriptor1: Desc1 {
            reserved: 0,
            size: std::mem::size_of::<Self>(),
        },
        copy: no_copy,
        dispose: Self::dispose,
    };

    extern "C" fn dispose(block: &mut Self) {
        debug_assert!(mem::needs_drop::<Closure>());
        unsafe {
            mem::ManuallyDrop::drop(&mut block.closure);
        }
    }

    invoke! {invoke0: }
    invoke! {invoke1: a: A}
    invoke! {invoke2: a: A, b: B}
    invoke! {invoke3: a: A, b: B, c: C}
    invoke! {invoke4: a: A, b: B, c: C, d: D}
    invoke! {invoke5: a: A, b: B, c: C, d: D, e: E}
    invoke! {invoke6: a: A, b: B, c: C, d: D, e: E, f: F}

    fn new(invoke: *const c_void, closure: Closure) -> &'a mut Self {
        let flags = if mem::needs_drop::<Closure>() {
            Flags::RETAINED_NEEDS_DROP
        } else {
            Flags::RETAINED_NEEDS_FREE
        };

        #[cfg(not(feature = "custom-allocator"))]
        {
            // we assume allocator is malloc. So it is safe
            // to allocate with Box::new and leak
            // so _Block_release will be able to free mem
            let block = Box::new(Self {
                isa: unsafe { &_NSConcreteMallocBlock },
                flags,
                reserved: 0,
                invoke,
                descriptor: &Self::DESCRIPTOR_2,
                closure: mem::ManuallyDrop::new(closure),
            });
            Box::leak(block)
        }
        #[cfg(feature = "custom-allocator")]
        {
            // We can't use Box::new since global allocator could be changed.
            // We use cf::Allocator to allocate block
            // so _Block_release will be able to free mem
            //
            // Another option is to use _Block_copy from stacked block but
            // it is another few function calls
            let block = Self {
                isa: unsafe { &_NSConcreteMallocBlock },
                flags,
                reserved: 0,
                invoke,
                descriptor: &Self::DESCRIPTOR_2,
                closure: mem::ManuallyDrop::new(closure),
            };

            let layout = std::alloc::Layout::new::<Self>();

            unsafe {
                let ptr = cf::Allocator::allocate_size(layout.size());
                *(ptr as *mut Self) = block;
                std::mem::transmute(ptr)
            }
        }
    }
}

#[link(name = "System", kind = "dylib")]
unsafe extern "C-unwind" {
    // static _NSConcreteGlobalBlock: objc::Class<ns::Id>;
    static _NSConcreteStackBlock: objc::Class<ns::Id>;
    static _NSConcreteMallocBlock: objc::Class<ns::Id>;

    fn _Block_copy(block: *const c_void) -> *const c_void;
    fn _Block_release(block: *const c_void);
}

#[cfg(test)]
mod tests {

    use crate::{blocks, dispatch};

    #[derive(Debug)]
    struct Foo;

    impl Drop for Foo {
        fn drop(&mut self) {
            println!("dropped foo");
        }
    }

    #[test]
    fn simple_block() {
        let foo = Foo;
        // let rc = Rc::new(10);
        let mut b = dispatch::Block::<blocks::Send>::new0(move || println!("nice {foo:?}"));

        let q = dispatch::Queue::new();
        q.async_b(&mut b);
        q.async_b(&mut b);
        q.async_mut(|| println!("nice"));
        q.sync_mut(|| println!("fuck"));
        // q.async_once(move || println!("nice {rc:?}"));

        println!("finished");
    }
}

#[cfg(feature = "async")]
use parking_lot::Mutex;

#[cfg(feature = "async")]
use std::sync::Arc;

#[cfg(feature = "async")]
pub(crate) struct Shared<T> {
    ready: Option<T>,
    pending: Option<std::task::Waker>,
}

#[cfg(feature = "async")]
impl<T> Shared<T> {
    pub(crate) fn new() -> Arc<Mutex<Self>> {
        Arc::new(Mutex::new(Self {
            ready: None,
            pending: None,
        }))
    }

    pub fn ready(&mut self, result: T) {
        self.ready = Some(result);

        if let Some(waker) = self.pending.take() {
            waker.wake();
        }
    }
}

#[cfg(feature = "async")]
pub struct Completion<R>(Arc<Mutex<Shared<R>>>);

#[cfg(feature = "async")]
impl<R> Completion<R> {
    pub(crate) const fn new(r: Arc<Mutex<Shared<R>>>) -> Self {
        Self(r)
    }
}

#[cfg(feature = "async")]
impl<T> std::future::Future for Completion<T> {
    type Output = T;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        let mut lock = self.0.lock();

        if let Some(r) = lock.ready.take() {
            std::task::Poll::Ready(r)
        } else {
            lock.pending = Some(cx.waker().clone());
            std::task::Poll::Pending
        }
    }
}

#[cfg(feature = "async")]
pub fn comp0() -> (Completion<()>, arc::R<CompletionBlock>) {
    let shared = Shared::new();
    (
        Completion(shared.clone()),
        CompletionBlock::new0(move || shared.lock().ready(())),
    )
}

#[cfg(feature = "async")]
pub fn comp1<R: std::marker::Send>() -> (Completion<R>, arc::R<Block<fn(R), Send>>) {
    let shared = Shared::new();
    (
        Completion(shared.clone()),
        SendBlock::new1(move |v: R| shared.lock().ready(v)),
    )
}

#[cfg(feature = "async")]
pub fn retained1<R: arc::Retain + std::marker::Send>()
-> (Completion<arc::R<R>>, arc::R<Block<fn(&R), Send>>) {
    let shared = Shared::new();
    (
        Completion(shared.clone()),
        SendBlock::new1(move |v: &R| shared.lock().ready(v.retained())),
    )
}

#[cfg(feature = "async")]
pub fn ok<'a>() -> (Completion<Result<(), arc::R<ns::Error>>>, arc::R<ErrCh>) {
    let shared = Shared::new();
    (
        Completion(shared.clone()),
        ErrCh::new1(move |error: Option<&ns::Error>| {
            shared.lock().ready(match error {
                None => Ok(()),
                Some(err) => Err(err.retained()),
            });
        }),
    )
}

#[cfg(feature = "async")]
pub fn result<T: arc::Retain + std::marker::Send>() -> (
    Completion<Result<arc::R<T>, arc::R<ns::Error>>>,
    arc::R<ResultCh<T>>,
) {
    let shared = Shared::new();
    (
        Completion(shared.clone()),
        ResultCh::<T>::new2(move |value: Option<&T>, error: Option<&ns::Error>| {
            let res = match error {
                None => Ok(unsafe { value.unwrap_unchecked().retained() }),
                Some(err) => Err(err.retained()),
            };

            shared.lock().ready(res);
        }),
    )
}