interlock 0.0.4

Readers-writer locks designed for locking intervals
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
use quickcheck_macros::quickcheck;

use std::prelude::v1::*;

type Index = usize;
type Priority = u64;
type InProgress = LockId;

type IsWrite = bool;

const LEN: usize = 32;

// Reference Implementation
// --------------------------------------------------------------------------

// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⢀⣀⣀⣠⣀⣄⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⢀⣀⣀⣠⣤⣤⣄⣤⣠⣤⣠⣤⣠⣄⣤⣄⣤⣤⣠⣤⣠⣄⣤⣄⣤⣠⣄⣤⣠⣄⣤⣠⣄⣤⣠⣠⣠⣠⣠⣠⣠⣠⣠
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠝⡎⠆⡋⡻⣻⢿⣻⢟⣿⣻⢯⡿⣯⡿⣽⣟⣿⢿⣻⣷⣷⣷⣿⣮⠑⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⠌⡌⡣⣳⣹⣪⣾⣽⣽⣯⣿⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠫⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⢜⣮⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⠿⠿⠿⡿⣋⣔⣤⡢⡻⢿⢿⣿⣿⣿⣿⣿⡿⠟⠉⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⠀⠀⠀⠀⠀⢀⣤⡤⣄⣄⣄⣤⣤⣶⣵⣿⣿⣿⣿⣿⡿⠿⠻⠛⠛⠋⠉⠉⠈⡀⠠⣀⣢⣢⣷⣿⣿⣾⡪⡊⠨⡐⠕⢜⢜⢒⢆⢂⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⠀⠀⠀⠀⠀⠃⣿⠇⠀⠀⠀⣠⡤⣌⣌⣍⣉⠉⠙⣿⠇⠀⠀⠀⠀⠀⢀⠔⡡⡢⣿⣿⣿⣿⣿⢿⣿⡿⡣⠀⡪⣸⣼⣜⠔⠡⢱⢱⢡⢄⠀⠀⠀⠀wow⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⠐⠀⠀⠀⠀⢐⣿⠁⠀⠀⠀⠈⠈⠉⠈⠉⠑⠀⢠⣿⣅⣄⣠⣠⣤⣶⣵⣷⣷⣿⣿⣿⣿⠁⠀⠀⢹⣱⣔⣔⢽⡻⠵⠛⠎⢎⠔⡡⡣⡳⡳⡦⡄⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⠀⠀⠀⠀⢀⣠⡿⠀⠀⠀⢄⢔⠤⡀⠀⠀⡰⡰⣺⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣄⣠⣴⣽⣷⣿⢎⠀⠀⠀⠀⠀⠀⢀⣇⣗⡽⣜⡵⡝⡆⡀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⢀⢴⡟⠯⢬⢾⠃⠀⠀so much allocation⣿⣿⣿⣿⡿⠿⠛⠛⠻⣿⣿⣿⣳⢔⣄⣀⡀⡠⡴⣿⣿⣿⣿⣿⣿⣟⣮⣖⢌⢎⣿⣿⣿⣿⣿⣿⣿⣿⣿OMG⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⡀⣀⣁⣅⣀⣀⣻⣿⣿⣑⢔⢈⠌⠂⢷⣫⣖⡮⣕⣿⢥⠛⠿⣦⡀⡉⣟⣿⣿⣿⣿⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣻⠪⠣⡫⡾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⣿⣿⣿⣿⣿⣿⣿⣿⣯⣿⣿⣿⣟⣿⣳⣟⢿⠷⣏⠣⡈⢠⣤⣺⣟⢯⡳⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⡻⡛⣗⠽⡿⡿⣿⣿⣿⣿⣿⢿⢟⢯⣫⣳⠪⠡⠁⡇⢝⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣾⣷⣼⣼⣵⣽⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠈⠊⠂⠁⢈⡻⣪⣺⢼⣞⢮⣷⣿⣿⡿⡮⡣⠡⡑⡐⠅⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⡀⠀⠀⠀⠀⠀⢀⢠⢪⡺⡜⡎⣟⣾⣽⡾⣵⡳⢝⠜⠨⠐⠀⠀⠁⠆⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣻⢽⡕⡽⡸⡱⡑⡕⣜⣼⣯⣷⡯⡯⡻⡪⣪⠢⡁⠊⠀⠀⢀⠜⡨⣺⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⣿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢟⣞⡷⣹⢜⢜⢜⢜⢜⢜⠪⡓⡗⣝⢮⢯⢳⢕⢕⢡⢀⡀⡆⣇⣗⣽⢾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⡷⣟⡯⣷⣻⣻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣳⢕⡁⡃⡃⡁⡁⡂⢅⢢⣱⢼⢼⣪⣗⢗⣝⡮⣪⣦⣾⣾⣽⣷⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⡯⣗⢯⢗⢯⢞⡾⡵⣗⡯⡯⣟⣿⣻⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⢳⡩⡲⡨⡨⡢⣣⣓⣟⢾⢽⣞⡮⣮⣛mallolc/free cometh⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⡇⣗⢝⢎⡗⣝⢎⢯⢺⡺⣝⢵⡳⣳⡻⣽⡺⣽⣻⡻⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢳⡱⣨⢢⡑⡕⡧⣗⡏⣗⡯⣶⢻⢯⣿⣵⣾⣿⣿⣿⣿⣿⣿⡷⡓⠍⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⡇⡇⡏⡮⡺⡸⡱⡹⡪⡪⣪⢣⡫⡺⡜⡮⢮⢳⢕⢯⣫⣳⣵⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢯⣗⢧⢣⡣⣳⢵⢳⢕⣯⣳⣻⡺⡻⡻⣽⣿⣷⣿⣿⣿⣿⢟⢝⢊⢊⢀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⢕⢕⢕⢕⠕⡝⢜⢜⢎⢣wow⢣⢣⠣⡣⠣⡣⡣⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⡕⡎⡮⡪⡞⡗⣝⡯⣯⣗⣯⡷⣿⣻⣷⣽⢽⣿⣿⣿⢿⣮⣯⡧⡂⢀⠀⢯⢿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
// ⠕⡡⠣⡑⢅⠣⡑⢕⢘⠌⠆⡣⢑⠡⠡⠑⠨⠈⠂⠌⡚⡻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢯⡫⣎⢎⢇⢗⢝⢜⢎⢗⢗⢽⡺⡵⡫⡺⣝⣟⣞⣷⢿⡿⣿⣾⣿⡪⠀⢈⢪⢫⢯⡺⣝⢝⡮⣗⢯⡺⣺⢽⢝⡯⣟⢽⡫⡯⡯⡯
// ⠈⠄⠁⡂⠂⠅⠌⠐⠐⠨⠐⠀⠂⠈⠀⠁⠀⠠⢡⠳⢝⢗⢿⣿⣿⣿⣿⣿⣿⠿⠟⠯⡫⡺⡸⡪⡪⡣⡳⡱⡱⢱⢱⢣⢝⢎⢽⢺⢜⠮⣞⢯⣟⡿⣿⣿⣿⠇⠂⠀⢂⠣⠣⠣⡣⡣⡓⡕⡕⡝⡜⡵⡹⡪⠮⡳⡹⡹⡪⢯

mod refr {
    use super::{Index, IsWrite, LockId, Priority, LEN};

    use std::{
        cmp::Ordering,
        collections::{BTreeSet, HashMap, HashSet},
        fmt,
        ops::Range,
        prelude::v1::*,
    };

    #[derive(Default)]
    struct RwLock {
        owners: HashSet<(LockId, IsWrite)>,
        waits: BTreeSet<Wait>,
        next_order: u64,
    }

    #[derive(PartialEq, Eq)]
    struct Wait {
        id: LockId,
        write: IsWrite,
        priority: Priority,
        /// Enforce FIFO ordering
        order: u64,
    }

    impl PartialOrd for Wait {
        fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
            Some(self.cmp(o))
        }
    }

    impl Ord for Wait {
        fn cmp(&self, o: &Self) -> Ordering {
            // (-priority, order)
            o.priority
                .cmp(&self.priority)
                .then(self.order.cmp(&o.order))
        }
    }

    struct Lock {
        range: Range<Index>,
        write: IsWrite,
        pos: Index,
        priority: Priority,
        /// The last copy of `Wait::order`
        order: Option<u64>,
    }

    #[derive(Default)]
    pub struct RwLockSet {
        rwlocks: Vec<RwLock>,
        locks: HashMap<LockId, Lock>,
    }

    impl RwLockSet {
        pub fn new() -> Self {
            Self {
                rwlocks: (0..LEN).map(|_| RwLock::default()).collect(),
                locks: HashMap::new(),
            }
        }

        /// Acquire a lock. Returns whether the lock is complete.
        pub fn lock(
            &mut self,
            id: LockId,
            range: Range<Index>,
            write: IsWrite,
            priority: Priority,
        ) -> bool {
            let lock = Lock {
                range: range.clone(),
                write,
                priority,
                pos: range.start,
                order: None,
            };
            self.locks.insert(id, lock);
            self.resume(id)
        }

        /// Release a lock.
        pub fn unlock(&mut self, id: LockId) {
            let mut lock = self.locks.remove(&id).unwrap();

            if let Some(order) = lock.order.take() {
                let rwl = &mut self.rwlocks[lock.pos];
                assert!(rwl.waits.remove(&Wait {
                    id,
                    write: lock.write,
                    priority: lock.priority,
                    order,
                }));
            }

            while lock.pos > lock.range.start {
                lock.pos -= 1;

                let rwl = &mut self.rwlocks[lock.pos];
                rwl.owners.remove(&(id, lock.write));

                // Check for unblocked pending borrows
                let maybe_unblocked_ids: Vec<_> = rwl.waits.iter().map(|w| w.id).collect();
                for id in maybe_unblocked_ids {
                    self.resume(id);
                }
            }
        }

        pub fn is_complete(&self, id: LockId) -> bool {
            let lock = self.locks.get(&id).expect("non-existent lock");
            lock.pos == lock.range.end
        }

        fn resume(&mut self, id: LockId) -> bool {
            let lock = self.locks.get_mut(&id).unwrap();

            if let Some(order) = lock.order.take() {
                let rwl = &mut self.rwlocks[lock.pos];
                assert!(rwl.waits.remove(&Wait {
                    id,
                    write: lock.write,
                    priority: lock.priority,
                    order,
                }));
            }

            while lock.pos < lock.range.end {
                let rwl = &mut self.rwlocks[lock.pos];
                match lock.write {
                    true => {
                        if !rwl.owners.is_empty() {
                            break;
                        }
                    }
                    false => {
                        if rwl
                            .owners
                            .iter()
                            .next()
                            .map_or(false, |&(_, writing_lock)| writing_lock)
                        {
                            break;
                        }
                    }
                }
                rwl.owners.insert((id, lock.write));
                lock.pos += 1;
            }

            if lock.pos < lock.range.end {
                let rwl = &mut self.rwlocks[lock.pos];
                let order = rwl.next_order;
                rwl.next_order += 1;
                lock.order = Some(order);
                rwl.waits.insert(Wait {
                    id,
                    write: lock.write,
                    priority: lock.priority,
                    order,
                });
            }

            lock.pos == lock.range.end
        }
    }

    impl fmt::Debug for RwLockSet {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let borrow_sym = |is_write: Option<IsWrite>| match is_write {
                None => " ",
                Some(true) => "",
                Some(false) => "",
            };

            // Lock state bitmap
            writeln!(f, "Memory bitmap:")?;
            write!(f, "    ")?;
            for x in (0..LEN).step_by(8) {
                write!(f, "{:<8}", x)?;
            }
            writeln!(f, "{}", LEN)?;

            write!(f, "   |")?;
            for rwlock in self.rwlocks.iter() {
                write!(
                    f,
                    "{}",
                    borrow_sym(rwlock.owners.iter().next().map(|&(_, is_write)| is_write))
                )?;
            }
            writeln!(f, "|")?;

            // Locks
            writeln!(f, "Borrows:")?;
            for (id, lock) in self.locks.iter() {
                write!(f, "{:3}:", id)?;

                for _ in 0..lock.range.start {
                    write!(f, " ")?;
                }
                for _ in lock.range.start..lock.pos {
                    write!(f, "{}", borrow_sym(Some(lock.write)))?;
                }
                for _ in lock.pos..lock.range.end {
                    write!(f, "-")?;
                }
                writeln!(f)?;
            }

            Ok(())
        }
    }
}

// Subject
// --------------------------------------------------------------------------

mod subj {

    use super::super::*;
    use super::{InProgress, Index, IsWrite, LockId, Priority};
    use std::{collections::HashMap, prelude::v1::*};

    #[derive(Debug)]
    struct Lock {
        range: Range<Index>,
        priority: Priority,
        state: LockState,
        complete: bool,
    }

    #[derive(Debug)]
    enum LockState {
        Read(Pin<Box<ReadLockState<Index, Priority, InProgress>>>),
        Write(Pin<Box<WriteLockState<Index, Priority, InProgress>>>),
        TryRead(Pin<Box<TryReadLockState<Index, Priority, InProgress>>>),
        TryWrite(Pin<Box<TryWriteLockState<Index, Priority, InProgress>>>),
    }

    pub struct RwLockSet {
        rwlocks: Pin<Box<RbTreeIntervalRwLockCore<Index, Priority, InProgress>>>,
        locks: HashMap<LockId, Lock>,
    }

    impl RwLockSet {
        pub fn new() -> Self {
            Self {
                rwlocks: Box::pin(RbTreeIntervalRwLockCore::new()),
                locks: HashMap::new(),
            }
        }

        /// Acquire a lock. Returns whether the lock is complete.
        pub fn lock(
            &mut self,
            id: LockId,
            range: Range<Index>,
            write: IsWrite,
            priority: Priority,
            is_try: bool,
        ) -> bool {
            let rwlocks = Pin::as_mut(&mut self.rwlocks);

            let (complete, state) = match (write, is_try) {
                (false, false) => {
                    let mut state = Box::pin(ReadLockState::new());
                    let complete = rwlocks.lock_read(
                        range.clone(),
                        priority,
                        Pin::as_mut(&mut state),
                        TestLockCallback(id),
                    );
                    (complete, LockState::Read(state))
                }
                (true, false) => {
                    let mut state = Box::pin(WriteLockState::new());
                    let complete = rwlocks.lock_write(
                        range.clone(),
                        priority,
                        Pin::as_mut(&mut state),
                        TestLockCallback(id),
                    );
                    (complete, LockState::Write(state))
                }
                (false, true) => {
                    let mut state = Box::pin(TryReadLockState::new());
                    let complete = rwlocks.try_lock_read(range.clone(), Pin::as_mut(&mut state));
                    (complete, LockState::TryRead(state))
                }
                (true, true) => {
                    let mut state = Box::pin(TryWriteLockState::new());
                    let complete = rwlocks.try_lock_write(range.clone(), Pin::as_mut(&mut state));
                    (complete, LockState::TryWrite(state))
                }
            };

            if complete || !is_try {
                // Remember the lock
                self.locks.insert(
                    id,
                    Lock {
                        state,
                        range,
                        priority,
                        complete,
                    },
                );
            }

            complete
        }

        /// Release a lock.
        pub fn unlock(&mut self, id: LockId) {
            let mut lock = self.locks.remove(&id).unwrap();
            let rwlocks = Pin::as_mut(&mut self.rwlocks);

            let callback = TestUnlockCallback(&mut self.locks);

            match &mut lock.state {
                LockState::Read(state) => {
                    rwlocks.unlock_read(Pin::as_mut(state), callback);
                }
                LockState::Write(state) => {
                    rwlocks.unlock_write(Pin::as_mut(state), callback);
                }
                LockState::TryRead(state) => {
                    rwlocks.unlock_try_read(Pin::as_mut(state), callback);
                }
                LockState::TryWrite(state) => {
                    rwlocks.unlock_try_write(Pin::as_mut(state), callback);
                }
            }
        }

        pub fn is_complete(&self, id: LockId) -> bool {
            self.locks.get(&id).expect("non-existent lock").complete
        }

        pub fn validate(&mut self) {
            unsafe {
                rbtree::Node::validate(&mut ReadNodeCallback, &self.rwlocks.reads);
                rbtree::Node::validate(&mut WriteNodeCallback, &self.rwlocks.writes);
                rbtree::Node::validate(&mut PendingNodeCallback, &self.rwlocks.pendings);
            }

            let mut rwlocks = Pin::as_mut(&mut self.rwlocks);

            for (_, lock) in self.locks.iter_mut() {
                let actual_complete = match &mut lock.state {
                    LockState::Read(state) => matches!(
                        Pin::as_mut(&mut rwlocks).inspect_read_mut(Pin::as_mut(state)),
                        crate::core::LockState::Complete
                    ),
                    LockState::Write(state) => matches!(
                        Pin::as_mut(&mut rwlocks).inspect_write_mut(Pin::as_mut(state)),
                        crate::core::LockState::Complete
                    ),
                    LockState::TryRead(_) => true,
                    LockState::TryWrite(_) => true,
                };

                assert_eq!(actual_complete, lock.complete);
            }
        }
    }

    impl Drop for RwLockSet {
        fn drop(&mut self) {
            // Remove borrows in a not-so-subtle way so that this won't abort
            let rwlocks = unsafe { Pin::get_unchecked_mut(Pin::as_mut(&mut self.rwlocks)) };
            rwlocks.reads = None;
            rwlocks.writes = None;
            rwlocks.pendings = None;

            for (_, lock) in self.locks.iter_mut() {
                match &mut lock.state {
                    LockState::Read(state) => {
                        state.inner.get().unwrap().parent.set(None);
                    }
                    LockState::Write(state) => {
                        state.inner.get().unwrap().parent.set(None);
                    }
                    LockState::TryRead(state) => {
                        state.inner.get().unwrap().parent.set(None);
                    }
                    LockState::TryWrite(state) => {
                        state.inner.get().unwrap().parent.set(None);
                    }
                }
            }
        }
    }

    #[derive(Clone, Copy)]
    struct TestLockCallback(LockId);

    impl LockCallback<LockId> for TestLockCallback {
        type Output = bool;

        fn in_progress(self) -> (Self::Output, LockId) {
            (false, self.0)
        }

        fn complete(self) -> Self::Output {
            true
        }
    }

    struct TestUnlockCallback<'a>(&'a mut HashMap<LockId, Lock>);

    impl UnlockCallback<LockId> for TestUnlockCallback<'_> {
        fn complete(&mut self, in_progress: LockId) {
            log::debug!("... lock #{} is now complete", in_progress);

            let lock = self.0.get_mut(&in_progress).unwrap();
            assert_eq!(lock.complete, false);
            lock.complete = true;
        }
    }
}

// Tests
// --------------------------------------------------------------------------

type LockId = usize;

#[quickcheck]
fn qc_rbtree_interval_rw_lock_core(cmds: Vec<u8>) {
    let mut cmds = cmds.into_iter();
    let mut next_lock_id = 1;

    let mut locks: Vec<LockId> = Vec::new();

    log::info!("cmds = {:?}", cmds);

    let mut subject_rwlock = subj::RwLockSet::new();
    let mut reference_rwlock = refr::RwLockSet::new();

    (|| -> Option<()> {
        while let Some(cmd) = cmds.next() {
            match cmd % 2 {
                0 if !locks.is_empty() => {
                    // Choose the lock to unlock
                    let i = cmds.next()? as usize % locks.len();
                    let id = locks.swap_remove(i);

                    log::debug!("Unlocking lock #{:?}", id);

                    // `subject_rwlock`
                    subject_rwlock.unlock(id);

                    // `reference_rwlock`
                    reference_rwlock.unlock(id);
                }

                1 if locks.len() < 64 => {
                    let range = (cmds.next()? as usize % LEN)..(cmds.next()? as usize % LEN);
                    let range = range.start.min(range.end)..range.start.max(range.end);
                    if range.start == range.end {
                        continue;
                    }

                    let priority = cmds.next()? as Priority;

                    let lock_id = next_lock_id;
                    next_lock_id += 1;

                    let lock_ty = (cmd / 2 % 4) as usize;
                    let lock_ty_name = ["Read", "Write", "TryRead", "TryWrite"][lock_ty];
                    let is_write = (lock_ty % 2) == 1;
                    let is_try = lock_ty >= 2;

                    log::debug!(
                        "Locking {:?} as #{}",
                        (&range, priority, lock_ty_name),
                        lock_id
                    );

                    // `subject_rwlock`
                    let subject_complete =
                        subject_rwlock.lock(lock_id, range.clone(), is_write, priority, is_try);

                    if !subject_complete {
                        log::debug!("... it did not complete");
                    }

                    // `reference_rwlock`
                    let reference_complete =
                        reference_rwlock.lock(lock_id, range.clone(), is_write, priority);

                    // Compare the results
                    assert_eq!(subject_complete, reference_complete);

                    // Lock failure?
                    if is_try && !subject_complete {
                        reference_rwlock.unlock(lock_id);
                        continue;
                    }

                    // Remember the lock
                    locks.push(lock_id);
                }

                _ => {}
            }

            // Validate trees after each command completion
            subject_rwlock.validate();

            // Compare completeness
            for &id in locks.iter() {
                let subject_complete = subject_rwlock.is_complete(id);
                let reference_complete = reference_rwlock.is_complete(id);
                assert_eq!(
                    subject_complete, reference_complete,
                    "lock #{} is completed in one but not in the other",
                    id
                );
            }

            // Dump the borrow state
            log::trace!("{:?}", reference_rwlock);
        }

        // Release completed locks. This will unblock and complete other locks
        // in turn. After repeating this step, if there are still incomplete
        // locks, that means our interval lock is prone to deadlocks.
        while !locks.is_empty() {
            let i = locks
                .iter()
                .cloned()
                .position(|id| subject_rwlock.is_complete(id));

            if let Some(i) = i {
                let id = locks.swap_remove(i);
                subject_rwlock.unlock(id);
            } else {
                panic!("deadlock");
            }
        }

        None
    })();
}

#[quickcheck]
fn qc_waitlist_is_fifo(write1: IsWrite, write2: IsWrite) {
    log::info!("{:?}", (write1, write2));

    let mut subject_rwlock = subj::RwLockSet::new();
    assert!(subject_rwlock.lock(1, 0..4, true, 0, true));
    assert!(!subject_rwlock.lock(2, 0..3, write1, 0, false));
    assert!(!subject_rwlock.lock(3, 0..2, write2, 0, false));

    // Lock #2 and #3 are blocked at index 0

    subject_rwlock.unlock(1);

    // Now they are unblocked. However, lock #2 blocked first, so it will
    // complete first. This means index 2 is still locked for reading or
    // writing.

    assert!(!subject_rwlock.lock(4, 2..3, true, 0, true));
}

#[test]
fn unblock_multiple() {
    let mut subject_rwlock = subj::RwLockSet::new();
    assert!(subject_rwlock.lock(1, 0..1, true, 0, true));
    assert!(!subject_rwlock.lock(2, 0..4, false, 0, false));
    assert!(!subject_rwlock.lock(3, 0..5, false, 0, false));

    // Lock #2 and #3 (read) are blocked at index 0

    subject_rwlock.unlock(1);

    // Now they are unblocked.
    assert!(subject_rwlock.is_complete(2));
    assert!(subject_rwlock.is_complete(3));
}