quarkrs/structures/thead_data.rs
1use std::sync::{RwLock, Arc, RwLockReadGuard, RwLockWriteGuard, TryLockError};
2
3/// An Abstracted generic combining the functionality of Arc types and Read/Write locks.
4/// all functions are atomic and can be passed between threads safely.
5pub struct ThreadData<T> {
6 value: Arc<RwLock<T>>
7}
8
9impl<T> Clone for ThreadData<T> {
10 fn clone(&self) -> Self {
11 Self { value: self.value.clone() }
12 }
13}
14
15
16impl<T> ThreadData<T> {
17 pub fn new(val: T) -> ThreadData<T> {
18 ThreadData {
19 value: Arc::new(
20 RwLock::new(val)
21 ),
22 }
23 }
24
25 /// Attepmts to aquire immutable access to the data contained within, returning eithwer a ReadGuard if the data is available to be read, or a TryLockError if data is unreadable
26 /// the data will be unreadable if there is a mutable access to the data somewhere else.
27 /// ---
28 /// ThreadData allows infinite immutable accesses or a single mutable access.
29 pub fn try_read_access(&self) -> Result<RwLockReadGuard<'_, T>, TryLockError<RwLockReadGuard<'_, T>>> {
30 self.value.try_read()
31 }
32
33 /// Attepmts to aquire mutable access to the data contained within, returning eithwer a WriteGuard if the data is available to be read, or a TryLockError if data is unreadable
34 /// the data will be unreadable if there is a access to the data somewhere else in any form.
35 /// ---
36 /// ThreadData allows infinite immutable accesses or a single mutable access.
37 pub fn try_write_access(&self) -> Result<RwLockWriteGuard<'_, T>, TryLockError<RwLockWriteGuard<'_, T>>> {
38 self.value.try_write()
39 }
40
41 /// ignores any error managing while attempting to aquire an immutable referance to the data stored, if access is unavailable, function will panic.
42 /// Useage is heavily discouraged as will likely cause panics.
43 pub fn force_read_access(&self) -> RwLockReadGuard<'_, T> {
44 match self.value.try_read() {
45 Ok(out) => out,
46 Err(_) => panic!(),
47 }
48 }
49
50 /// ignores any error managing while attempting to aquire a mutable referance to the data stored, if access is unavailable, function will panic.
51 /// Useage is heavily discouraged as will likely cause panics.
52 pub fn force_write_access(&self) -> RwLockWriteGuard<'_, T> {
53 match self.value.try_write() {
54 Ok(out) => out,
55 Err(_) => panic!(),
56 }
57 }
58}