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
//! Extension traits for `std::sync::RwLock`.

use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};

/// Extension trait with useful methods for [`std::sync::RwLock`].
///
/// [`std::sync::RwLock`]: https://doc.rust-lang.org/std/sync/struct.RwLock.html
pub trait RwLockExt<T> {
    /// Shorthand for `lock.read().unwrap()` with a better panic message.
    ///
    /// This method is intended to be used in situations where poisoned locks are
    /// considered an exceptional situation and should always result in panic.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::{Arc, RwLock};
    /// use stdext::prelude::*;
    ///
    /// let lock = Arc::new(RwLock::new(1));
    ///
    /// let n = lock.force_read();
    /// assert_eq!(*n, 1);
    /// ```
    fn force_read(&self) -> RwLockReadGuard<T>;

    /// Shorthand for `lock.write().unwrap()` with a better panic message.
    ///
    /// This method is intended to be used in situations where poisoned locks are
    /// considered an exceptional situation and should always result in panic.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::{Arc, RwLock};
    /// use stdext::prelude::*;
    ///
    /// let lock = Arc::new(RwLock::new(1));
    ///
    /// {
    ///     let mut n = lock.force_write();
    ///     *n = 2;
    /// }
    ///
    /// let n = lock.force_read();
    /// assert_eq!(*n, 2);
    /// ```
    fn force_write(&self) -> RwLockWriteGuard<T>;
}

impl<T> RwLockExt<T> for RwLock<T> {
    fn force_read(&self) -> RwLockReadGuard<T> {
        self.read()
            .expect("Unable to obtain read lock: RwLock is poisoned")
    }
    fn force_write(&self) -> RwLockWriteGuard<T> {
        self.write()
            .expect("Unable to obtain write lock: RwLock is poisoned")
    }
}