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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
//! Provides specialized readers-writer locks for borrowing subslices efficiently.
use core::{
    fmt,
    future::Future,
    mem,
    ops::{Deref, DerefMut, Range},
    pin::Pin,
    ptr::NonNull,
    task::{Context, Poll},
};
use futures::{future::FusedFuture, ready};
use stable_deref_trait::StableDeref;

use crate::raw::{self, RawAsyncIntervalRwLock, RawBlockingIntervalRwLock, RawIntervalRwLock};

#[cfg(test)]
mod tests;

// Lock guards associated with state data
// ----------------------------------------------------------------------------

if_alloc! {
    use alloc::boxed::Box;
    use crate::utils::PinDerefMut;

    /// Associates a lock guard with state data.
    ///
    /// The `*_boxed` method family wraps a lock guard with this type instead of
    /// having their own lock guard types. While this is less efficient (because
    /// of an extra pointer to `State`) and requires lifetime transmutation,
    /// this approach lets us minimize code duplication.
    #[pin_project::pin_project]
    struct WithState<LockGuard, State> {
        /// `guard` must precede `state` because `guard` might include a
        /// reference to `state`.
        guard: Option<LockGuard>,
        #[pin]
        state: State,
        /// `!Unpin` because `guard` might reference `state`.
        _phantom: core::marker::PhantomPinned,
    }

    impl<LockGuard, State: Default> Default for WithState<LockGuard, State> {
        #[inline]
        fn default() -> Self {
            Self {
                guard: None,
                state: State::default(),
                _phantom: core::marker::PhantomPinned,
            }
        }
    }

    impl<LockGuard: Deref, State> Deref for WithState<LockGuard, State> {
        type Target = LockGuard::Target;

        #[inline]
        fn deref(&self) -> &Self::Target {
            self.guard.as_ref().unwrap()
        }
    }

    impl<LockGuard: DerefMut, State> PinDerefMut for WithState<LockGuard, State> {
        #[inline]
        fn pin_deref_mut(self: Pin<&mut Self>) -> &mut Self::Target {
            self.project().guard.as_mut().unwrap()
        }
    }

    /// Erase the pinned mutable reference's lifetime.
    ///
    /// This is used to create a self-referential object of type [`WithState`],
    #[inline]
    unsafe fn transmute_lifetime_mut<'a, T: ?Sized>(x: Pin<&mut T>) -> Pin<&'a mut T> {
        unsafe { Pin::new_unchecked(&mut *( x.get_unchecked_mut() as *mut T)) }
    }
}

// `SliceIntervalRwLock` and its methods
// ----------------------------------------------------------------------------

/// A specialized readers-writer lock for borrowing subslices of `Container:
/// DerefMut<Target = [Element]>`.
///
/// # Locking Methods
///
/// | Category         | Read           | Write           | Read (boxed¹)        | Write (boxed¹)        |
/// | ---------------- | -------------- | --------------- | -------------------- | --------------------- |
/// | Fallible         | [`try_read`]   | [`try_write`]   | [`try_read_boxed`]   | [`try_write_boxed`]   |
/// | [Blocking]       | [`read`]       | [`write`]       | [`read_boxed`]       | [`write_boxed`]       |
/// | [`Future`-based] | [`async_read`] | [`async_write`] | [`async_read_boxed`] | [`async_write_boxed`] |
///
/// ¹ The boxed variation dynamically allocates a storage to store the borrow
/// data and bundles it in the created RAII guard.
///
/// [Blocking]: #blocking-lock-operations
/// [`Future`-based]: #future-based-lock-operations
/// [`try_read`]: Self::try_read
/// [`try_write`]: Self::try_write
/// [`try_read_boxed`]: Self::try_read_boxed
/// [`try_write_boxed`]: Self::try_write_boxed
/// [`read`]: Self::read
/// [`write`]: Self::write
/// [`read_boxed`]: Self::read_boxed
/// [`write_boxed`]: Self::write_boxed
/// [`async_read`]: Self::async_read
/// [`async_write`]: Self::async_write
/// [`async_read_boxed`]: Self::async_read_boxed
/// [`async_write_boxed`]: Self::async_write_boxed
#[pin_project::pin_project]
pub struct SliceIntervalRwLock<Container, Element, RawLock> {
    container: Container,
    #[pin]
    raw: RawLock,
    /// A pointer to the elements, acquired ahead-of-time by `deref_mut`.
    /// This is guaranteed to be up-to-date because of `Container: StableDeref`.
    ptr: NonNull<[Element]>,
}

// Safety: `ptr` is just a cached value of `container.as_mut_ptr()` and
//		   therefore can be ignored when determining this type's thread safety.
unsafe impl<Container: Send, RawLock: Send, Element: Send> Send
    for SliceIntervalRwLock<Container, Element, RawLock>
{
}

unsafe impl<Container: Sync, RawLock: Sync, Element: Send + Sync> Sync
    for SliceIntervalRwLock<Container, Element, RawLock>
{
}

impl<Container, Element, RawLock> SliceIntervalRwLock<Container, Element, RawLock>
where
    Container: Deref<Target = [Element]> + DerefMut + StableDeref,
    RawLock: RawIntervalRwLock<Index = usize>,
{
    #[inline]
    pub fn new(mut container: Container) -> Self {
        Self {
            ptr: NonNull::from(&mut *container),
            container,
            raw: RawLock::INIT,
        }
    }

    /// Replace the contained `Container` with another one, returning the old
    /// one.
    ///
    /// # Panics
    ///
    /// This method will panic if `Container::deref_mut` panics.
    #[inline]
    pub fn replace_container(self: Pin<&mut Self>, mut container: Container) -> Container {
        let this = self.project();

        // `deref_mut` can panic, hence we must do it before updating our fields
        let ptr = NonNull::from(&mut *container);
        let old_container = mem::replace(this.container, container);
        *this.ptr = ptr;

        old_container
    }

    /// Replace the contained `Container` with [`Default::default`], returning
    /// the old one.
    ///
    /// # Panics
    ///
    /// This method will panic if `Container::deref_mut` panics.
    #[inline]
    pub fn take_container(self: Pin<&mut Self>) -> Container
    where
        Container: Default,
    {
        self.replace_container(Container::default())
    }

    /// Update the contained `Container` with the provided closure.
    ///
    /// # Panics
    ///
    /// This method will propagate any panics caused by the closure. This method
    /// will **abort** the program if `Container::deref_mut` panics.
    ///
    /// # Example
    ///
    /// ```rust
    /// use interlock::hl::slice::SyncRbTreeVecIntervalRwLock;
    ///
    /// let mut rwl = Box::pin(SyncRbTreeVecIntervalRwLock::new(vec![42u8; 2]));
    ///
    /// // Resize the inner `Vec`
    /// rwl.as_mut().update_container(|vec| vec.resize(64, 56u8));
    ///
    /// let guard = rwl.as_ref().read_boxed(0..4, ());
    /// assert_eq!(guard[..], [42, 42, 56, 56]);
    /// ```
    ///
    #[inline]
    pub fn update_container<R>(
        self: Pin<&mut Self>,
        updater: impl FnOnce(&mut Container) -> R,
    ) -> R {
        struct Guard<'a, Container: DerefMut>(
            &'a mut Container,
            &'a mut NonNull<Container::Target>,
        );
        let this = self.project();
        let guard = Guard(this.container, this.ptr);

        // Call the provided closure
        let output = updater(guard.0);

        // Ensure `this.ptr` is up-to-date, whether `updater` panics or not
        impl<Container: DerefMut> Drop for Guard<'_, Container> {
            fn drop(&mut self) {
                *self.1 = NonNull::from(&mut **self.0);
            }
        }

        output
    }

    /// Get the number of elements in the underlying slice.
    #[inline]
    pub fn len(&self) -> usize {
        self.ptr.len()
    }

    /// Get a flag indicating whether the underlying slice has no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get a raw pointer to the underlying slice.
    #[inline]
    pub fn as_ptr(&self) -> *mut [Element] {
        self.ptr.as_ptr()
    }

    /// Get a raw pointer to the underlying slice.
    #[inline]
    pub fn as_non_null_ptr(&self) -> NonNull<[Element]> {
        self.ptr
    }

    /// Return a mutable reference to the underlying slice.
    #[inline]
    pub fn get_mut(self: Pin<&mut Self>) -> &mut [Element] {
        // Safety: `self.ptr`'s value is literally `&mut *self.container`, which
        // should be still true because of `Container: StableDeref`.
        // Nevertheless we are using the cached value in case `deref_mut` does
        // something nasty to the memory model.
        unsafe { self.project().ptr.as_mut() }
    }

    /// Get a slice pointer to subelements.
    #[inline]
    fn slice(&self, range: Range<usize>) -> NonNull<[Element]> {
        let ptr = self.ptr;
        assert!(
            range.start <= range.end && range.end <= ptr.len(),
            "out of bounds"
        );

        // Safety: We just checked that `range` is in-bounds
        unsafe { ptr.get_unchecked_mut(range) }
    }

    /// Attempt to acquire a reader lock on the specified range.
    ///
    /// # Example
    ///
    /// ```rust
    /// use interlock::{hl::slice::SyncRbTreeVecIntervalRwLock, state};
    ///
    /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::<_, ()>::new(vec![42u8; 64]));
    ///
    /// // The borrow state must be stored in a pinned place, which
    /// // will be mutably borrowed by the lock guard
    /// state!(let mut state);
    ///
    /// // Attempt to lock the range
    /// let guard = vec.as_ref().try_read(0..4, state).unwrap();
    /// assert_eq!(guard[..], [42u8; 4][..]);
    ///
    /// // (Optional) Explicitly unlock the range by dropping the lock guard
    /// drop(guard);
    /// ```
    pub fn try_read<'a>(
        self: Pin<&'a Self>,
        range: Range<usize>,
        mut lock_state: Pin<&'a mut RawLock::TryReadLockState>,
    ) -> Result<TryReadLockGuard<'a, Element, RawLock, RawLock::TryReadLockState>, TryLockError>
    {
        let this = self.project_ref();
        let ptr = self.slice(range.clone()); // may panic
        if this.raw.try_lock_read(range, Pin::as_mut(&mut lock_state)) {
            Ok(TryReadLockGuard {
                lock_state,
                raw: this.raw,
                ptr,
            })
        } else {
            Err(TryLockError::WouldBlock)
        }
    }

    /// Attempt to acquire a writer lock on the specified range.
    ///
    /// # Example
    ///
    /// ```rust
    /// use interlock::{hl::slice::SyncRbTreeVecIntervalRwLock, utils::PinDerefMut, state};
    /// use std::pin::Pin;
    ///
    /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::<_, ()>::new(vec![42u8; 64]));
    ///
    /// // The borrow state must be stored in a pinned place, which
    /// // will be mutably borrowed by the lock guard
    /// state!(let mut state);
    ///
    /// // Attempt to lock the range
    /// let mut guard = vec.as_ref().try_write(0..4, state).unwrap();
    /// guard.copy_from_slice(&[56; 4]);
    ///
    /// // (Optional) Explicitly unlock the range by dropping the lock guard
    /// drop(guard);
    /// ```
    pub fn try_write<'a>(
        self: Pin<&'a Self>,
        range: Range<usize>,
        mut lock_state: Pin<&'a mut RawLock::TryWriteLockState>,
    ) -> Result<TryWriteLockGuard<'a, Element, RawLock, RawLock::TryWriteLockState>, TryLockError>
    {
        let this = self.project_ref();
        let ptr = self.slice(range.clone()); // may panic
        if this.raw.try_lock_write(range, Pin::as_mut(&mut lock_state)) {
            Ok(TryWriteLockGuard {
                lock_state,
                raw: this.raw,
                ptr,
            })
        } else {
            Err(TryLockError::WouldBlock)
        }
    }

    if_alloc! {
        #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))]
        /// The variant of [`Self::try_read`] that dynamically allocates a
        /// storage for borrow state data.
        ///
        /// # Example
        ///
        /// ```rust
        /// use interlock::hl::slice::SyncRbTreeVecIntervalRwLock;
        ///
        /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::<_, ()>::new(vec![42u8; 64]));
        /// let vec = vec.as_ref();
        ///
        /// let guard = vec.try_read_boxed(0..4).unwrap();
        /// assert_eq!(guard[..], [42u8; 4][..]);
        /// ```
        pub fn try_read_boxed(
            self: Pin<&Self>,
            range: Range<usize>,
        ) -> Result<Pin<Box<impl Deref<Target = [Element]> + '_>>, TryLockError>
        {
            let mut guard_with_state = Box::pin(WithState::default());
            {
                let guard_with_state = WithState::project(Pin::as_mut(&mut guard_with_state));
                let state = unsafe { transmute_lifetime_mut(guard_with_state.state) };
                *guard_with_state.guard = Some(self.try_read(range, state)?);
            }
            Ok(guard_with_state)
        }

        #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))]
        /// The variant of [`Self::try_write`] that dynamically allocates a
        /// storage for borrow state data.
        ///
        /// # Example
        ///
        /// ```rust
        /// use interlock::{hl::slice::SyncRbTreeVecIntervalRwLock, utils::PinDerefMut};
        /// use std::pin::Pin;
        ///
        /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::<_, ()>::new(vec![42u8; 64]));
        /// let vec = vec.as_ref();
        ///
        /// let mut guard = vec.try_write_boxed(0..4).unwrap();
        /// Pin::as_mut(&mut guard).pin_deref_mut().copy_from_slice(&[56; 4]);
        /// ```
        pub fn try_write_boxed(
            self: Pin<&Self>,
            range: Range<usize>,
        ) -> Result<Pin<Box<impl PinDerefMut<Target = [Element]> + '_>>, TryLockError>
        {
            let mut guard_with_state = Box::pin(WithState::default());
            {
                let guard_with_state = WithState::project(Pin::as_mut(&mut guard_with_state));
                let state = unsafe { transmute_lifetime_mut(guard_with_state.state) };
                *guard_with_state.guard = Some(self.try_write(range, state)?);
            }
            Ok(guard_with_state)
        }
    }
}

/// Indicates a failure of a non-blocking lock operation.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
pub enum TryLockError {
    /// The lock could not be acquired at this time because the operation would
    /// otherwise block.
    #[cfg_attr(
        feature = "std",
        error("lock failed because the operation would block")
    )]
    WouldBlock,
}

/// # Blocking Lock Operations
///
/// These methods require `RawLock: `[`RawBlockingIntervalRwLock`].
impl<Container, Element, RawLock> SliceIntervalRwLock<Container, Element, RawLock>
where
    Container: Deref<Target = [Element]> + DerefMut + StableDeref,
    RawLock: RawIntervalRwLock<Index = usize> + RawBlockingIntervalRwLock,
{
    /// Acquire a reader lock on the specified range, blocking the current
    /// thread until it can be acquired.
    ///
    /// # Example
    ///
    /// ```rust
    /// use interlock::{hl::slice::SyncRbTreeVecIntervalRwLock, state};
    ///
    /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::new(vec![42u8; 64]));
    ///
    /// state!(let mut state);
    ///
    /// let guard = vec.as_ref().read(0..4, (), state);
    /// assert_eq!(guard[..], [42u8; 4][..]);
    /// ```
    pub fn read<'a>(
        self: Pin<&'a Self>,
        range: Range<usize>,
        priority: RawLock::Priority,
        mut lock_state: Pin<&'a mut RawLock::ReadLockState>,
    ) -> ReadLockGuard<'a, Element, RawLock, RawLock::ReadLockState> {
        let this = self.project_ref();
        let ptr = self.slice(range.clone()); // may panic
        this.raw
            .lock_read(range, priority, Pin::as_mut(&mut lock_state));
        ReadLockGuard {
            lock_state,
            raw: this.raw,
            ptr,
        }
    }

    /// Acquire a writer lock on the specified range, blocking the current
    /// thread until it can be acquired.
    ///
    /// # Example
    ///
    /// ```rust
    /// use interlock::{hl::slice::SyncRbTreeVecIntervalRwLock, utils::PinDerefMut, state};
    /// use std::pin::Pin;
    ///
    /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::new(vec![42u8; 64]));
    ///
    /// state!(let mut state);
    ///
    /// let mut guard = vec.as_ref().write(0..4, (), state);
    /// guard.copy_from_slice(&[56; 4]);
    /// ```
    pub fn write<'a>(
        self: Pin<&'a Self>,
        range: Range<usize>,
        priority: RawLock::Priority,
        mut lock_state: Pin<&'a mut RawLock::WriteLockState>,
    ) -> WriteLockGuard<'a, Element, RawLock, RawLock::WriteLockState> {
        let this = self.project_ref();
        let ptr = self.slice(range.clone()); // may panic
        this.raw
            .lock_write(range, priority, Pin::as_mut(&mut lock_state));
        WriteLockGuard {
            lock_state,
            raw: this.raw,
            ptr,
        }
    }

    if_alloc! {
        #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))]
        /// The variant of [`Self::read`] that dynamically allocates a
        /// storage for borrow state data.
        ///
        /// # Example
        ///
        /// ```rust
        /// use interlock::hl::slice::SyncRbTreeVecIntervalRwLock;
        ///
        /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::new(vec![42u8; 64]));
        /// let vec = vec.as_ref();
        ///
        /// let guard = vec.read_boxed(0..4, ());
        /// assert_eq!(guard[..], [42u8; 4][..]);
        /// ```
        pub fn read_boxed(
            self: Pin<&Self>,
            range: Range<usize>,
            priority: RawLock::Priority,
        ) -> Pin<Box<impl Deref<Target = [Element]> + '_>>
        {
            let mut guard_with_state = Box::pin(WithState::default());
            {
                let guard_with_state = WithState::project(Pin::as_mut(&mut guard_with_state));
                let state = unsafe { transmute_lifetime_mut(guard_with_state.state) };
                *guard_with_state.guard = Some(self.read(range, priority, state));
            }
            guard_with_state
        }

        #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))]
        /// The variant of [`Self::write`] that dynamically allocates a
        /// storage for borrow state data.
        ///
        /// # Example
        ///
        /// ```rust
        /// use interlock::{hl::slice::SyncRbTreeVecIntervalRwLock, utils::PinDerefMut};
        /// use std::pin::Pin;
        ///
        /// let vec = Box::pin(SyncRbTreeVecIntervalRwLock::new(vec![42u8; 64]));
        /// let vec = vec.as_ref();
        ///
        /// let mut guard = vec.write_boxed(0..4, ());
        /// Pin::as_mut(&mut guard).pin_deref_mut().copy_from_slice(&[56; 4]);
        /// ```
        pub fn write_boxed(
            self: Pin<&Self>,
            range: Range<usize>,
            priority: RawLock::Priority,
        ) -> Pin<Box<impl PinDerefMut<Target = [Element]> + '_>>
        {
            let mut guard_with_state = Box::pin(WithState::default());
            {
                let guard_with_state = WithState::project(Pin::as_mut(&mut guard_with_state));
                let state = unsafe { transmute_lifetime_mut(guard_with_state.state) };
                *guard_with_state.guard = Some(self.write(range, priority, state));
            }
            guard_with_state
        }
    }
}

/// # `Future`-based Lock Operations
///
/// These methods require `RawLock: `[`RawAsyncIntervalRwLock`].
impl<Container, Element, RawLock> SliceIntervalRwLock<Container, Element, RawLock>
where
    Container: Deref<Target = [Element]> + DerefMut + StableDeref,
    RawLock: RawIntervalRwLock<Index = usize> + RawAsyncIntervalRwLock,
{
    /// Acquire a reader lock on the specified range asynchronously.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[tokio::main] async fn main() {
    /// use interlock::{hl::slice::AsyncRbTreeVecIntervalRwLock, state};
    /// use parking_lot::RawMutex;
    ///
    /// let vec = Box::pin(AsyncRbTreeVecIntervalRwLock::<RawMutex, _>::new(vec![42u8; 64]));
    ///
    /// state!(let mut state);
    ///
    /// let guard = vec.as_ref().async_read(0..4, (), state).await;
    /// assert_eq!(guard[..], [42u8; 4][..]);
    /// # }
    /// ```
    pub fn async_read<'a>(
        self: Pin<&'a Self>,
        range: Range<usize>,
        priority: RawLock::Priority,
        mut lock_state: Pin<&'a mut RawLock::ReadLockState>,
    ) -> ReadLockFuture<'a, Element, RawLock, RawLock::ReadLockState> {
        let this = self.project_ref();
        let ptr = self.slice(range.clone()); // may panic
        this.raw
            .start_lock_read(range, priority, Pin::as_mut(&mut lock_state));
        ReadLockFuture {
            guard: Some(AsyncReadLockGuard {
                lock_state,
                raw: this.raw,
                ptr,
            }),
        }
    }

    /// Acquire a writer lock on the specified range asynchronously.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[tokio::main] async fn main() {
    /// use interlock::{hl::slice::AsyncRbTreeVecIntervalRwLock, utils::PinDerefMut, state};
    /// use parking_lot::RawMutex;
    /// use std::pin::Pin;
    ///
    /// let vec = Box::pin(AsyncRbTreeVecIntervalRwLock::<RawMutex, _>::new(vec![42u8; 64]));
    ///
    /// state!(let mut state);
    ///
    /// let mut guard = vec.as_ref().async_write(0..4, (), state).await;
    /// guard.copy_from_slice(&[56; 4]);
    /// # }
    /// ```
    pub fn async_write<'a>(
        self: Pin<&'a Self>,
        range: Range<usize>,
        priority: RawLock::Priority,
        mut lock_state: Pin<&'a mut RawLock::WriteLockState>,
    ) -> WriteLockFuture<'a, Element, RawLock, RawLock::WriteLockState> {
        let this = self.project_ref();
        let ptr = self.slice(range.clone()); // may panic
        this.raw
            .start_lock_write(range, priority, Pin::as_mut(&mut lock_state));
        WriteLockFuture {
            guard: Some(AsyncWriteLockGuard {
                lock_state,
                raw: this.raw,
                ptr,
            }),
        }
    }

    if_alloc! {
        #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))]
        /// The variant of [`Self::async_read`] that dynamically allocates a
        /// storage for borrow state data.
        ///
        /// # Example
        ///
        /// ```rust
        /// # #[tokio::main] async fn main() {
        /// use interlock::hl::slice::AsyncRbTreeVecIntervalRwLock;
        /// use parking_lot::RawMutex;
        ///
        /// let vec = Box::pin(AsyncRbTreeVecIntervalRwLock::<RawMutex, _>::new(vec![42u8; 64]));
        /// let vec = vec.as_ref();
        ///
        /// let guard = vec.async_read_boxed(0..4, ()).await;
        /// assert_eq!(guard[..], [42u8; 4][..]);
        /// # }
        /// ```
        pub async fn async_read_boxed(
            self: Pin<&Self>,
            range: Range<usize>,
            priority: RawLock::Priority,
        ) -> Pin<Box<impl Deref<Target = [Element]> + '_>>
        {
            let mut guard_with_state = Box::pin(WithState::default());
            {
                let guard_with_state = WithState::project(Pin::as_mut(&mut guard_with_state));
                let state = unsafe { transmute_lifetime_mut(guard_with_state.state) };
                *guard_with_state.guard = Some(self.async_read(range, priority, state).await);
            }
            guard_with_state
        }

        #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))]
        /// The variant of [`Self::async_write`] that dynamically allocates a
        /// storage for borrow state data.
        ///
        /// # Example
        ///
        /// ```rust
        /// # #[tokio::main] async fn main() {
        /// use interlock::{hl::slice::AsyncRbTreeVecIntervalRwLock, utils::PinDerefMut};
        /// use parking_lot::RawMutex;
        /// use std::pin::Pin;
        ///
        /// let vec = Box::pin(AsyncRbTreeVecIntervalRwLock::<RawMutex, _>::new(vec![42u8; 64]));
        /// let vec = vec.as_ref();
        ///
        /// let mut guard = vec.async_write_boxed(0..4, ()).await;
        /// Pin::as_mut(&mut guard).pin_deref_mut().copy_from_slice(&[56; 4]);
        /// # }
        /// ```
        pub async fn async_write_boxed(
            self: Pin<&Self>,
            range: Range<usize>,
            priority: RawLock::Priority,
        ) -> Pin<Box<impl PinDerefMut<Target = [Element]> + '_>>
        {
            let mut guard_with_state = Box::pin(WithState::default());
            {
                let guard_with_state = WithState::project(Pin::as_mut(&mut guard_with_state));
                let state = unsafe { transmute_lifetime_mut(guard_with_state.state) };
                *guard_with_state.guard = Some(self.async_write(range, priority, state).await);
            }
            guard_with_state
        }
    }
}

macro_rules! define_lock_future {
	(
		$( #[$meta:meta] )*
		pub struct $ident:ident<'_, Element, RawLock, LockState>
		where
			RawLock: [$($raw_lock_bounds:tt)*]
		{
			guard: $guard_ty:ident,
		}

		impl Future for _ { => $poll_method:ident }
	) => {
		$( #[$meta] )*
		///
		/// # Notes
		///
		/// It's probably a bad idea to [`forget`] a value of this type. The
		/// underlying `LockState` will remain associated with a pending lock
		/// (and dropping it will abort the program), and you can't dissociate
		/// it.
		///
		/// [`forget`]: core::mem::forget
		pub struct $ident<'a, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
			/// Stores a lock guard representing the pending lock, which will
			/// be returned by `poll` when the lock completes.
			guard: Option<$guard_ty<'a, Element, RawLock, LockState>>,
		}

		impl<'a, Element, RawLock, LockState> Future
			for $ident<'a, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
			type Output = $guard_ty<'a, Element, RawLock, LockState>;

			fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
				let this = Pin::into_inner(self);
				let guard = this.guard.as_mut().expect("future polled after completion");
				ready!(guard.raw.$poll_method(Pin::as_mut(&mut guard.lock_state), cx));

				Poll::Ready(this.guard.take().unwrap())
			}
		}

		impl<'a, Element, RawLock, LockState> FusedFuture
			for $ident<'a, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
			#[inline]
    		fn is_terminated(&self) -> bool {
    			self.guard.is_none()
    		}
		}
	};
}

define_lock_future! {
    /// A future representing a pending reader lock of [`SliceIntervalRwLock`],
    /// which will resolve when the lock has been successfully acquired.
    pub struct ReadLockFuture<'_, Element, RawLock, LockState>
    where
        RawLock: [RawAsyncIntervalRwLock<Index = usize, ReadLockState = LockState>]
    {
        guard: AsyncReadLockGuard,
    }

    impl Future for _ { => poll_lock_read }
}

define_lock_future! {
    /// A future representing a pending writer lock of [`SliceIntervalRwLock`],
    /// which will resolve when the lock has been successfully acquired.
    pub struct WriteLockFuture<'_, Element, RawLock, LockState>
    where
        RawLock: [RawAsyncIntervalRwLock<Index = usize, WriteLockState = LockState>]
    {
        guard: AsyncWriteLockGuard,
    }

    impl Future for _ { => poll_lock_write }
}

macro_rules! define_lock_guard {
	(
		$( #[$meta:meta] )*
		pub struct $ident:ident<'_, Element, RawLock, LockState>
		where
			RawLock: [$($raw_lock_bounds:tt)*];
		impl $deref:tt for _;
		impl Drop for _ { => $unlock_method:ident }
	) => {
		$( #[$meta] )*
		///
		/// # Notes
		///
		/// It's probably a bad idea to [`forget`] a value of this type. The
		/// underlying `LockState` will remain associated with a lock (and
		/// dropping it will abort the program), and you can't dissociate it.
		///
		/// [`forget`]: core::mem::forget
		pub struct $ident<'a, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
			lock_state: Pin<&'a mut LockState>,
			raw: Pin<&'a RawLock>,
			ptr: NonNull<[Element]>,
		}

		unsafe impl<Element: Send + Sync, RawLock: Sync, LockState: Send> Send
			for $ident<'_, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
		}

		unsafe impl<Element: Send + Sync, RawLock: Sync, LockState: Sync> Sync
			for $ident<'_, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
		}

		// impl `Deref` and optionally `DerefMut`
		define_lock_guard!(@deref $deref [$($raw_lock_bounds)*] $ident);

		impl<Element, RawLock, LockState> fmt::Debug for $ident<'_, Element, RawLock, LockState>
		where
			Element: fmt::Debug,
			RawLock: $($raw_lock_bounds)*,
		{
			fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				(**self).fmt(f)
			}
		}

		impl<Element, RawLock, LockState> Drop for $ident<'_, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
			#[inline]
			fn drop(&mut self) {
				self.raw.$unlock_method(Pin::as_mut(&mut self.lock_state));
			}
		}
	};

	(@deref DerefMut [$($raw_lock_bounds:tt)*] $ident:ident) => {
		impl<Element, RawLock, LockState> DerefMut for $ident<'_, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
			#[inline]
			fn deref_mut(&mut self) -> &mut Self::Target {
				// Safety: Upheld by a runtime check
				unsafe { self.ptr.as_mut() }
			}
		}

		define_lock_guard!(@deref Deref [$($raw_lock_bounds)*] $ident);
	};

	(@deref Deref [$($raw_lock_bounds:tt)*] $ident:ident) => {
		impl<Element, RawLock, LockState> Deref for $ident<'_, Element, RawLock, LockState>
		where
			RawLock: $($raw_lock_bounds)*,
		{
			type Target = [Element];

			#[inline]
			fn deref(&self) -> &Self::Target {
				// Safety: Upheld by a runtime check
				unsafe { self.ptr.as_ref() }
			}
		}
	};
}

define_lock_guard! {
    /// [`SliceIntervalRwLock`]'s RAII lock guard for a non-blocking reader lock.
    pub struct TryReadLockGuard<'_, Element, RawLock, LockState>
    where
        RawLock: [RawIntervalRwLock<Index = usize, TryReadLockState = LockState>];
    impl Deref for _;
    impl Drop for _ { => unlock_try_read }
}

define_lock_guard! {
    /// [`SliceIntervalRwLock`]'s RAII lock guard for a non-blocking writing lock.
    pub struct TryWriteLockGuard<'_, Element, RawLock, LockState>
    where
        RawLock: [RawIntervalRwLock<Index = usize, TryWriteLockState = LockState>];
    impl DerefMut for _;
    impl Drop for _ { => unlock_try_write }
}

define_lock_guard! {
    /// [`SliceIntervalRwLock`]'s RAII lock guard for a blocking reader lock.
    pub struct ReadLockGuard<'_, Element, RawLock, LockState>
    where
        RawLock: [RawBlockingIntervalRwLock<Index = usize, ReadLockState = LockState>];
    impl Deref for _;
    impl Drop for _ { => unlock_read }
}

define_lock_guard! {
    /// [`SliceIntervalRwLock`]'s RAII lock guard for a blocking writing lock.
    pub struct WriteLockGuard<'_, Element, RawLock, LockState>
    where
        RawLock: [RawBlockingIntervalRwLock<Index = usize, WriteLockState = LockState>];
    impl DerefMut for _;
    impl Drop for _ { => unlock_write }
}

define_lock_guard! {
    /// [`SliceIntervalRwLock`]'s RAII lock guard for a `Future`-based reader
    /// lock.
    pub struct AsyncReadLockGuard<'_, Element, RawLock, LockState>
    where
        RawLock: [RawAsyncIntervalRwLock<Index = usize, ReadLockState = LockState>];
    impl Deref for _;
    impl Drop for _ { => unlock_read }
}

define_lock_guard! {
    /// [`SliceIntervalRwLock`]'s RAII lock guard for a `Future`-based writer
    /// lock.
    pub struct AsyncWriteLockGuard<'_, Element, RawLock, LockState>
    where
        RawLock: [RawAsyncIntervalRwLock<Index = usize, WriteLockState = LockState>];
    impl DerefMut for _;
    impl Drop for _ { => unlock_write }
}

// Utility trait to extract an element type
// ----------------------------------------------------------------------------

mod hidden {
    pub trait DerefToSlice {
        type Element;
    }

    impl<Element, T: ?Sized + core::ops::DerefMut<Target = [Element]>> DerefToSlice for T {
        type Element = Element;
    }
}

// Convenient Type Aliases
// ----------------------------------------------------------------------------

/// A non-thread-safe readers-writer lock for borrowing subslices of
/// `Container`, implemented by a [red-black tree][1].
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type LocalRbTreeSliceIntervalRwLock<Container> = SliceIntervalRwLock<
    Container,
    <Container as hidden::DerefToSlice>::Element,
    raw::local::LocalRawRbTreeIntervalRwLock<usize>,
>;

#[cfg(feature = "std")]
#[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "std")))]
/// A thread-safe, blocking readers-writer lock for borrowing subslices of
/// `Container`, implemented by a [red-black tree][1].
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type SyncRbTreeSliceIntervalRwLock<Container, Priority = ()> = SliceIntervalRwLock<
    Container,
    <Container as hidden::DerefToSlice>::Element,
    raw::sync::SyncRawRbTreeIntervalRwLock<usize, Priority>,
>;

#[cfg(feature = "async")]
#[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "async")))]
/// A thread-safe, `Future`-oriented readers-writer lock for borrowing
/// subslices of `Container`, implemented by a [red-black tree][1].
/// `RawMutex: `[`lock_api::RawMutex`] is used to protect the internal state
/// data from concurrent accesses.
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type AsyncRbTreeSliceIntervalRwLock<RawMutex, Container, Priority = ()> = SliceIntervalRwLock<
    Container,
    <Container as hidden::DerefToSlice>::Element,
    raw::future::AsyncRawRbTreeIntervalRwLock<RawMutex, usize, Priority>,
>;

/// A non-thread-safe readers-writer lock for borrowing subslices of
/// `&'a mut [Element]`, implemented by a [red-black tree][1].
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type LocalRbTreeSliceRefIntervalRwLock<'a, Element> = SliceIntervalRwLock<
    &'a mut [Element],
    Element,
    raw::local::LocalRawRbTreeIntervalRwLock<usize>,
>;

#[cfg(feature = "std")]
#[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "std")))]
/// A thread-safe, blocking readers-writer lock for borrowing subslices of
/// `&'a mut [Element]`, implemented by a [red-black tree][1].
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type SyncRbTreeSliceRefIntervalRwLock<'a, Element, Priority = ()> = SliceIntervalRwLock<
    &'a mut [Element],
    Element,
    raw::sync::SyncRawRbTreeIntervalRwLock<usize, Priority>,
>;

#[cfg(feature = "async")]
#[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "async")))]
/// A thread-safe, `Future`-oriented readers-writer lock for borrowing
/// subslices of `&'a mut [Element]`, implemented by a [red-black tree][1].
/// `RawMutex: `[`lock_api::RawMutex`] is used to protect the internal state
/// data from concurrent accesses.
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type AsyncRbTreeSliceRefIntervalRwLock<'a, RawMutex, Element, Priority = ()> =
    SliceIntervalRwLock<
        &'a mut [Element],
        Element,
        raw::future::AsyncRawRbTreeIntervalRwLock<RawMutex, usize, Priority>,
    >;

#[cfg(feature = "alloc")]
#[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "alloc")))]
/// A non-thread-safe readers-writer lock for borrowing subslices of
/// `Vec<Element>`, implemented by a [red-black tree][1].
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type LocalRbTreeVecIntervalRwLock<Element> = SliceIntervalRwLock<
    alloc::vec::Vec<Element>,
    Element,
    raw::local::LocalRawRbTreeIntervalRwLock<usize>,
>;

#[cfg(feature = "std")]
#[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "std")))]
/// A thread-safe, blocking readers-writer lock for borrowing subslices of
/// `Vec<Element>`, implemented by a [red-black tree][1].
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type SyncRbTreeVecIntervalRwLock<Element, Priority = ()> = SliceIntervalRwLock<
    alloc::vec::Vec<Element>,
    Element,
    raw::sync::SyncRawRbTreeIntervalRwLock<usize, Priority>,
>;

#[cfg(all(feature = "async", feature = "alloc"))]
#[cfg_attr(
    feature = "doc_cfg",
    doc(cfg(all(feature = "async", feature = "alloc")))
)]
/// A thread-safe, `Future`-oriented readers-writer lock for borrowing
/// subslices of `Vec<Element>`, implemented by a [red-black tree][1].
/// `RawMutex: `[`lock_api::RawMutex`] is used to protect the internal state
/// data from concurrent accesses.
///
/// [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
pub type AsyncRbTreeVecIntervalRwLock<RawMutex, Element, Priority = ()> = SliceIntervalRwLock<
    alloc::vec::Vec<Element>,
    Element,
    raw::future::AsyncRawRbTreeIntervalRwLock<RawMutex, usize, Priority>,
>;