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