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,25 +61,50 @@ where T: Clone + Send + Sync + 'static {
self.value.read().unwrap().clone() self.value.read().unwrap().clone()
} }
pub fn set(&mut self, new_value: T) { pub fn get_mut(&self) -> MutableSingletonAccess<T> {
let mut v = self.value.write().unwrap(); MutableSingletonAccess {
*v = new_value; buf: self.clone(),
drop(v); val: self.get()
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 set(&mut self, new_value: T) {
// TODO: impl Deref & DerefMut 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());
}
}