futures_signals/
signal_map.rs

1use crate::signal::Signal;
2use std::cmp::Ord;
3use std::collections::{BTreeMap, VecDeque};
4use std::pin::Pin;
5use std::marker::Unpin;
6use std::future::Future;
7use std::task::{Poll, Context};
8use futures_core::Stream;
9use futures_util::stream;
10use futures_util::stream::StreamExt;
11use pin_project::pin_project;
12
13// TODO make this non-exhaustive
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum MapDiff<K, V> {
17    Replace {
18        entries: Vec<(K, V)>,
19    },
20
21    Insert {
22        key: K,
23        value: V,
24    },
25
26    Update {
27        key: K,
28        value: V,
29    },
30
31    Remove {
32        key: K,
33    },
34
35    Clear {},
36}
37
38impl<K, A> MapDiff<K, A> {
39    // TODO inline this ?
40    fn map<B, F>(self, mut callback: F) -> MapDiff<K, B> where F: FnMut(A) -> B {
41        match self {
42            // TODO figure out a more efficient way of implementing this
43            MapDiff::Replace { entries } => MapDiff::Replace { entries: entries.into_iter().map(|(k, v)| (k, callback(v))).collect() },
44            MapDiff::Insert { key, value } => MapDiff::Insert { key, value: callback(value) },
45            MapDiff::Update { key, value } => MapDiff::Update { key, value: callback(value) },
46            MapDiff::Remove { key } => MapDiff::Remove { key },
47            MapDiff::Clear {} => MapDiff::Clear {},
48        }
49    }
50}
51
52
53// TODO impl for AssertUnwindSafe ?
54#[must_use = "SignalMaps do nothing unless polled"]
55pub trait SignalMap {
56    type Key;
57    type Value;
58
59    fn poll_map_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>>;
60}
61
62
63// Copied from Future in the Rust stdlib
64impl<'a, A> SignalMap for &'a mut A where A: ?Sized + SignalMap + Unpin {
65    type Key = A::Key;
66    type Value = A::Value;
67
68    #[inline]
69    fn poll_map_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> {
70        A::poll_map_change(Pin::new(&mut **self), cx)
71    }
72}
73
74// Copied from Future in the Rust stdlib
75impl<A> SignalMap for Box<A> where A: ?Sized + SignalMap + Unpin {
76    type Key = A::Key;
77    type Value = A::Value;
78
79    #[inline]
80    fn poll_map_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> {
81        A::poll_map_change(Pin::new(&mut *self), cx)
82    }
83}
84
85// Copied from Future in the Rust stdlib
86impl<A> SignalMap for Pin<A>
87    where A: Unpin + ::std::ops::DerefMut,
88          A::Target: SignalMap {
89    type Key = <<A as ::std::ops::Deref>::Target as SignalMap>::Key;
90    type Value = <<A as ::std::ops::Deref>::Target as SignalMap>::Value;
91
92    #[inline]
93    fn poll_map_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> {
94        Pin::get_mut(self).as_mut().poll_map_change(cx)
95    }
96}
97
98
99// TODO Seal this
100pub trait SignalMapExt: SignalMap {
101    #[inline]
102    fn map_value<A, F>(self, callback: F) -> MapValue<Self, F>
103        where F: FnMut(Self::Value) -> A,
104              Self: Sized {
105        MapValue {
106            signal: self,
107            callback,
108        }
109    }
110
111    #[inline]
112    fn map_value_signal<A, F>(self, callback: F) -> MapValueSignal<Self, A, F>
113        where A: Signal,
114              F: FnMut(Self::Value) -> A,
115              Self: Sized {
116        MapValueSignal {
117            signal: Some(self),
118            signals: BTreeMap::new(),
119            pending: VecDeque::new(),
120            callback,
121        }
122    }
123
124    /// Returns a signal that tracks the value of a particular key in the map.
125    #[inline]
126    fn key_cloned(self, key: Self::Key) -> MapWatchKeySignal<Self>
127        where Self::Key: PartialEq,
128              Self::Value: Clone,
129              Self: Sized {
130        MapWatchKeySignal {
131            signal_map: self,
132            watch_key: key,
133            first: true,
134        }
135    }
136
137    #[inline]
138    fn for_each<U, F>(self, callback: F) -> ForEach<Self, U, F>
139        where U: Future<Output = ()>,
140              F: FnMut(MapDiff<Self::Key, Self::Value>) -> U,
141              Self: Sized {
142        // TODO a little hacky
143        ForEach {
144            inner: SignalMapStream {
145                signal_map: self,
146            }.for_each(callback)
147        }
148    }
149
150    /// A convenience for calling `SignalMap::poll_map_change` on `Unpin` types.
151    #[inline]
152    fn poll_map_change_unpin(&mut self, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> where Self: Unpin + Sized {
153        Pin::new(self).poll_map_change(cx)
154    }
155
156    #[inline]
157    fn boxed<'a>(self) -> Pin<Box<dyn SignalMap<Key = Self::Key, Value = Self::Value> + Send + 'a>>
158        where Self: Sized + Send + 'a {
159        Box::pin(self)
160    }
161
162    #[inline]
163    fn boxed_local<'a>(self) -> Pin<Box<dyn SignalMap<Key = Self::Key, Value = Self::Value> + 'a>>
164        where Self: Sized + 'a {
165        Box::pin(self)
166    }
167}
168
169// TODO why is this ?Sized
170impl<T: ?Sized> SignalMapExt for T where T: SignalMap {}
171
172
173/// An owned dynamically typed [`SignalMap`].
174///
175/// This is useful if you don't know the static type, or if you need
176/// indirection.
177pub type BoxSignalMap<'a, Key, Value> = Pin<Box<dyn SignalMap<Key = Key, Value = Value> + Send + 'a>>;
178
179/// Same as [`BoxSignalMap`], but without the `Send` requirement.
180pub type LocalBoxSignalMap<'a, Key, Value> = Pin<Box<dyn SignalMap<Key = Key, Value = Value> + 'a>>;
181
182
183#[derive(Debug)]
184#[must_use = "SignalMaps do nothing unless polled"]
185pub struct Always<A> {
186    map: Option<A>,
187}
188
189impl<A> Unpin for Always<A> {}
190
191impl<A, K, V> SignalMap for Always<A> where A: IntoIterator<Item = (K, V)> {
192    type Key = K;
193    type Value = V;
194
195    #[inline]
196    fn poll_map_change(mut self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> {
197        match self.map.take() {
198            Some(map) => {
199                let entries: Vec<(K, V)> = map.into_iter().collect();
200                Poll::Ready(Some(MapDiff::Replace { entries }))
201            },
202            None => {
203                Poll::Ready(None)
204            },
205        }
206    }
207}
208
209/// Converts an `IntoIterator<Item = (K, V)>` into a `SignalMap<Key = K, Value = V>`.
210///
211/// This will usually be a `BTreeMap<K, V>` or `Vec<(K, V)>`.
212#[inline]
213pub fn always<A, K, V>(map: A) -> Always<A> where A: IntoIterator<Item = (K, V)> {
214    Always {
215        map: Some(map),
216    }
217}
218
219
220#[pin_project(project = MapValueProj)]
221#[derive(Debug)]
222#[must_use = "SignalMaps do nothing unless polled"]
223pub struct MapValue<A, B> {
224    #[pin]
225    signal: A,
226    callback: B,
227}
228
229impl<A, B, F> SignalMap for MapValue<A, F>
230    where A: SignalMap,
231          F: FnMut(A::Value) -> B {
232    type Key = A::Key;
233    type Value = B;
234
235    // TODO should this inline ?
236    #[inline]
237    fn poll_map_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> {
238        let MapValueProj { signal, callback } = self.project();
239
240        signal.poll_map_change(cx).map(|some| some.map(|change| change.map(|value| callback(value))))
241    }
242}
243
244// This is an optimization to allow a SignalMap to efficiently "return" multiple MapDiff
245// TODO can this be made more efficient ?
246// TODO refactor `signal_map`'s and `signal_vec`'s `PendingBuilder` & `unwrap` into common helpers?
247struct PendingBuilder<A> {
248    first: Option<A>,
249    rest: VecDeque<A>,
250}
251
252impl<A> PendingBuilder<A> {
253    fn new() -> Self {
254        Self {
255            first: None,
256            rest: VecDeque::new(),
257        }
258    }
259
260    fn push(&mut self, value: A) {
261        if let None = self.first {
262            self.first = Some(value);
263
264        } else {
265            self.rest.push_back(value);
266        }
267    }
268}
269
270fn unwrap<A>(x: Poll<Option<A>>) -> A {
271    match x {
272        Poll::Ready(Some(x)) => x,
273        _ => panic!("Signal did not return a value"),
274    }
275}
276
277#[pin_project(project = MapValueSignalProj)]
278#[derive(Debug)]
279#[must_use = "SignalMaps do nothing unless polled"]
280pub struct MapValueSignal<A, B, F> where A: SignalMap, B: Signal {
281    #[pin]
282    signal: Option<A>,
283    // TODO is there a more efficient way to implement this ?
284    signals: BTreeMap<A::Key, Option<Pin<Box<B>>>>,
285    pending: VecDeque<MapDiff<A::Key, B::Item>>,
286    callback: F,
287}
288
289impl<A, B, F> SignalMap for MapValueSignal<A, B, F>
290    where A: SignalMap,
291          A::Key: Clone + Ord,
292          B: Signal,
293          F: FnMut(A::Value) -> B {
294    type Key = A::Key;
295    type Value = B::Item;
296
297    fn poll_map_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> {
298        let MapValueSignalProj { mut signal, signals, pending, callback } = self.project();
299
300        if let Some(diff) = pending.pop_front() {
301            return Poll::Ready(Some(diff));
302        }
303
304        let mut new_pending = PendingBuilder::new();
305
306        let done = loop {
307            break match signal.as_mut().as_pin_mut().map(|signal| signal.poll_map_change(cx)) {
308                None => {
309                    true
310                },
311                Some(Poll::Ready(None)) => {
312                    signal.set(None);
313                    true
314                },
315                Some(Poll::Ready(Some(change))) => {
316                    new_pending.push(match change {
317                        MapDiff::Replace { entries } => {
318                            *signals = BTreeMap::new();
319
320                            MapDiff::Replace {
321                                entries: entries.into_iter().map(|(key, value)| {
322                                    let mut signal = Box::pin(callback(value));
323                                    let poll = (key.clone(), unwrap(signal.as_mut().poll_change(cx)));
324                                    signals.insert(key, Some(signal));
325                                    poll
326                                }).collect()
327                            }
328                        },
329
330                        MapDiff::Insert { key, value } => {
331                            let mut signal = Box::pin(callback(value));
332                            let poll = unwrap(signal.as_mut().poll_change(cx));
333                            signals.insert(key.clone(), Some(signal));
334                            MapDiff::Insert { key, value: poll }
335                        },
336
337                        MapDiff::Update { key, value } => {
338                            let mut signal = Box::pin(callback(value));
339                            let poll = unwrap(signal.as_mut().poll_change(cx));
340                            *signals.get_mut(&key).expect("The key is not in the map") = Some(signal);
341                            MapDiff::Update { key, value: poll }
342                        },
343
344                        MapDiff::Remove { key } => {
345                            signals.remove(&key);
346                            MapDiff::Remove { key }
347                        },
348
349                        MapDiff::Clear {} => {
350                            signals.clear();
351                            MapDiff::Clear {}
352                        },
353                    });
354
355                    continue;
356                },
357                Some(Poll::Pending) => false,
358            };
359        };
360
361        let mut has_pending = false;
362
363        // TODO ensure that this is as efficient as possible
364        // TODO make this more efficient (e.g. using a similar strategy as FuturesUnordered)
365        for (key, signal) in signals.into_iter() {
366            // TODO use a loop until the value stops changing ?
367            match signal.as_mut().map(|s| s.as_mut().poll_change(cx)) {
368                Some(Poll::Ready(Some(value))) => {
369                    new_pending.push(MapDiff::Update { key: key.clone(), value });
370                },
371                Some(Poll::Ready(None)) => {
372                    *signal = None;
373                },
374                Some(Poll::Pending) => {
375                    has_pending = true;
376                },
377                None => {},
378            }
379        }
380
381        if let Some(first) = new_pending.first {
382            *pending = new_pending.rest;
383            Poll::Ready(Some(first))
384
385        } else if done && !has_pending {
386            Poll::Ready(None)
387
388        } else {
389            Poll::Pending
390        }
391    }
392}
393
394#[pin_project(project = MapWatchKeySignalProj)]
395#[derive(Debug)]
396pub struct MapWatchKeySignal<M> where M: SignalMap {
397    #[pin]
398    signal_map: M,
399    watch_key: M::Key,
400    first: bool,
401}
402
403impl<M> Signal for MapWatchKeySignal<M>
404    where M: SignalMap,
405          M::Key: PartialEq,
406          M::Value: Clone {
407    type Item = Option<M::Value>;
408
409    fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
410        let MapWatchKeySignalProj { mut signal_map, watch_key, first } = self.project();
411
412        let mut changed: Option<Option<M::Value>> = None;
413
414        let is_done = loop {
415            break match signal_map.as_mut().poll_map_change(cx) {
416                Poll::Ready(some) => match some {
417                    Some(MapDiff::Replace { entries }) => {
418                        changed = Some(
419                            entries
420                                .into_iter()
421                                .find(|entry| entry.0 == *watch_key)
422                                .map(|entry| entry.1)
423                        );
424                        continue;
425                    },
426                    Some(MapDiff::Insert { key, value }) | Some(MapDiff::Update { key, value }) => {
427                        if key == *watch_key {
428                            changed = Some(Some(value));
429                        }
430                        continue;
431                    },
432                    Some(MapDiff::Remove { key }) => {
433                        if key == *watch_key {
434                            changed = Some(None);
435                        }
436                        continue;
437                    },
438                    Some(MapDiff::Clear {}) => {
439                        changed = Some(None);
440                        continue;
441                    },
442                    None => {
443                        true
444                    },
445                },
446                Poll::Pending => {
447                    false
448                },
449            }
450        };
451
452        if let Some(change) = changed {
453            *first = false;
454            Poll::Ready(Some(change))
455
456        } else if *first {
457            *first = false;
458            Poll::Ready(Some(None))
459
460        } else if is_done {
461            Poll::Ready(None)
462
463        } else {
464            Poll::Pending
465        }
466    }
467}
468
469
470#[pin_project]
471#[derive(Debug)]
472#[must_use = "Streams do nothing unless polled"]
473struct SignalMapStream<A> {
474    #[pin]
475    signal_map: A,
476}
477
478impl<A: SignalMap> Stream for SignalMapStream<A> {
479    type Item = MapDiff<A::Key, A::Value>;
480
481    #[inline]
482    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
483        self.project().signal_map.poll_map_change(cx)
484    }
485}
486
487
488#[pin_project]
489#[derive(Debug)]
490#[must_use = "Futures do nothing unless polled"]
491pub struct ForEach<A, B, C> {
492    #[pin]
493    inner: stream::ForEach<SignalMapStream<A>, B, C>,
494}
495
496impl<A, B, C> Future for ForEach<A, B, C>
497    where A: SignalMap,
498          B: Future<Output = ()>,
499          C: FnMut(MapDiff<A::Key, A::Value>) -> B {
500    type Output = ();
501
502    #[inline]
503    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
504        self.project().inner.poll(cx)
505    }
506}
507
508
509// TODO verify that this is correct
510mod mutable_btree_map {
511    use super::{SignalMap, SignalMapExt, MapDiff};
512    use std::pin::Pin;
513    use std::marker::Unpin;
514    use std::fmt;
515    use std::ops::{Deref, Index};
516    use std::cmp::{Ord, Ordering};
517    use std::hash::{Hash, Hasher};
518    use std::collections::BTreeMap;
519    use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
520    use std::task::{Poll, Context};
521    use futures_channel::mpsc;
522    use futures_util::stream::StreamExt;
523    use crate::signal_vec::{SignalVec, VecDiff};
524
525
526    #[derive(Debug)]
527    struct MutableBTreeState<K, V> {
528        values: BTreeMap<K, V>,
529        senders: Vec<mpsc::UnboundedSender<MapDiff<K, V>>>,
530    }
531
532    impl<K: Ord, V> MutableBTreeState<K, V> {
533        // TODO should this inline ?
534        #[inline]
535        fn notify<B: FnMut() -> MapDiff<K, V>>(&mut self, mut change: B) {
536            self.senders.retain(|sender| {
537                sender.unbounded_send(change()).is_ok()
538            });
539        }
540
541        // If there is only 1 sender then it won't clone at all.
542        // If there is more than 1 sender then it will clone N-1 times.
543        // TODO verify that this works correctly
544        #[inline]
545        fn notify_clone<A, F>(&mut self, value: Option<A>, mut f: F) where A: Clone, F: FnMut(A) -> MapDiff<K, V> {
546            if let Some(value) = value {
547                let mut len = self.senders.len();
548
549                if len > 0 {
550                    let mut copy = Some(value);
551
552                    self.senders.retain(move |sender| {
553                        let value = copy.take().unwrap();
554
555                        len -= 1;
556
557                        // This isn't the last element
558                        if len != 0 {
559                            copy = Some(value.clone());
560                        }
561
562                        sender.unbounded_send(f(value)).is_ok()
563                    });
564                }
565            }
566        }
567
568        #[inline]
569        fn change<A, F>(&self, f: F) -> Option<A> where F: FnOnce() -> A {
570            if self.senders.is_empty() {
571                None
572
573            } else {
574                Some(f())
575            }
576        }
577
578        fn clear(&mut self) {
579            if !self.values.is_empty() {
580                self.values.clear();
581
582                self.notify(|| MapDiff::Clear {});
583            }
584        }
585    }
586
587    impl<K: Ord + Clone, V> MutableBTreeState<K, V> {
588        fn remove(&mut self, key: &K) -> Option<V> {
589            let value = self.values.remove(key)?;
590
591            let key = self.change(|| key.clone());
592            self.notify_clone(key, |key| MapDiff::Remove { key });
593
594            Some(value)
595        }
596    }
597
598    impl<K: Clone + Ord, V: Clone> MutableBTreeState<K, V> {
599        fn entries_cloned(values: &BTreeMap<K, V>) -> Vec<(K, V)> {
600            values.into_iter().map(|(k, v)| {
601                (k.clone(), v.clone())
602            }).collect()
603        }
604
605        fn replace_cloned(&mut self, values: BTreeMap<K, V>) {
606            let entries = self.change(|| Self::entries_cloned(&values));
607
608            self.values = values;
609
610            self.notify_clone(entries, |entries| MapDiff::Replace { entries });
611        }
612
613        fn insert_cloned(&mut self, key: K, value: V) -> Option<V> {
614            let x = self.change(|| (key.clone(), value.clone()));
615
616            if let Some(value) = self.values.insert(key, value) {
617                self.notify_clone(x, |(key, value)| MapDiff::Update { key, value });
618                Some(value)
619
620            } else {
621                self.notify_clone(x, |(key, value)| MapDiff::Insert { key, value });
622                None
623            }
624        }
625
626        fn signal_map_cloned(&mut self) -> MutableSignalMap<K, V> {
627            let (sender, receiver) = mpsc::unbounded();
628
629            if !self.values.is_empty() {
630                sender.unbounded_send(MapDiff::Replace {
631                    entries: Self::entries_cloned(&self.values),
632                }).unwrap();
633            }
634
635            self.senders.push(sender);
636
637            MutableSignalMap {
638                receiver
639            }
640        }
641    }
642
643    impl<K: Copy + Ord, V: Copy> MutableBTreeState<K, V> {
644        fn entries(values: &BTreeMap<K, V>) -> Vec<(K, V)> {
645            values.into_iter().map(|(k, v)| {
646                (*k, *v)
647            }).collect()
648        }
649
650        fn replace(&mut self, values: BTreeMap<K, V>) {
651            let entries = self.change(|| Self::entries(&values));
652
653            self.values = values;
654
655            self.notify_clone(entries, |entries| MapDiff::Replace { entries });
656        }
657
658        fn insert(&mut self, key: K, value: V) -> Option<V> {
659            if let Some(old_value) = self.values.insert(key, value) {
660                self.notify(|| MapDiff::Update { key, value });
661                Some(old_value)
662
663            } else {
664                self.notify(|| MapDiff::Insert { key, value });
665                None
666            }
667        }
668
669        fn signal_map(&mut self) -> MutableSignalMap<K, V> {
670            let (sender, receiver) = mpsc::unbounded();
671
672            if !self.values.is_empty() {
673                sender.unbounded_send(MapDiff::Replace {
674                    entries: Self::entries(&self.values),
675                }).unwrap();
676            }
677
678            self.senders.push(sender);
679
680            MutableSignalMap {
681                receiver
682            }
683        }
684    }
685
686
687    macro_rules! make_shared {
688        ($t:ty) => {
689            impl<'a, K, V> PartialEq<BTreeMap<K, V>> for $t where K: PartialEq<K>, V: PartialEq<V> {
690                #[inline] fn eq(&self, other: &BTreeMap<K, V>) -> bool { **self == *other }
691                #[inline] fn ne(&self, other: &BTreeMap<K, V>) -> bool { **self != *other }
692            }
693
694            impl<'a, K, V> PartialEq<$t> for $t where K: PartialEq<K>, V: PartialEq<V> {
695                #[inline] fn eq(&self, other: &$t) -> bool { *self == **other }
696                #[inline] fn ne(&self, other: &$t) -> bool { *self != **other }
697            }
698
699            impl<'a, K, V> Eq for $t where K: Eq, V: Eq {}
700
701            impl<'a, K, V> PartialOrd<BTreeMap<K, V>> for $t where K: PartialOrd<K>, V: PartialOrd<V> {
702                #[inline]
703                fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
704                    PartialOrd::partial_cmp(&**self, &*other)
705                }
706            }
707
708            impl<'a, K, V> PartialOrd<$t> for $t where K: PartialOrd<K>, V: PartialOrd<V> {
709                #[inline]
710                fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
711                    PartialOrd::partial_cmp(&**self, &**other)
712                }
713            }
714
715            impl<'a, K, V> Ord for $t where K: Ord, V: Ord {
716                #[inline]
717                fn cmp(&self, other: &Self) -> Ordering {
718                    Ord::cmp(&**self, &**other)
719                }
720            }
721
722            impl<'a, 'b, K, V> Index<&'b K> for $t where K: Ord {
723                type Output = V;
724
725                #[inline]
726                fn index(&self, key: &'b K) -> &Self::Output {
727                    Index::index(&**self, key)
728                }
729            }
730
731            impl<'a, K, V> Deref for $t {
732                type Target = BTreeMap<K, V>;
733
734                #[inline]
735                fn deref(&self) -> &Self::Target {
736                    &self.lock.values
737                }
738            }
739
740            impl<'a, K, V> Hash for $t where K: Hash, V: Hash {
741                #[inline]
742                fn hash<H>(&self, state: &mut H) where H: Hasher {
743                    Hash::hash(&**self, state)
744                }
745            }
746        };
747    }
748
749
750    #[derive(Debug)]
751    pub struct MutableBTreeMapLockRef<'a, K, V> where K: 'a, V: 'a {
752        lock: RwLockReadGuard<'a, MutableBTreeState<K, V>>,
753    }
754
755    make_shared!(MutableBTreeMapLockRef<'a, K, V>);
756
757
758    #[derive(Debug)]
759    pub struct MutableBTreeMapLockMut<'a, K, V> where K: 'a, V: 'a {
760        lock: RwLockWriteGuard<'a, MutableBTreeState<K, V>>,
761    }
762
763    make_shared!(MutableBTreeMapLockMut<'a, K, V>);
764
765    impl<'a, K, V> MutableBTreeMapLockMut<'a, K, V> where K: Ord {
766        #[inline]
767        pub fn clear(&mut self) {
768            self.lock.clear()
769        }
770    }
771
772    impl<'a, K, V> MutableBTreeMapLockMut<'a, K, V> where K: Ord + Clone {
773        #[inline]
774        pub fn remove(&mut self, key: &K) -> Option<V> {
775            self.lock.remove(key)
776        }
777    }
778
779    impl<'a, K, V> MutableBTreeMapLockMut<'a, K, V> where K: Ord + Clone, V: Clone {
780        #[inline]
781        pub fn replace_cloned(&mut self, values: BTreeMap<K, V>) {
782            self.lock.replace_cloned(values)
783        }
784
785        #[inline]
786        pub fn insert_cloned(&mut self, key: K, value: V) -> Option<V> {
787            self.lock.insert_cloned(key, value)
788        }
789    }
790
791    impl<'a, K, V> MutableBTreeMapLockMut<'a, K, V> where K: Ord + Copy, V: Copy {
792        #[inline]
793        pub fn replace(&mut self, values: BTreeMap<K, V>) {
794            self.lock.replace(values)
795        }
796
797        #[inline]
798        pub fn insert(&mut self, key: K, value: V) -> Option<V> {
799            self.lock.insert(key, value)
800        }
801    }
802
803
804    // TODO get rid of the Arc
805    // TODO impl some of the same traits as BTreeMap
806    pub struct MutableBTreeMap<K, V>(Arc<RwLock<MutableBTreeState<K, V>>>);
807
808    impl<K, V> MutableBTreeMap<K, V> {
809        // TODO deprecate this and replace with From ?
810        #[inline]
811        pub fn with_values(values: BTreeMap<K, V>) -> Self {
812            Self::from(values)
813        }
814
815        // TODO return Result ?
816        #[inline]
817        pub fn lock_ref(&self) -> MutableBTreeMapLockRef<K, V> {
818            MutableBTreeMapLockRef {
819                lock: self.0.read().unwrap(),
820            }
821        }
822
823        // TODO return Result ?
824        #[inline]
825        pub fn lock_mut(&self) -> MutableBTreeMapLockMut<K, V> {
826            MutableBTreeMapLockMut {
827                lock: self.0.write().unwrap(),
828            }
829        }
830    }
831
832    impl<K, V> MutableBTreeMap<K, V> where K: Ord {
833        #[inline]
834        pub fn new() -> Self {
835            Self::with_values(BTreeMap::new())
836        }
837    }
838
839    impl<T, K, V> From<T> for MutableBTreeMap<K, V> where BTreeMap<K, V>: From<T> {
840        #[inline]
841        fn from(values: T) -> Self {
842            Self(Arc::new(RwLock::new(MutableBTreeState {
843                values: values.into(),
844                senders: vec![],
845            })))
846        }
847    }
848
849    impl<K, V> MutableBTreeMap<K, V> where K: Ord + Clone, V: Clone {
850        #[inline]
851        pub fn signal_map_cloned(&self) -> MutableSignalMap<K, V> {
852            self.0.write().unwrap().signal_map_cloned()
853        }
854
855        // TODO deprecate and rename to keys_cloned
856        // TODO replace with MutableBTreeMapKeysCloned
857        #[inline]
858        pub fn signal_vec_keys(&self) -> MutableBTreeMapKeys<K, V> {
859            MutableBTreeMapKeys {
860                signal: self.signal_map_cloned(),
861                keys: vec![],
862            }
863        }
864
865        // TODO replace with MutableBTreeMapEntriesCloned
866        #[inline]
867        pub fn entries_cloned(&self) -> MutableBTreeMapEntries<K, V> {
868            MutableBTreeMapEntries {
869                signal: self.signal_map_cloned(),
870                keys: vec![],
871            }
872        }
873    }
874
875    impl<K, V> MutableBTreeMap<K, V> where K: Ord + Copy, V: Copy {
876        #[inline]
877        pub fn signal_map(&self) -> MutableSignalMap<K, V> {
878            self.0.write().unwrap().signal_map()
879        }
880
881        // TODO deprecate and rename to entries
882        #[inline]
883        pub fn signal_vec_entries(&self) -> MutableBTreeMapEntries<K, V> {
884            MutableBTreeMapEntries {
885                signal: self.signal_map(),
886                keys: vec![],
887            }
888        }
889    }
890
891    impl<K, V> fmt::Debug for MutableBTreeMap<K, V> where K: fmt::Debug, V: fmt::Debug {
892        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
893            let state = self.0.read().unwrap();
894
895            fmt.debug_tuple("MutableBTreeMap")
896                .field(&state.values)
897                .finish()
898        }
899    }
900
901    #[cfg(feature = "serde")]
902    impl<K, V> serde::Serialize for MutableBTreeMap<K, V> where BTreeMap<K, V>: serde::Serialize {
903        #[inline]
904        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
905            self.0.read().unwrap().values.serialize(serializer)
906        }
907    }
908
909    #[cfg(feature = "serde")]
910    impl<'de, K, V> serde::Deserialize<'de> for MutableBTreeMap<K, V> where BTreeMap<K, V>: serde::Deserialize<'de> {
911        #[inline]
912        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
913            <BTreeMap<K, V>>::deserialize(deserializer).map(MutableBTreeMap::with_values)
914        }
915    }
916
917    impl<K, V> Default for MutableBTreeMap<K, V> where K: Ord {
918        #[inline]
919        fn default() -> Self {
920            MutableBTreeMap::new()
921        }
922    }
923
924    impl<K, V> Clone for MutableBTreeMap<K, V> {
925        #[inline]
926        fn clone(&self) -> Self {
927            MutableBTreeMap(self.0.clone())
928        }
929    }
930
931    #[derive(Debug)]
932    #[must_use = "SignalMaps do nothing unless polled"]
933    pub struct MutableSignalMap<K, V> {
934        receiver: mpsc::UnboundedReceiver<MapDiff<K, V>>,
935    }
936
937    impl<K, V> Unpin for MutableSignalMap<K, V> {}
938
939    impl<K, V> SignalMap for MutableSignalMap<K, V> {
940        type Key = K;
941        type Value = V;
942
943        #[inline]
944        fn poll_map_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<MapDiff<Self::Key, Self::Value>>> {
945            self.receiver.poll_next_unpin(cx)
946        }
947    }
948
949
950    #[derive(Debug)]
951    #[must_use = "SignalVecs do nothing unless polled"]
952    pub struct MutableBTreeMapKeys<K, V> {
953        signal: MutableSignalMap<K, V>,
954        keys: Vec<K>,
955    }
956
957    impl<K, V> Unpin for MutableBTreeMapKeys<K, V> {}
958
959    impl<K, V> SignalVec for MutableBTreeMapKeys<K, V> where K: Ord + Clone {
960        type Item = K;
961
962        #[inline]
963        fn poll_vec_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<VecDiff<Self::Item>>> {
964            loop {
965                return match self.signal.poll_map_change_unpin(cx) {
966                    Poll::Ready(Some(diff)) => match diff {
967                        MapDiff::Replace { entries } => {
968                            // TODO verify that it is in sorted order ?
969                            self.keys = entries.into_iter().map(|(k, _)| k).collect();
970                            Poll::Ready(Some(VecDiff::Replace { values: self.keys.clone() }))
971                        },
972                        MapDiff::Insert { key, value: _ } => {
973                            let index = self.keys.binary_search(&key).unwrap_err();
974                            self.keys.insert(index, key.clone());
975                            Poll::Ready(Some(VecDiff::InsertAt { index, value: key }))
976                        },
977                        MapDiff::Update { .. } => {
978                            continue;
979                        },
980                        MapDiff::Remove { key } => {
981                            let index = self.keys.binary_search(&key).unwrap();
982                            self.keys.remove(index);
983                            Poll::Ready(Some(VecDiff::RemoveAt { index }))
984                        },
985                        MapDiff::Clear {} => {
986                            self.keys.clear();
987                            Poll::Ready(Some(VecDiff::Clear {}))
988                        },
989                    },
990                    Poll::Ready(None) => Poll::Ready(None),
991                    Poll::Pending => Poll::Pending,
992                };
993            }
994        }
995    }
996
997
998    #[derive(Debug)]
999    #[must_use = "SignalVecs do nothing unless polled"]
1000    pub struct MutableBTreeMapEntries<K, V> {
1001        signal: MutableSignalMap<K, V>,
1002        keys: Vec<K>,
1003    }
1004
1005    impl<K, V> Unpin for MutableBTreeMapEntries<K, V> {}
1006
1007    impl<K, V> SignalVec for MutableBTreeMapEntries<K, V> where K: Ord + Clone {
1008        type Item = (K, V);
1009
1010        #[inline]
1011        fn poll_vec_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<VecDiff<Self::Item>>> {
1012            self.signal.poll_map_change_unpin(cx).map(|opt| opt.map(|diff| {
1013                match diff {
1014                    MapDiff::Replace { entries } => {
1015                        // TODO verify that it is in sorted order ?
1016                        self.keys = entries.iter().map(|(k, _)| k.clone()).collect();
1017                        VecDiff::Replace { values: entries }
1018                    },
1019                    MapDiff::Insert { key, value } => {
1020                        let index = self.keys.binary_search(&key).unwrap_err();
1021                        self.keys.insert(index, key.clone());
1022                        VecDiff::InsertAt { index, value: (key, value) }
1023                    },
1024                    MapDiff::Update { key, value } => {
1025                        let index = self.keys.binary_search(&key).unwrap();
1026                        VecDiff::UpdateAt { index, value: (key, value) }
1027                    },
1028                    MapDiff::Remove { key } => {
1029                        let index = self.keys.binary_search(&key).unwrap();
1030                        self.keys.remove(index);
1031                        VecDiff::RemoveAt { index }
1032                    },
1033                    MapDiff::Clear {} => {
1034                        self.keys.clear();
1035                        VecDiff::Clear {}
1036                    },
1037                }
1038            }))
1039        }
1040    }
1041}
1042
1043pub use self::mutable_btree_map::*;