add IndexBuffer

This commit is contained in:
Michael Sippel 2021-08-27 22:31:25 +02:00
parent cec7b4a0a0
commit fb5ae53e88
Signed by: senvas
GPG key ID: F96CF119C34B64A6
2 changed files with 82 additions and 1 deletions

View file

@ -0,0 +1,81 @@
use {
std::{
sync::Arc,
collections::HashMap,
hash::Hash
},
std::sync::RwLock,
crate::{
core::{
Observer,
ObserverBroadcast,
View,
InnerViewPort
},
index::IndexView
}
};
pub struct IndexBufferView<Key, Item>(Arc<RwLock<HashMap<Key, Item>>>)
where Key: Clone + Hash + Eq + Send + Sync + 'static,
Item: Clone + Send + Sync + 'static;
impl<Key, Item> View for IndexBufferView<Key, Item>
where Key: Clone + Hash + Eq + Send + Sync + 'static,
Item: Clone + Send + Sync + 'static
{
type Msg = Key;
}
impl<Key, Item> IndexView<Key> for IndexBufferView<Key, Item>
where Key: Clone + Hash + Eq + Send + Sync + 'static,
Item: Clone + Send + Sync + 'static
{
type Item = Item;
fn get(&self, key: &Key) -> Option<Self::Item> {
self.0.read().unwrap().get(key).cloned()
}
fn area(&self) -> Option<Vec<Key>> {
Some(self.0.read().unwrap().keys().cloned().collect())
}
}
pub struct IndexBuffer<Key, Item>
where Key: Clone + Hash + Eq + Send + Sync + 'static,
Item: Clone + Send + Sync + 'static
{
data: Arc<RwLock<HashMap<Key, Item>>>,
cast: Arc<RwLock<ObserverBroadcast<dyn IndexView<Key, Item = Item>>>>
}
impl<Key, Item> IndexBuffer<Key, Item>
where Key: Clone + Hash + Eq + Send + Sync + 'static,
Item: Clone + Send + Sync + 'static
{
pub fn new(port: InnerViewPort<dyn IndexView<Key, Item = Item>>) -> Self {
let data = Arc::new(RwLock::new(HashMap::<Key, Item>::new()));
port.set_view(Some(Arc::new(IndexBufferView(data.clone()))));
IndexBuffer {
data,
cast: port.get_broadcast()
}
}
pub fn insert(&mut self, key: Key, item: Item) {
self.data.write().unwrap().insert(key.clone(), item);
self.cast.notify(&key);
}
pub fn insert_iter<T>(&mut self, iter: T)
where T: IntoIterator<Item = (Key, Item)> {
for (key, item) in iter {
self.insert(key, item);
}
}
}

View file

@ -1,6 +1,7 @@
pub mod map_item;
pub mod map_key;
pub mod buffer;
use {
std::{
@ -46,7 +47,6 @@ impl<Key, V> IndexView<Key> for Arc<V>
where Key: Send + Sync,
V: IndexView<Key> + ?Sized
{
type Item = V::Item;
fn get(&self, key: &Key) -> Option<Self::Item> {