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

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

macro_rules! impl_locking_method {
    ($policy:ty, $write:expr) => {
        impl WriteLockMethod for $policy {
            #[inline(always)]
            #[allow(unused_variables)]
            fn write<'a, V>(&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!().write()));

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

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

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

#[cfg(test)]
mod test {
    use crate::*;

    #[test]
    fn smoke() {
        let rwlock = RwLock::new(String::from("test"));
        assert_eq!(*WriteLockMethod::write(&Blocking, &rwlock).unwrap(), "test");
    }

    #[test]
    fn trylocks() {
        let rwlock = RwLock::new(String::from("test"));

        assert_eq!(*WriteLockMethod::write(&TryLock, &rwlock).unwrap(), "test");
        assert_eq!(
            *WriteLockMethod::write(&Duration::from_millis(100), &rwlock).unwrap(),
            "test"
        );
        assert_eq!(
            *WriteLockMethod::write(&(Instant::now() + Duration::from_millis(100)), &rwlock)
                .unwrap(),
            "test"
        );
    }
}