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
use crate::{Exception, ExceptionValue as EV};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};

#[derive(Clone, Debug)]
pub struct Locker<T> {
    val: Arc<RwLock<T>>,
}

impl<T> Locker<T> {
    pub fn new(val: T) -> Self {
        Self {
            val: Arc::new(RwLock::new(val)),
        }
    }

    pub fn read(&self) -> Result<RwLockReadGuard<T>, Exception> {
        match self.val.read() {
            Ok(val) => Ok(val),
            Err(_) => Err(Exception::new(
                EV::Concurrency,
                None,
                Some(
                    "could not safely find value in memory (has concurrency gone wrong?)"
                        .to_string(),
                ),
            )),
        }
    }

    pub fn write(&self) -> Result<RwLockWriteGuard<T>, Exception> {
        match self.val.write() {
            Ok(val) => Ok(val),
            Err(_) => Err(Exception::new(
                EV::Concurrency,
                None,
                Some(
                    "could not safely find value in memory (has concurrency gone wrong?)"
                        .to_string(),
                ),
            )),
        }
    }
}