1use crate::{Exception, ExceptionValue as EV};
2use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
3
4#[derive(Clone, Debug)]
5pub struct Locker<T> {
6 val: Arc<RwLock<T>>,
7}
8
9impl<T> Locker<T> {
10 pub fn new(val: T) -> Self {
11 Self {
12 val: Arc::new(RwLock::new(val)),
13 }
14 }
15
16 pub fn read(&self) -> Result<RwLockReadGuard<T>, Exception> {
17 match self.val.read() {
18 Ok(val) => Ok(val),
19 Err(_) => Err(Exception::new(
20 EV::Concurrency,
21 None,
22 Some(
23 "could not safely find value in memory (has concurrency gone wrong?)"
24 .to_string(),
25 ),
26 )),
27 }
28 }
29
30 pub fn write(&self) -> Result<RwLockWriteGuard<T>, Exception> {
31 match self.val.write() {
32 Ok(val) => Ok(val),
33 Err(_) => Err(Exception::new(
34 EV::Concurrency,
35 None,
36 Some(
37 "could not safely find value in memory (has concurrency gone wrong?)"
38 .to_string(),
39 ),
40 )),
41 }
42 }
43}