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
use crate::*;

/// Trait for implementing read/write flavors on RwLocks.
pub trait RwLockMethod<'a, V> {
    /// Obtain a read lock. Blocking locks are infallible and always return a 'Some()' variant.
    fn read(&self, rwlock: &'a RwLock<V>) -> Option<RwLockReadGuard<'a, V>>;

    /// Obtain a write lock. Blocking locks are infallible and always return a 'Some()' variant.
    fn write(&self, rwlock: &'a RwLock<V>) -> Option<RwLockWriteGuard<'a, V>>;
}

macro_rules! impl_locking_method {
    ($policy:ty, $read:expr, $write:expr) => {
        impl<'a, V> RwLockMethod<'a, V> for $policy {
            #[inline(always)]
            #[allow(unused_variables)]
            fn read(&self, rwlock: &'a RwLock<V>) -> Option<RwLockReadGuard<'a, V>> {
                #[allow(unused_macros)]
                macro_rules! method {
                    () => {
                        self
                    };
                }
                #[allow(unused_macros)]
                macro_rules! lock {
                    () => {
                        rwlock
                    };
                }
                $read
            }

            #[inline(always)]
            #[allow(unused_variables)]
            fn write(&self, rwlock: &'a RwLock<V>) -> Option<RwLockWriteGuard<'a, V>> {
                #[allow(unused_macros)]
                macro_rules! method {
                    () => {
                        self
                    };
                }
                #[allow(unused_macros)]
                macro_rules! lock {
                    () => {
                        rwlock
                    };
                }
                $write
            }
        }
    };
}

impl_locking_method!(Blocking, Some(lock!().read()), Some(lock!().write()));

impl_locking_method!(TryLock, lock!().try_read(), lock!().try_write());

impl_locking_method!(
    Duration,
    lock!().try_read_for(*method!()),
    lock!().try_write_for(*method!())
);

impl_locking_method!(
    Instant,
    lock!().try_read_until(*method!()),
    lock!().try_write_until(*method!())
);

impl_locking_method!(
    Recursive<Blocking>,
    Some(lock!().read_recursive()),
    Some(lock!().write())
);

impl_locking_method!(
    Recursive<TryLock>,
    lock!().try_read_recursive(),
    unimplemented!("Not implemented in parking_lot")
);

impl_locking_method!(
    Recursive<Duration>,
    lock!().try_read_recursive_for(method!().0),
    unimplemented!("Not implemented in parking_lot")
);

impl_locking_method!(
    Recursive<Instant>,
    lock!().try_read_recursive_until(method!().0),
    unimplemented!("Not implemented in parking_lot")
);