SingletonBuffer: add get_mut()

This commit is contained in:
Michael Sippel 2021-11-18 14:43:10 +01:00
parent 941da4ed7d
commit 4ab20be1c5
Signed by: senvas
GPG key ID: F96CF119C34B64A6

View file

@ -1,6 +1,7 @@
use {
std::{
sync::{Arc}
sync::{Arc},
ops::{Deref, DerefMut}
},
std::sync::RwLock,
crate::{
@ -14,6 +15,8 @@ use {
}
};
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
pub struct SingletonBufferView<T: Clone + Send + Sync + 'static>(Arc<RwLock<T>>);
impl<T> View for SingletonBufferView<T>
@ -30,6 +33,8 @@ where T: Clone + Send + Sync + 'static {
}
}
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
#[derive(Clone)]
pub struct SingletonBuffer<T>
where T: Clone + Send + Sync + 'static {
@ -56,25 +61,50 @@ where T: Clone + Send + Sync + 'static {
self.value.read().unwrap().clone()
}
pub fn set(&mut self, new_value: T) {
let mut v = self.value.write().unwrap();
*v = new_value;
drop(v);
self.cast.notify(&());
}
}
/*
impl<T> SingletonBuffer<T>
where T: Clone + Eq + Send + Sync + 'static {
pub fn set(&mut self, new_value: T) {
let mut v = self.value.write().unwrap();
if *v != new_value {
*v = new_value;
drop(v);
self.cast.notify(&());
pub fn get_mut(&self) -> MutableSingletonAccess<T> {
MutableSingletonAccess {
buf: self.clone(),
val: self.get()
}
}
}
*/
// TODO: impl Deref & DerefMut
pub fn set(&mut self, new_value: T) {
let mut v = self.value.write().unwrap();
*v = new_value;
drop(v);
self.cast.notify(&());
}
}
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
pub struct MutableSingletonAccess<T>
where T: Clone + Send + Sync + 'static {
buf: SingletonBuffer<T>,
val: T,
}
impl<T> Deref for MutableSingletonAccess<T>
where T: Clone + Send + Sync + 'static {
type Target = T;
fn deref(&self) -> &T {
&self.val
}
}
impl<T> DerefMut for MutableSingletonAccess<T>
where T: Clone + Send + Sync + 'static {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.val
}
}
impl<T> Drop for MutableSingletonAccess<T>
where T: Clone + Send + Sync + 'static {
fn drop(&mut self) {
self.buf.set(self.val.clone());
}
}