Skip to main content

ds_ext/
map.rs

1//! A hash map ordered by key using an ordered hash set
2
3use std::borrow::Borrow;
4use std::cmp::Ordering;
5use std::collections::{hash_map, HashMap as Inner};
6use std::fmt;
7use std::hash::Hash;
8use std::mem;
9use std::sync::Arc;
10
11use get_size::GetSize;
12use get_size_derive::*;
13
14use super::set::OrdHashSet;
15
16/// An iterator removing entries as they are consumed. Dropping it restores the remainder.
17pub struct Drain<'a, K, V> {
18    target_inner: &'a mut Inner<Arc<K>, V>,
19    inner: Inner<Arc<K>, V>,
20    order: super::set::Drain<'a, Arc<K>>,
21}
22
23impl<K, V> Drop for Drain<'_, K, V> {
24    fn drop(&mut self) {
25        *self.target_inner = mem::take(&mut self.inner);
26        // The embedded set drain restores the remaining ordering on field drop.
27    }
28}
29
30impl<'a, K: Eq + Hash + fmt::Debug, V> Drain<'a, K, V> {
31    fn next_entry(&mut self, key: Arc<K>) -> Option<(K, V)> {
32        let value = self.inner.remove(&*key).expect("value");
33        let key = Arc::try_unwrap(key).expect("key");
34        Some((key, value))
35    }
36}
37
38impl<'a, K: Eq + Hash + fmt::Debug, V> Iterator for Drain<'a, K, V> {
39    type Item = (K, V);
40
41    fn next(&mut self) -> Option<Self::Item> {
42        let key = self.order.next()?;
43        self.next_entry(key)
44    }
45
46    fn size_hint(&self) -> (usize, Option<usize>) {
47        self.order.size_hint()
48    }
49}
50
51impl<'a, K: Eq + Hash + fmt::Debug, V> DoubleEndedIterator for Drain<'a, K, V> {
52    fn next_back(&mut self) -> Option<Self::Item> {
53        let key = self.order.next_back()?;
54        self.next_entry(key)
55    }
56}
57
58/// An iterator to drain the contents of an [`OrdHashMap`] conditionally
59pub struct DrainWhile<'a, K, V, Cond> {
60    inner: &'a mut Inner<Arc<K>, V>,
61    order: &'a mut OrdHashSet<Arc<K>>,
62    cond: Cond,
63}
64
65impl<'a, K, V, Cond> Iterator for DrainWhile<'a, K, V, Cond>
66where
67    K: Eq + Hash + Ord + fmt::Debug,
68    Cond: Fn((&K, &V)) -> bool,
69{
70    type Item = (K, V);
71
72    fn next(&mut self) -> Option<Self::Item> {
73        let should_drain = {
74            let key = self.order.first()?;
75            let value = self.inner.get(&**key).expect("value");
76            (self.cond)((&**key, value))
77        };
78
79        if should_drain {
80            let key = self.order.pop_first().expect("key");
81            let value = self.inner.remove(&*key).expect("value");
82            let key = Arc::try_unwrap(key).expect("key");
83            Some((key, value))
84        } else {
85            None
86        }
87    }
88
89    fn size_hint(&self) -> (usize, Option<usize>) {
90        (0, Some(self.inner.len()))
91    }
92}
93
94/// An iterator over the contents of an [`OrdHashMap`]
95pub struct IntoIter<K, V> {
96    inner: Inner<Arc<K>, V>,
97    order: super::set::IntoIter<Arc<K>>,
98}
99
100impl<K: Eq + Hash + fmt::Debug, V> IntoIter<K, V> {
101    fn next_entry(&mut self, key: Arc<K>) -> Option<(K, V)> {
102        let value = self.inner.remove(&*key).expect("value");
103        let key = Arc::try_unwrap(key).expect("key");
104        Some((key, value))
105    }
106}
107
108impl<K: Eq + Hash + fmt::Debug, V> Iterator for IntoIter<K, V> {
109    type Item = (K, V);
110
111    fn next(&mut self) -> Option<Self::Item> {
112        let key = self.order.next()?;
113        self.next_entry(key)
114    }
115
116    fn size_hint(&self) -> (usize, Option<usize>) {
117        self.order.size_hint()
118    }
119}
120
121impl<K: Eq + Hash + fmt::Debug, V> DoubleEndedIterator for IntoIter<K, V> {
122    fn next_back(&mut self) -> Option<Self::Item> {
123        let key = self.order.next_back()?;
124        self.next_entry(key)
125    }
126}
127
128/// An iterator over the entries in an [`OrdHashMap`]
129pub struct Iter<'a, K, V> {
130    inner: &'a Inner<Arc<K>, V>,
131    order: super::set::Iter<'a, Arc<K>>,
132}
133
134impl<'a, K: Eq + Hash + fmt::Debug, V> Iterator for Iter<'a, K, V> {
135    type Item = (&'a K, &'a V);
136
137    fn next(&mut self) -> Option<Self::Item> {
138        let key = &**self.order.next()?;
139        let (key, value) = self.inner.get_key_value(key).expect("entry");
140        Some((&**key, value))
141    }
142
143    fn size_hint(&self) -> (usize, Option<usize>) {
144        self.order.size_hint()
145    }
146}
147
148impl<'a, K: Eq + Hash + fmt::Debug, V> DoubleEndedIterator for Iter<'a, K, V> {
149    fn next_back(&mut self) -> Option<Self::Item> {
150        let key = self.order.next_back()?;
151        let (key, value) = self.inner.get_key_value(&**key).expect("entry");
152        Some((&**key, value))
153    }
154}
155
156/// An iterator over the keys in an [`OrdHashMap`]
157pub struct Keys<'a, K, V> {
158    inner: &'a Inner<Arc<K>, V>,
159    order: super::set::Iter<'a, Arc<K>>,
160}
161
162impl<'a, K: Eq + Hash + fmt::Debug, V> Iterator for Keys<'a, K, V> {
163    type Item = &'a K;
164
165    fn next(&mut self) -> Option<Self::Item> {
166        let key = self.order.next()?;
167        let (key, _) = self.inner.get_key_value(&**key).expect("entry");
168        Some(&**key)
169    }
170
171    fn size_hint(&self) -> (usize, Option<usize>) {
172        self.order.size_hint()
173    }
174}
175
176impl<'a, K: Eq + Hash + fmt::Debug, V> DoubleEndedIterator for Keys<'a, K, V> {
177    fn next_back(&mut self) -> Option<Self::Item> {
178        let key = self.order.next_back()?;
179        let (key, _) = self.inner.get_key_value(&**key).expect("entry");
180        Some(&**key)
181    }
182}
183
184/// An owned iterator over the values in an [`OrdHashMap`]
185pub struct IntoValues<K, V> {
186    inner: Inner<Arc<K>, V>,
187    order: super::set::IntoIter<Arc<K>>,
188}
189
190impl<K: Eq + Hash + fmt::Debug, V> Iterator for IntoValues<K, V> {
191    type Item = V;
192
193    fn next(&mut self) -> Option<Self::Item> {
194        let key = self.order.next()?;
195        self.inner.remove(&*key)
196    }
197
198    fn size_hint(&self) -> (usize, Option<usize>) {
199        self.order.size_hint()
200    }
201}
202
203impl<K: Eq + Hash + fmt::Debug, V> DoubleEndedIterator for IntoValues<K, V> {
204    fn next_back(&mut self) -> Option<Self::Item> {
205        let key = self.order.next_back()?;
206        self.inner.remove(&*key)
207    }
208}
209
210/// An iterator over the values in an [`OrdHashMap`]
211pub struct Values<'a, K, V> {
212    inner: &'a Inner<Arc<K>, V>,
213    order: super::set::Iter<'a, Arc<K>>,
214}
215
216impl<'a, K: Eq + Hash + fmt::Debug, V> Iterator for Values<'a, K, V> {
217    type Item = &'a V;
218
219    fn next(&mut self) -> Option<Self::Item> {
220        let key = self.order.next()?;
221        self.inner.get(&**key)
222    }
223
224    fn size_hint(&self) -> (usize, Option<usize>) {
225        self.order.size_hint()
226    }
227}
228
229impl<'a, K: Eq + Hash + fmt::Debug, V> DoubleEndedIterator for Values<'a, K, V> {
230    fn next_back(&mut self) -> Option<Self::Item> {
231        let key = self.order.next_back()?;
232        self.inner.get(&**key)
233    }
234}
235
236/// An occupied entry whose mutations keep the ordering index synchronized.
237pub struct OccupiedEntry<'a, K, V> {
238    order: &'a mut OrdHashSet<Arc<K>>,
239    entry: hash_map::OccupiedEntry<'a, Arc<K>, V>,
240}
241
242impl<'a, K, V> OccupiedEntry<'a, K, V> {
243    /// Borrow this entry's key without exposing its internal shared owner.
244    pub fn key(&self) -> &K {
245        self.entry.key()
246    }
247
248    /// Borrow this entry's value.
249    pub fn get(&self) -> &V {
250        self.entry.get()
251    }
252
253    /// Borrow this entry's value mutably.
254    pub fn get_mut(&mut self) -> &mut V {
255        self.entry.get_mut()
256    }
257
258    /// Consume the entry and borrow its value mutably.
259    pub fn into_mut(self) -> &'a mut V {
260        self.entry.into_mut()
261    }
262
263    /// Replace the value and return the previous value.
264    pub fn insert(&mut self, value: V) -> V {
265        self.entry.insert(value)
266    }
267}
268
269impl<K: Eq + Hash + Ord, V> OccupiedEntry<'_, K, V> {
270    /// Remove the entry from both indexes and return its value.
271    pub fn remove(self) -> V {
272        let (key, value) = self.entry.remove_entry();
273        assert!(self.order.remove(&key));
274        value
275    }
276}
277
278impl<K: Eq + Hash + Ord + fmt::Debug, V> OccupiedEntry<'_, K, V> {
279    /// Remove the entry from both indexes and return its key and value.
280    pub fn remove_entry(self) -> (K, V) {
281        let (key, value) = self.entry.remove_entry();
282        assert!(self.order.remove(&key));
283        (Arc::try_unwrap(key).expect("key"), value)
284    }
285}
286
287/// A vacant entry in an [`OrdHashMap`]
288pub struct VacantEntry<'a, K, V> {
289    order: &'a mut OrdHashSet<Arc<K>>,
290    entry: hash_map::VacantEntry<'a, Arc<K>, V>,
291}
292
293impl<'a, K, V> VacantEntry<'a, K, V>
294where
295    K: Eq + Hash + Ord,
296{
297    /// Create a new entry with the given `value`
298    pub fn insert(self, value: V) -> &'a mut V {
299        self.order.insert(self.entry.key().clone());
300        self.entry.insert(value)
301    }
302}
303
304/// An entry in an [`OrdHashMap`]
305pub enum Entry<'a, K, V> {
306    Occupied(OccupiedEntry<'a, K, V>),
307    Vacant(VacantEntry<'a, K, V>),
308}
309
310/// A `HashMap` ordered by key using a [`OrdHashSet`]
311#[derive(GetSize)]
312pub struct OrdHashMap<K, V> {
313    inner: Inner<Arc<K>, V>,
314    order: OrdHashSet<Arc<K>>,
315}
316
317impl<K: Clone + Eq + Hash + Ord + fmt::Debug, V: Clone> Clone for OrdHashMap<K, V> {
318    fn clone(&self) -> Self {
319        let mut inner = Inner::with_capacity(self.inner.capacity());
320        let mut order = OrdHashSet::<Arc<K>>::with_capacity(inner.capacity());
321
322        for key in &self.order {
323            let key = Arc::new(K::clone(&**key));
324            let value = self.inner.get(&key).cloned().expect("value");
325            inner.insert(key.clone(), value);
326            order.insert(key);
327        }
328
329        Self { inner, order }
330    }
331}
332
333impl<K, V> OrdHashMap<K, V> {
334    /// Construct a new [`OrdHashMap`].
335    pub fn new() -> Self {
336        Self {
337            inner: Inner::new(),
338            order: OrdHashSet::new(),
339        }
340    }
341
342    /// Construct a new [`OrdHashMap`] with the given `capacity`.
343    pub fn with_capacity(capacity: usize) -> Self {
344        Self {
345            inner: Inner::with_capacity(capacity),
346            order: OrdHashSet::with_capacity(capacity),
347        }
348    }
349
350    /// Return the size of this [`OrdHashMap`].
351    pub fn len(&self) -> usize {
352        self.inner.len()
353    }
354}
355
356impl<K, V> Default for OrdHashMap<K, V> {
357    fn default() -> Self {
358        Self::new()
359    }
360}
361
362impl<K: Eq + Hash + Ord, V> OrdHashMap<K, V> {
363    /// Bisect this map to match a key using the provided comparison, and return its value (if any).
364    ///
365    /// The first key for which the comparison returns `Some(Ordering::Equal)` will be returned.
366    /// The comparison is target-relative: `Greater` skips smaller keys. Its defined
367    /// results must be monotone, with incomparable keys only at the edges. Search
368    /// takes O(p + s + log n), where p and s are incomparable edge lengths.
369    pub fn bisect<Cmp>(&self, cmp: Cmp) -> Option<&V>
370    where
371        Cmp: Fn(&K) -> Option<Ordering> + Copy,
372    {
373        self.order
374            .bisect(|key| cmp(key))
375            .map(|key| self.get(&**key).expect("value"))
376    }
377
378    /// Remove all entries from this [`OrdHashMap`].
379    pub fn clear(&mut self) {
380        self.inner.clear();
381        self.order.clear();
382    }
383
384    /// Return `true` if there is an entry for the given `key` in this [`OrdHashMap`].
385    pub fn contains_key<Q>(&self, key: &Q) -> bool
386    where
387        Arc<K>: Borrow<Q>,
388        Q: Eq + Hash + ?Sized,
389    {
390        self.inner.contains_key(key)
391    }
392
393    /// Remove entries as they are consumed, preserving unconsumed entries on drop.
394    /// Forgetting the iterator leaves the map empty.
395    pub fn drain(&mut self) -> Drain<'_, K, V> {
396        let inner = mem::take(&mut self.inner);
397        Drain {
398            target_inner: &mut self.inner,
399            inner,
400            order: self.order.drain(),
401        }
402    }
403
404    /// Remove leading entries while they match the condition.
405    pub fn drain_while<Cond>(&mut self, cond: Cond) -> DrainWhile<'_, K, V, Cond>
406    where
407        Cond: Fn((&K, &V)) -> bool,
408    {
409        DrainWhile {
410            inner: &mut self.inner,
411            order: &mut self.order,
412            cond,
413        }
414    }
415
416    /// Return a mutable [`Entry`] for an owned key without exposing shared key ownership.
417    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
418        match self.inner.entry(Arc::new(key)) {
419            hash_map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry {
420                entry,
421                order: &mut self.order,
422            }),
423            hash_map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry {
424                entry,
425                order: &mut self.order,
426            }),
427        }
428    }
429
430    /// Consume `iter` and insert all its elements into this [`OrdHashMap`].
431    pub fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
432        for (key, value) in iter {
433            self.insert(key, value);
434        }
435    }
436
437    /// Borrow the first value in this [`OrdHashMap`].
438    pub fn first(&self) -> Option<&V> {
439        let key = self.order.first()?;
440        self.inner.get(&**key)
441    }
442
443    /// Borrow the first value in this [`OrdHashMap`] mutably.
444    pub fn first_mut(&mut self) -> Option<&mut V> {
445        let key = self.order.first()?;
446        self.inner.get_mut(&**key)
447    }
448
449    /// Borrow the value at the given `key`, if present.
450    pub fn get<Q>(&self, key: &Q) -> Option<&V>
451    where
452        Arc<K>: Borrow<Q>,
453        Q: Eq + Hash + ?Sized,
454    {
455        self.inner.get(key)
456    }
457
458    /// Borrow the entry at the given `key`, if present.
459    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
460    where
461        Arc<K>: Borrow<Q>,
462        Q: Eq + Hash + ?Sized,
463    {
464        self.inner
465            .get_key_value(key)
466            .map(|(key, value)| (&**key, value))
467    }
468
469    /// Borrow the value at the given `key` mutably, if present.
470    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
471    where
472        Arc<K>: Borrow<Q>,
473        Q: Eq + Hash + ?Sized,
474    {
475        self.inner.get_mut(key)
476    }
477
478    /// Insert a new `value` at `key` and return the previous value, if any.
479    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
480        let key = Arc::new(key);
481        self.order.insert(key.clone());
482        self.inner.insert(key, value)
483    }
484
485    /// Construct an iterator over the entries in this [`OrdHashMap`].
486    pub fn iter(&self) -> Iter<'_, K, V> {
487        Iter {
488            inner: &self.inner,
489            order: self.order.iter(),
490        }
491    }
492
493    /// Return `true` if this [`OrdHashMap`] is empty.
494    pub fn is_empty(&self) -> bool {
495        self.inner.is_empty()
496    }
497
498    /// Construct an iterator over keys of this [`OrdHashMap`].
499    pub fn keys(&self) -> Keys<'_, K, V> {
500        Keys {
501            inner: &self.inner,
502            order: self.order.iter(),
503        }
504    }
505
506    /// Borrow the last value in this [`OrdHashMap`].
507    pub fn last(&self) -> Option<&V> {
508        let key = self.order.last()?;
509        self.inner.get(&**key)
510    }
511
512    /// Borrow the last value in this [`OrdHashMap`] mutably.
513    pub fn last_mut(&mut self) -> Option<&mut V> {
514        let key = self.order.last()?;
515        self.inner.get_mut(&**key)
516    }
517
518    /// Remove and return the first value in this [`OrdHashMap`].
519    pub fn pop_first(&mut self) -> Option<V>
520    where
521        K: fmt::Debug,
522    {
523        let key = self.order.pop_first()?;
524        self.inner.remove(&*key)
525    }
526
527    /// Remove and return the last value in this [`OrdHashMap`].
528    pub fn pop_last(&mut self) -> Option<V>
529    where
530        K: fmt::Debug,
531    {
532        let key = self.order.pop_last()?;
533        self.inner.remove(&*key)
534    }
535
536    /// Remove an entry from this [`OrdHashMap`] and return its value, if present.
537    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
538    where
539        Arc<K>: Borrow<Q>,
540        Q: Hash + Eq + ?Sized,
541    {
542        let (key, value) = self.inner.remove_entry(key)?;
543        assert!(self.order.remove(&key));
544        Some(value)
545    }
546
547    /// Return `true` if the first elements in this [`OrdHashMap`] equal those in the given `iter`.
548    pub fn starts_with<'a, I: IntoIterator<Item = (&'a K, &'a V)>>(&self, other: I) -> bool
549    where
550        K: fmt::Debug + 'a,
551        V: PartialEq + 'a,
552    {
553        let mut this = self.iter();
554        let that = other.into_iter();
555
556        for item in that {
557            if this.next() != Some(item) {
558                return false;
559            }
560        }
561
562        true
563    }
564
565    /// Construct an owned iterator over the values in this [`OrdHashMap`].
566    pub fn into_values(self) -> IntoValues<K, V>
567    where
568        K: fmt::Debug,
569    {
570        IntoValues {
571            inner: self.inner,
572            order: self.order.into_iter(),
573        }
574    }
575
576    /// Construct an iterator over the values in this [`OrdHashMap`].
577    pub fn values(&self) -> Values<'_, K, V> {
578        Values {
579            inner: &self.inner,
580            order: self.order.iter(),
581        }
582    }
583}
584
585impl<K: Eq + Hash + Ord + fmt::Debug, V> OrdHashMap<K, V> {
586    /// Bisect this map to match and remove an entry using the provided comparison.
587    ///
588    /// The first key for which the comparison returns `Some(Ordering::Equal)` will be returned.
589    /// The comparison is target-relative: `Greater` skips smaller keys. Its defined
590    /// results must be monotone, with incomparable keys only at the edges. Search
591    /// takes O(p + s + log n), where p and s are incomparable edge lengths.
592    pub fn bisect_and_remove<Cmp>(&mut self, cmp: Cmp) -> Option<(K, V)>
593    where
594        Cmp: Fn(&K) -> Option<Ordering> + Copy,
595    {
596        let key = self.order.bisect_and_remove(|key| cmp(key))?;
597        let value = self.inner.remove(&*key).expect("value");
598        let key = Arc::try_unwrap(key).expect("key");
599        Some((key, value))
600    }
601
602    /// Remove and return the first entry in this [`OrdHashMap`].
603    pub fn pop_first_entry(&mut self) -> Option<(K, V)> {
604        let key = self.order.pop_first()?;
605        let value = self.inner.remove(&*key).expect("entry");
606        let key = Arc::try_unwrap(key).expect("key");
607        Some((key, value))
608    }
609
610    /// Remove and return the last entry in this [`OrdHashMap`].
611    pub fn pop_last_entry(&mut self) -> Option<(K, V)> {
612        let key = self.order.pop_last()?;
613        let value = self.inner.remove(&*key).expect("entry");
614        let key = Arc::try_unwrap(key).expect("key");
615        Some((key, value))
616    }
617
618    /// Remove and return an entry from this [`OrdHashMap`], if present.
619    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
620    where
621        Arc<K>: Borrow<Q>,
622        Q: Hash + Eq + ?Sized,
623    {
624        let (key, value) = self.inner.remove_entry(key)?;
625        assert!(self.order.remove(&key));
626        let key = Arc::try_unwrap(key).expect("key");
627        Some((key, value))
628    }
629}
630
631impl<K: Eq + Hash + Ord + fmt::Debug, V: PartialEq> PartialEq<Self> for OrdHashMap<K, V> {
632    fn eq(&self, other: &Self) -> bool {
633        if self.len() != other.len() {
634            return false;
635        }
636
637        self.iter().eq(other.iter())
638    }
639}
640
641impl<K: Eq + Hash + Ord + fmt::Debug, V: Eq> Eq for OrdHashMap<K, V> {}
642
643impl<K: Eq + Hash + Ord + fmt::Debug, V> FromIterator<(K, V)> for OrdHashMap<K, V> {
644    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
645        let iter = iter.into_iter();
646        let mut map = match iter.size_hint() {
647            (_, Some(max)) => Self::with_capacity(max),
648            (min, None) if min > 0 => Self::with_capacity(min),
649            _ => Self::new(),
650        };
651
652        map.extend(iter);
653        map
654    }
655}
656
657impl<K: Eq + Hash + fmt::Debug, V> IntoIterator for OrdHashMap<K, V> {
658    type Item = (K, V);
659    type IntoIter = IntoIter<K, V>;
660
661    fn into_iter(self) -> Self::IntoIter {
662        IntoIter {
663            inner: self.inner,
664            order: self.order.into_iter(),
665        }
666    }
667}
668
669impl<'a, K: Ord + Eq + Hash + fmt::Debug, V> IntoIterator for &'a OrdHashMap<K, V> {
670    type Item = (&'a K, &'a V);
671    type IntoIter = Iter<'a, K, V>;
672
673    fn into_iter(self) -> Self::IntoIter {
674        self.iter()
675    }
676}
677
678impl<K: Eq + Hash + Ord + fmt::Debug, V: fmt::Debug> fmt::Debug for OrdHashMap<K, V> {
679    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680        f.write_str("{")?;
681
682        for (key, value) in self.iter() {
683            write!(f, "{:?}: {:?}, ", key, value)?;
684        }
685
686        f.write_str("}")
687    }
688}
689
690#[cfg(test)]
691#[path = "../tests/unit/map.rs"]
692mod tests;