boc 0.0.1

Behaviour-Oriented Concurrency
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
use core::{fmt, marker::PhantomData, ops};
use std::ops::Deref;

use boc_sys as ffi;

use crate::cown::Cown;

pub struct AcquiredCown<'a, T> {
    // TODO: As an optimization, point to the `T`, and roll the pointer back to
    // find the cown, (instead of pointing to cown, and going forward to T).
    ptr: ffi::CownPtr,
    marker: PhantomData<&'a mut T>,
}

impl<'a, T> AcquiredCown<'a, T> {
    fn data_ptr(&self) -> *mut T {
        super::cown::cown_to_data(self.ptr)
    }
}

impl<'a, T> ops::Deref for AcquiredCown<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.data_ptr() }
    }
}

impl<'a, T> ops::DerefMut for AcquiredCown<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.data_ptr() }
    }
}

impl<'a, T: fmt::Debug> fmt::Debug for AcquiredCown<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.deref(), f)
    }
}
impl<'a, T: fmt::Display> fmt::Display for AcquiredCown<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.deref(), f)
    }
}

unsafe fn make_aq<'a, T>(aq: &ffi::Slot) -> AcquiredCown<'a, T> {
    AcquiredCown {
        ptr: aq.cown,
        marker: PhantomData,
    }
}

macro_rules! one_when {
    (
        $whenfunc:ident
        <
        $($gty:ident $cname:ident $idx:literal),+
        >
    ) => {
        pub fn $whenfunc
            <F, $($gty : 'static),+>
        ($($cname: &Cown<$gty>),+, func: F)
            where
                F: for <'a> FnOnce( $(AcquiredCown<'a, $gty>),+)
                    + Send + 'static
         {
            let cs = [$($cname.cown_ptr),+];
            assert!(is_unique(&cs), "Cowns not unique");
            $crate::schedule_lambda(
                move |s| {
                    unsafe { func($(make_aq(&s[$idx])),+) }
                },
                &cs
            );
        }
    };
}

one_when!(when1 <T cown 0>);
one_when!(when2 <T cown0 0, U cown1 1>);
one_when!(when3 <T cown0 0, U cown1 1, V cown2 2>);
one_when!(when4 <T cown0 0, U cown1 1, V cown2 2, W cown3 3>);
one_when!(when5 <T cown0 0, U cown1 1, V cown2 2, W cown3 3, X cown4 4>);
one_when!(when6 <T cown0 0, U cown1 1, V cown2 2, W cown3 3, X cown4 4, Y cown5 5>);
one_when!(when7 <T cown0 0, U cown1 1, V cown2 2, W cown3 3, X cown4 4, Y cown5 5, Z cown6 6>);
one_when!(when8 <T cown0 0, U cown1 1, V cown2 2, W cown3 3, X cown4 4, Y cown5 5, Z cown6 6, H cown7 7>);
one_when!(when9 <T cown0 0, U cown1 1, V cown2 2, W cown3 3, X cown4 4, Y cown5 5, Z cown6 6, H cown7 7, I cown8 8>);

// FIXME: LLVM eat's shit on this codegen. https://godbolt.org/z/s9sqGqGbP
fn is_unique<const N: usize>(cown: &[ffi::CownPtr; N]) -> bool {
    let mut addrs = cown.map(|c| c.addr());
    addrs.sort_unstable();
    !addrs.windows(2).any(|w| w[0] == w[1])
}

impl<T> AcquiredCown<'_, T> {
    // TODO: This shouldn't be needed.
    // TODO: impl CownCollection for AcquiredCown.
    pub fn cown(&self) -> Cown<T> {
        unsafe {
            ffi::boxcars_acquire_object(self.ptr);
            Cown {
                cown_ptr: self.ptr,
                _marker: PhantomData,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        sync::{
            atomic::{AtomicU8, Ordering},
            Arc, Barrier, Mutex,
        },
        thread,
    };
    use stdx::SetOnDrop;

    use crate::{scheduler, when, with_leak_detector};

    use super::*;

    #[test]
    fn basic() {
        static RUN_COUNTER: AtomicU8 = AtomicU8::new(0);
        fn incr() {
            RUN_COUNTER.fetch_add(1, Ordering::SeqCst);
        }

        assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 0);

        scheduler::with_scheduler(|| {
            let v = Cown::new(101);
            when1(&v, |mut v| {
                assert_eq!(*v, 101);
                *v += 1;
                incr();
            });
            when1(&v, |v| {
                assert_eq!(*v, 102);
                incr();
            });
        });

        assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn when2_runs() {
        static RUN_COUNTER: AtomicU8 = AtomicU8::new(0);

        assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 0);

        scheduler::with_scheduler(|| {
            let v1 = Cown::new(1);
            let v2 = Cown::new(2);
            when2(&v1, &v2, |a1, a2| {
                assert_eq!(*a1, 1);
                assert_eq!(*a2, 2);
                RUN_COUNTER.fetch_add(1, Ordering::SeqCst);
            })
        });

        assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn on_vec() {
        static RUN_COUNTER: AtomicU8 = AtomicU8::new(0);
        fn incr() {
            RUN_COUNTER.fetch_add(1, Ordering::SeqCst);
        }

        assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 0);

        scheduler::with_scheduler(|| {
            let vec_cown = Cown::new(vec![1, 2, 3]);

            when1(&vec_cown, |mut v| {
                assert_eq!(*v, &[1, 2, 3]);
                v.push(4);
                incr();
            });

            when1(&vec_cown, |mut v| {
                assert_eq!(*v, &[1, 2, 3, 4]);
                assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 1);
                assert_eq!(v.pop(), Some(4));
                incr();
            });

            when1(&vec_cown, |v| {
                assert_eq!(*v, &[1, 2, 3]);
                assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 2);
                incr();
            });
        });

        assert_eq!(RUN_COUNTER.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn when_two() {
        scheduler::with_scheduler(|| {
            let string = Cown::new(String::new());
            let vec = Cown::new(Vec::new());

            when1(&string, |mut s| {
                assert_eq!(&*s, "");
                s.push_str("foo");
            });
            when1(&vec, |mut v| {
                assert_eq!(&*v, &[]);
                v.push(101);
            });
            when2(&string, &vec, |mut s, mut v| {
                assert_eq!(&*s, "foo");
                assert_eq!(&*v, &[101]);
                s.push_str("bar");
                v.push(666);
            });
            when1(&string, |s| assert_eq!(&*s, "foobar"));
            when1(&vec, |v| assert_eq!(&*v, &[101, 666]));
        })
    }

    #[test]
    #[should_panic = ""]
    #[ignore = "Panics with schedular lock don't work, see #16"]
    fn double_acquire() {
        scheduler::with_scheduler(|| {
            let c1 = Cown::new(10);
            let c2 = c1.clone();
            when2(&c1, &c2, |_, _| loop {});
        })
    }

    #[test]
    fn fmt_acquired() {
        scheduler::with_scheduler(|| {
            let x = Cown::new("101");
            when1(&x, |x| {
                assert_eq!(*x, "101");
                assert_eq!(format!("{x}"), "101");
                assert_eq!(format!("{x:?}"), r#""101""#);
            })
        })
    }

    #[test]
    fn when_retains_cowns() {
        let bars = Arc::new((Barrier::new(2), Barrier::new(2), Barrier::new(2)));
        let (droptrack, dropstate) = SetOnDrop::new();
        let bars_ = Arc::clone(&bars);

        let in_sched = move || {
            let c_main = Cown::new(droptrack);

            let c_bars = Cown::new(bars_);

            // t0
            when2(&c_main, &c_bars, |_, bars| {
                bars.0.wait();
            });
            // t1
            when2(&c_main, &c_bars, |_, bars| {
                bars.1.wait();
            });
            // t2
            when1(&c_bars, |bars| {
                bars.2.wait();
            });
        };

        let jh = thread::spawn(|| with_leak_detector(in_sched));

        bars.0.wait();
        // t0 may be done, but may not be, but t1 still hold a reference.
        assert_eq!(*dropstate.lock().unwrap(), false);
        bars.1.wait();
        // At some point here, we start running dtor for droptrack.
        bars.2.wait();
        // but it's definitely done here, as we've run t2, which must be after t1, as they
        // both acquire c_bars.
        assert_eq!(*dropstate.lock().unwrap(), true);

        jh.join().unwrap();
    }

    #[test]
    fn when_retains_cown_two() {
        let (droptrack, dropstate) = SetOnDrop::new();
        let bars = Arc::new((
            Barrier::new(2),
            Barrier::new(2),
            Barrier::new(2),
            Barrier::new(2),
        ));
        let bars_ = Arc::clone(&bars);
        let is_dropped = move || *dropstate.lock().unwrap();

        let in_sched = || {
            let c_main = Cown::new(droptrack);

            let c_bars = Cown::new(bars_);

            // t0
            when2(&c_main, &c_bars, |m, bars| {
                assert_eq!(*m.0.lock().unwrap(), false);
                bars.0.wait();
            });
            // t1
            when1(&c_bars, |bars| {
                bars.1.wait();
            });
            // t2
            when2(&c_main, &c_bars, |m, bars| {
                assert_eq!(*m.0.lock().unwrap(), false);
                bars.2.wait();
            });
            // t3
            when1(&c_bars, |bars| {
                bars.3.wait();
            });
        };
        let jh = thread::spawn(|| scheduler::with_leak_detector(in_sched));

        assert_eq!(is_dropped(), false);
        bars.0.wait();
        assert_eq!(is_dropped(), false);
        bars.1.wait();
        assert_eq!(is_dropped(), false);
        bars.2.wait();
        // t2 is over here, but we've not started t3, so unknown if drop has run
        bars.3.wait();
        assert_eq!(is_dropped(), true, "cown should still be alive here");

        jh.join().unwrap();
    }

    #[test]
    fn many_airety() {
        with_leak_detector(|| {
            let c0 = Cown::new(0);
            let c1 = Cown::new(1);
            let c2 = Cown::new(2);
            let c3 = Cown::new(3);
            let c4 = Cown::new(4);
            let c5 = Cown::new(5);
            let c6 = Cown::new(6);
            let c7 = Cown::new(7);
            let c8 = Cown::new(8);

            when9(
                &c0,
                &c1,
                &c2,
                &c3,
                &c4,
                &c5,
                &c6,
                &c7,
                &c8,
                |mut a0, mut a1, mut a2, mut a3, mut a4, mut a5, mut a6, mut a7, mut a8| {
                    assert_eq!(*a0, 0);
                    *a0 *= 10;
                    assert_eq!(*a1, 1);
                    *a1 *= 10;
                    assert_eq!(*a2, 2);
                    *a2 *= 10;
                    assert_eq!(*a3, 3);
                    *a3 *= 10;
                    assert_eq!(*a4, 4);
                    *a4 *= 10;
                    assert_eq!(*a5, 5);
                    *a5 *= 10;
                    assert_eq!(*a6, 6);
                    *a6 *= 10;
                    assert_eq!(*a7, 7);
                    *a7 *= 10;
                    assert_eq!(*a8, 8);
                    *a8 *= 10;
                },
            );

            when6(
                &c0,
                &c1,
                &c2,
                &c3,
                &c4,
                &c5,
                |mut a0, mut a1, mut a2, mut a3, mut a4, mut a5| {
                    assert_eq!(*a0, 0);
                    *a0 *= 10;
                    assert_eq!(*a1, 10);
                    *a1 *= 10;
                    assert_eq!(*a2, 20);
                    *a2 *= 10;
                    assert_eq!(*a3, 30);
                    *a3 *= 10;
                    assert_eq!(*a4, 40);
                    *a4 *= 10;
                    assert_eq!(*a5, 50);
                    *a5 *= 10;
                },
            );

            when3(&c0, &c1, &c2, |mut a0, mut a1, mut a2| {
                assert_eq!(*a0, 0);
                *a0 *= 10;
                assert_eq!(*a1, 100);
                *a1 *= 10;
                assert_eq!(*a2, 200);
                *a2 *= 10;
            });

            when9(
                &c0,
                &c1,
                &c2,
                &c3,
                &c4,
                &c5,
                &c6,
                &c7,
                &c8,
                |mut a0, mut a1, mut a2, mut a3, mut a4, mut a5, mut a6, mut a7, mut a8| {
                    assert_eq!(*a0, 0);
                    *a0 *= 10;
                    assert_eq!(*a1, 1000);
                    *a1 *= 10;
                    assert_eq!(*a2, 2000);
                    *a2 *= 10;
                    assert_eq!(*a3, 300);
                    *a3 *= 10;
                    assert_eq!(*a4, 400);
                    *a4 *= 10;
                    assert_eq!(*a5, 500);
                    *a5 *= 10;
                    assert_eq!(*a6, 60);
                    *a6 *= 10;
                    assert_eq!(*a7, 70);
                    *a7 *= 10;
                    assert_eq!(*a8, 80);
                    *a8 *= 10;
                },
            );
        });
    }

    #[test]
    fn lambda_one() {
        with_leak_detector(|| {
            let shared = Arc::new(Mutex::new(10));
            let shared2 = Arc::clone(&shared);

            let cown = Cown::new(1);

            when1(&cown, move |mut s| {
                assert_eq!(*s, 1);
                let mut shared = shared.lock().unwrap();
                assert_eq!(*shared, 10);
                *shared = 20;
                *s = 2;
            });

            when1(&cown, move |s| {
                assert_eq!(*s, 2);
                let shared = shared2.lock().unwrap();
                assert_eq!(*shared, 20);
            });
        })
    }

    #[test]
    fn acq_cown_to_cown() {
        with_leak_detector(|| {
            let c = Cown::new(1010);

            when1(&c, |c2| {
                when1(&c2.cown(), |c3| {
                    assert_eq!(*c3, 1010);
                })
            });
        })
    }

    #[test]
    fn acq_cown_sync() {
        with_leak_detector(|| {
            struct WaitRoom {
                barber: Cown<i32>,
                value: i32,
            }

            let wr = Cown::new(WaitRoom {
                barber: Cown::new(83),
                value: 566,
            });
            let wr = &wr;
            let customer = Cown::new(345);

            when(wr, move |wr| {
                when((&wr.barber, &customer), {
                    let wr = wr.cown();
                    move |(_, _)| {
                        when(&wr, |wr| {
                            assert_eq!(wr.value, 566);
                        });
                    }
                });
            })
        })
    }
}