use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex, MutexGuard};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ThreadSafeType<T: Clone> {
data: Arc<Mutex<T>>,
}
impl<T: Clone> ThreadSafeType<T> {
pub fn new(wrapped_type: T) -> Self {
ThreadSafeType {
data: Arc::new(Mutex::new(wrapped_type)),
}
}
pub fn create(an_arc: Arc<Mutex<T>>) -> Self {
ThreadSafeType { data: an_arc }
}
pub fn get_type(&self) -> MutexGuard<T> {
self.data.lock().unwrap()
}
pub fn get_arc(&self) -> Arc<Mutex<T>> {
self.data.clone()
}
pub fn set_arc(&mut self, new_arc: Arc<Mutex<T>>) {
self.data = Arc::clone(&new_arc);
}
}
#[derive(Debug)]
pub struct ThreadSafeOptionType<T> {
data: Arc<Mutex<Option<T>>>,
}
impl<T> Clone for ThreadSafeOptionType<T> {
fn clone(&self) -> Self {
let the_arc = self.get_arc();
ThreadSafeOptionType {
data: Arc::clone(&the_arc),
}
}
}
impl<T> Default for ThreadSafeOptionType<T> {
fn default() -> Self {
ThreadSafeOptionType::new(None)
}
}
impl<T> ThreadSafeOptionType<T> {
pub fn new(option_to_wrap: Option<T>) -> Self {
ThreadSafeOptionType {
data: Arc::new(Mutex::new(option_to_wrap)),
}
}
pub fn create(op_arc: Arc<Mutex<Option<T>>>) -> Self {
ThreadSafeOptionType { data: op_arc }
}
pub fn get_arc(&self) -> Arc<Mutex<Option<T>>> {
self.data.clone()
}
pub fn set_arc(&mut self, new_arc: Arc<Mutex<Option<T>>>) {
self.data = Arc::clone(&new_arc);
}
pub fn get_option(&self) -> MutexGuard<Option<T>> {
self.data.lock().unwrap()
}
pub fn set_option(&mut self, new_option: Option<T>) {
*self.data.lock().as_deref_mut().unwrap() = new_option;
}
pub fn is_none(&self) -> bool {
self.get_option().is_none()
}
pub fn is_some(&self) -> bool {
self.get_option().is_some()
}
}