From 906cc51329e7d5342bfa4266bb02ce1b68900326 Mon Sep 17 00:00:00 2001 From: Michael Sippel Date: Sun, 23 Oct 2022 14:48:39 +0200 Subject: [PATCH] sequence: add enumerate() --- nested/src/sequence/enumerate.rs | 86 ++++++++++++++++++++++++++++++++ nested/src/sequence/mod.rs | 1 + 2 files changed, 87 insertions(+) create mode 100644 nested/src/sequence/enumerate.rs diff --git a/nested/src/sequence/enumerate.rs b/nested/src/sequence/enumerate.rs new file mode 100644 index 0000000..69c661c --- /dev/null +++ b/nested/src/sequence/enumerate.rs @@ -0,0 +1,86 @@ +use { + crate::{ + core::{Observer, ObserverBroadcast, ObserverExt, OuterViewPort, View, ViewPort}, + sequence::SequenceView, + }, + std::sync::Arc, + std::sync::RwLock, +}; + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +impl OuterViewPort> { + pub fn enumerate(&self) -> OuterViewPort> { + let port = ViewPort::new(); + port.add_update_hook(Arc::new(self.0.clone())); + + let map = Arc::new(RwLock::new(EnumerateSequence { + src_view: None, + cast: port.inner().get_broadcast(), + })); + + self.add_observer(map.clone()); + port.inner().set_view(Some(map)); + port.into_outer() + } +} + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +pub struct EnumerateSequence +where + SrcView: SequenceView + ?Sized, +{ + src_view: Option>, + cast: Arc>>>, +} + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +impl View for EnumerateSequence +where + SrcView: SequenceView + ?Sized, +{ + type Msg = usize; +} + +impl SequenceView for EnumerateSequence +where + SrcView: SequenceView + ?Sized +{ + type Item = (usize, SrcView::Item); + + fn len(&self) -> Option { + self.src_view.len() + } + + fn get(&self, idx: &usize) -> Option<(usize, SrcView::Item)> { + self.src_view.get(idx).map(|item| (*idx, item)) + } +} + +//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>> + +impl Observer for EnumerateSequence +where + SrcView: SequenceView + ?Sized +{ + fn reset(&mut self, view: Option>) { + let old_len = self.len(); + self.src_view = view; + let new_len = self.len(); + + if let Some(len) = old_len { + self.cast.notify_each(0..len); + } + if let Some(len) = new_len { + self.cast.notify_each(0..len); + } + } + + fn notify(&mut self, msg: &usize) { + self.cast.notify(msg); + } +} + + diff --git a/nested/src/sequence/mod.rs b/nested/src/sequence/mod.rs index 3872995..d3f2d2c 100644 --- a/nested/src/sequence/mod.rs +++ b/nested/src/sequence/mod.rs @@ -1,5 +1,6 @@ pub mod filter; pub mod map; +pub mod enumerate; pub mod seq2idx; pub mod flatten; pub mod decorator;