parking_method/
mutex_method.rs1use crate::*;
2
3pub trait MutexMethod<'a, V> {
6 fn lock(&self, mutex: &'a Mutex<V>) -> Option<MutexGuard<'a, V>>;
8}
9
10macro_rules! impl_locking_method {
11 ($policy:ty, $lock:expr) => {
12 impl<'a, V> MutexMethod<'a, V> for $policy {
13 #[inline(always)]
14 #[allow(unused_variables)]
15 fn lock(&self, mutex: &'a Mutex<V>) -> Option<MutexGuard<'a, V>> {
16 #[allow(unused_macros)]
17 macro_rules! method {
18 () => {
19 self
20 };
21 }
22 #[allow(unused_macros)]
23 macro_rules! lock {
24 () => {
25 mutex
26 };
27 }
28 $lock
29 }
30 }
31 };
32}
33
34impl_locking_method!(Blocking, Some(lock!().lock()));
35
36impl_locking_method!(TryLock, lock!().try_lock());
37
38impl_locking_method!(Duration, lock!().try_lock_for(*method!()));
39
40impl_locking_method!(Instant, lock!().try_lock_until(*method!()));
41
42#[cfg(test)]
43mod test {
44 use crate::*;
45
46 #[test]
47 fn smoke() {
48 let mutex = Mutex::new(String::from("test"));
49 assert_eq!(*MutexMethod::lock(&Blocking, &mutex).unwrap(), "test");
50 }
51
52 #[test]
53 fn trylocks() {
54 let mutex = Mutex::new(String::from("test"));
55
56 assert_eq!(*MutexMethod::lock(&TryLock, &mutex).unwrap(), "test");
57 assert_eq!(
58 *MutexMethod::lock(&Duration::from_millis(100), &mutex).unwrap(),
59 "test"
60 );
61 assert_eq!(
62 *MutexMethod::lock(&(Instant::now() + Duration::from_millis(100)), &mutex).unwrap(),
63 "test"
64 );
65 }
66}