From 8e36e1c2fdcdedcb49436e9a221e668f247be794 Mon Sep 17 00:00:00 2001 From: Michael Sippel Date: Wed, 16 Jun 2021 02:56:11 +0200 Subject: [PATCH] singleton map --- nested/src/singleton/map.rs | 84 +++++++++++++++++++++++++++++++++++++ nested/src/singleton/mod.rs | 1 + 2 files changed, 85 insertions(+) create mode 100644 nested/src/singleton/map.rs diff --git a/nested/src/singleton/map.rs b/nested/src/singleton/map.rs new file mode 100644 index 0000000..e97802a --- /dev/null +++ b/nested/src/singleton/map.rs @@ -0,0 +1,84 @@ +use { + std::sync::Arc, + std::sync::RwLock, + crate::{ + singleton::{SingletonView}, + core::{ + Observer, ObserverExt, ObserverBroadcast, + View, ViewPort, OuterViewPort + } + } +}; + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +impl OuterViewPort> { + pub fn map< + DstItem: 'static, + F: Fn(Item) -> DstItem + Send + Sync + 'static + >( + &self, + f: F + ) -> OuterViewPort> { + let port = ViewPort::new(); + port.add_update_hook(Arc::new(self.0.clone())); + + let map = Arc::new(RwLock::new(MapSingleton { + src_view: None, + f, + cast: port.inner().get_broadcast() + })); + + self.add_observer(map.clone()); + port.inner().set_view(Some(map)); + port.into_outer() + } +} + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +pub struct MapSingleton +where SrcView: SingletonView + ?Sized, + F: Fn(SrcView::Item) -> DstItem + Send + Sync +{ + src_view: Option>, + f: F, + cast: Arc>>> +} + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +impl View for MapSingleton +where SrcView: SingletonView + ?Sized, + F: Fn(SrcView::Item) -> DstItem + Send + Sync +{ + type Msg = (); +} + +impl SingletonView for MapSingleton +where SrcView: SingletonView + ?Sized, + F: Fn(SrcView::Item) -> DstItem + Send + Sync +{ + type Item = DstItem; + + fn get(&self) -> DstItem { + (self.f)(self.src_view.as_ref().unwrap().get()) + } +} + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +impl Observer for MapSingleton +where SrcView: SingletonView + ?Sized, + F: Fn(SrcView::Item) -> DstItem + Send + Sync +{ + fn reset(&mut self, view: Option>) { + self.src_view = view; + self.cast.notify(&()); + } + + fn notify(&mut self, msg: &()) { + self.cast.notify(msg); + } +} + diff --git a/nested/src/singleton/mod.rs b/nested/src/singleton/mod.rs index b18ac46..5b55b2f 100644 --- a/nested/src/singleton/mod.rs +++ b/nested/src/singleton/mod.rs @@ -1,5 +1,6 @@ pub mod buffer; +pub mod map; use { std::{