use { std::{ sync::Arc, collections::HashMap, hash::Hash }, std::sync::RwLock, crate::{ core::{ Observer, ObserverBroadcast, View, InnerViewPort }, index::{IndexArea, IndexView} } }; struct GridBuffer { data: HashMap, Item>, limit: Point2 } impl View for GridBuffer where Item: Clone + Send + Sync + 'static { type Msg = IndexArea>; } impl IndexView> for GridBufferView where Item: Clone + Send + Sync + 'static { type Item = Item; fn get(&self, key: &Point2) -> Option { self.data.get(key).cloned() } fn area(&self) -> IndexArea> { IndexArea::Range( Point2::new(0, 0) ..= self.limit ) } } pub struct GridBufferController where Item: Clone + Send + Sync + 'static { data: Arc, Item>>>, cast: Arc, Item = Item>>>> } impl GridBuffer where Key: Clone + Hash + Eq + Send + Sync + 'static, Item: Clone + Send + Sync + 'static { pub fn new(port: InnerViewPort, Item = Item>>) -> Self { let data = Arc::new(RwLock::new(HashMap::, Item>::new())); port.set_view(Some(Arc::new(GridBufferView(data.clone())))); GridBuffer { data, cast: port.get_broadcast() } } pub fn insert(&mut self, key: Point2, item: Item) { self.data.write().unwrap().insert(key.clone(), item); if self.cast.notify(&IndexArea::Set(vec![ key ])); } pub fn insert_iter(&mut self, iter: T) where T: IntoIterator, Item)> { for (key, item) in iter { self.insert(key, item); } } pub fn remove(&mut self, key: Point2) { self.data.write().unwrap().remove(&key); self.cast.notify(&IndexArea::Set(vec![ key ])); } }