Skip to main content

imbl_value/in_order_map/
mod.rs

1use std::{
2    borrow::Borrow,
3    cmp::Ordering,
4    fmt::{Debug, Formatter},
5    hash::{Hash, Hasher},
6    iter::Sum,
7    ops::{Add, Deref, Index, IndexMut},
8};
9
10pub mod my_visitor;
11use imbl::{shared_ptr::DefaultSharedPtr, Vector};
12use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};
13
14#[macro_export]
15macro_rules! inOMap {
16    () => { $crate::in_order_map::InOMap::new() };
17
18    ( $( $key:expr => $value:expr ),* ) => {{
19        let mut map = $crate::in_order_map::InOMap::new();
20        $({
21            map.insert($key, $value);
22        })*;
23        map
24    }};
25
26    ( $( $key:expr => $value:expr ,)* ) => {{
27        let mut map = $crate::in_order_map::InOMap::new();
28        $({
29            map.insert($key, $value);
30        })*;
31        map
32    }};
33}
34
35#[derive(Clone)]
36pub struct InOMap<K, V>
37where
38    K: Eq + Clone,
39    V: Clone,
40{
41    value: Vector<(K, V)>,
42}
43
44impl<K, V> From<Vector<(K, V)>> for InOMap<K, V>
45where
46    K: Eq + Clone,
47    V: Clone,
48{
49    fn from(value: Vector<(K, V)>) -> Self {
50        Self { value }
51    }
52}
53
54impl<K, V> From<InOMap<K, V>> for Vector<(K, V)>
55where
56    K: Eq + Clone,
57    V: Clone,
58{
59    fn from(value: InOMap<K, V>) -> Self {
60        value.value
61    }
62}
63
64impl<K, V> PartialEq for InOMap<K, V>
65where
66    K: Eq + Clone,
67    V: Eq + Clone,
68{
69    fn eq(&self, other: &Self) -> bool {
70        self.value.ptr_eq(&other.value) || self.value == other.value || {
71            self.value.len() == other.value.len() && {
72                self.value.iter().all(|(k, v)| other.get(k) == Some(v))
73            }
74        }
75    }
76}
77
78impl<K, V> Eq for InOMap<K, V>
79where
80    K: Eq + Clone,
81    V: Eq + Clone,
82{
83}
84
85impl<K, V> PartialOrd for InOMap<K, V>
86where
87    K: Eq + Ord + Clone,
88    V: Ord + Clone,
89{
90    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
91        Some(self.cmp(other))
92    }
93}
94
95impl<K, V> Ord for InOMap<K, V>
96where
97    K: Eq + Ord + Clone,
98    V: Ord + Clone,
99{
100    fn cmp(&self, other: &Self) -> Ordering {
101        let mut self_pairs: Vec<_> = self.value.iter().collect();
102        let mut other_pairs: Vec<_> = other.value.iter().collect();
103        self_pairs.sort();
104        other_pairs.sort();
105        self_pairs.cmp(&other_pairs)
106    }
107}
108
109impl<K, V> Hash for InOMap<K, V>
110where
111    K: Eq + Hash + Clone,
112    V: Hash + Clone,
113{
114    fn hash<H: Hasher>(&self, state: &mut H) {
115        self.value.len().hash(state);
116        // Order-independent hash: wrapping_add individual pair hashes
117        let mut hash = 0u64;
118        for (k, v) in self.value.iter() {
119            let mut hasher = std::collections::hash_map::DefaultHasher::new();
120            k.hash(&mut hasher);
121            v.hash(&mut hasher);
122            hash = hash.wrapping_add(hasher.finish());
123        }
124        hash.hash(state);
125    }
126}
127
128impl<K, V> Serialize for InOMap<K, V>
129where
130    K: Serialize + Eq + Clone,
131    V: Serialize + Clone,
132{
133    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
134    where
135        S: Serializer,
136    {
137        let mut map = serializer.serialize_map(Some(self.len()))?;
138        for (k, v) in self {
139            map.serialize_entry(k, v)?;
140        }
141        map.end()
142    }
143}
144
145// This is the trait that informs Serde how to deserialize MyMap.
146impl<'de, K, V> Deserialize<'de> for InOMap<K, V>
147where
148    K: Deserialize<'de> + Clone + Eq + Deref,
149    V: Deserialize<'de> + Clone,
150    <K as Deref>::Target: Eq,
151{
152    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
153    where
154        D: Deserializer<'de>,
155    {
156        // Instantiate our Visitor and ask the Deserializer to drive
157        // it over the input data, resulting in an instance of MyMap.
158        deserializer.deserialize_map(my_visitor::MyVisitor::new())
159    }
160}
161
162impl<K, V> InOMap<K, V>
163where
164    K: Eq + Clone,
165    V: Clone,
166{
167    #[inline]
168    #[must_use]
169    pub fn new() -> Self {
170        Self {
171            value: Default::default(),
172        }
173    }
174    #[inline]
175    #[must_use]
176    pub fn is_empty(&self) -> bool {
177        self.value.is_empty()
178    }
179    #[inline]
180    #[must_use]
181    pub fn len(&self) -> usize {
182        self.value.len()
183    }
184}
185impl<K, V> InOMap<K, V>
186where
187    K: Eq + Clone,
188    V: Clone,
189{
190    pub fn ptr_eq(&self, other: &Self) -> bool {
191        self.value.ptr_eq(&other.value)
192    }
193}
194
195impl<K, V> InOMap<K, V>
196where
197    K: Eq + Clone,
198    V: Clone,
199{
200    #[inline]
201    #[must_use]
202    pub fn iter(&self) -> imbl::vector::Iter<'_, (K, V), DefaultSharedPtr> {
203        self.value.iter()
204    }
205    #[inline]
206    #[must_use]
207    pub fn keys(&self) -> impl Iterator<Item = &K> {
208        self.iter().map(|(key, _value)| key)
209    }
210
211    #[inline]
212    #[must_use]
213    pub fn values(&self) -> impl Iterator<Item = &V> {
214        self.iter().map(|(_key, value)| value)
215    }
216
217    pub fn clear(&mut self) {
218        self.value.clear();
219    }
220}
221
222impl<K, V> InOMap<K, V>
223where
224    V: Clone,
225    K: Eq + Clone,
226{
227    #[must_use]
228    pub fn get<BK>(&self, key: &BK) -> Option<&V>
229    where
230        BK: Eq + ?Sized,
231        K: Borrow<BK> + PartialEq<BK>,
232    {
233        let key = key.borrow();
234        self.iter().find(|(k, _)| k == key).map(|x| &x.1)
235    }
236    #[must_use]
237    pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
238    where
239        BK: Eq + ?Sized,
240        K: Borrow<BK> + PartialEq<BK>,
241    {
242        self.iter().find(|(k, _)| k == key).map(|(k, v)| (k, v))
243    }
244    #[inline]
245    #[must_use]
246    pub fn contains_key<BK>(&self, k: &BK) -> bool
247    where
248        BK: Eq + ?Sized,
249        K: Borrow<BK> + PartialEq<BK>,
250    {
251        self.get(&k).is_some()
252    }
253    #[must_use]
254    pub fn is_submap_by<B, RM, F>(&self, other: RM, mut cmp: F) -> bool
255    where
256        B: Clone,
257        F: FnMut(&V, &B) -> bool,
258        RM: Borrow<InOMap<K, B>>,
259    {
260        self.value
261            .iter()
262            .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
263    }
264
265    #[must_use]
266    pub fn is_proper_submap_by<B, RM, F>(&self, other: RM, cmp: F) -> bool
267    where
268        B: Clone,
269        F: FnMut(&V, &B) -> bool,
270        RM: Borrow<InOMap<K, B>>,
271    {
272        self.value.len() != other.borrow().value.len() && self.is_submap_by(other, cmp)
273    }
274
275    #[inline]
276    #[must_use]
277    pub fn is_submap<RM>(&self, other: RM) -> bool
278    where
279        V: PartialEq,
280        RM: Borrow<Self>,
281    {
282        self.is_submap_by(other.borrow(), PartialEq::eq)
283    }
284
285    #[inline]
286    #[must_use]
287    pub fn is_proper_submap<RM>(&self, other: RM) -> bool
288    where
289        V: PartialEq,
290        RM: Borrow<Self>,
291    {
292        self.is_proper_submap_by(other.borrow(), PartialEq::eq)
293    }
294}
295
296impl<K, V> InOMap<K, V>
297where
298    V: Clone,
299    K: Eq + Clone,
300{
301    /// Get a mutable iterator over the values of a hash map.
302    ///
303    /// Please note that the order is consistent between maps using
304    /// the same hasher, but no other ordering guarantee is offered.
305    /// Items will not come out in insertion order or sort order.
306    /// They will, however, come out in the same order every time for
307    /// the same map.
308    #[inline]
309    #[must_use]
310    pub fn iter_mut(&mut self) -> imbl::vector::IterMut<'_, (K, V), DefaultSharedPtr> {
311        self.value.iter_mut()
312    }
313
314    /// Get a mutable reference to the value for a key from a hash
315    /// map.
316    ///
317    /// Time: O(n)
318    ///
319    /// # Examples
320    ///
321    /// ```
322    /// # #[macro_use] extern crate imbl;
323    /// # use imbl_value::InOMap;
324    /// # use imbl_value::inOMap;
325    /// let mut map = inOMap!{123 => "lol"};
326    /// if let Some(value) = map.get_mut(&123) {
327    ///     *value = "omg";
328    /// }
329    /// assert_eq!(
330    ///   map.get(&123),
331    ///   Some(&"omg")
332    /// );
333    /// ```
334    #[must_use]
335    pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
336    where
337        BK: Eq + ?Sized,
338        K: Borrow<BK> + PartialEq<BK>,
339    {
340        self.value
341            .iter_mut()
342            .find(|(k, _)| k == key.borrow())
343            .map(|(_, v)| v)
344    }
345
346    /// Insert a key/value mapping into a map.
347    ///
348    /// If the map already has a mapping for the given key, the
349    /// previous value is overwritten.
350    ///
351    /// Time: O(n)
352    ///
353    /// # Examples
354    ///
355    /// ```
356    /// # #[macro_use] extern crate imbl;
357    /// # use imbl_value::InOMap;
358    /// # use imbl_value::inOMap;
359    /// let mut map = inOMap!{};
360    /// map.insert(123, "123");
361    /// map.insert(456, "456");
362    /// assert_eq!(
363    ///   map,
364    ///   inOMap!{123 => "123", 456 => "456"}
365    /// );
366    /// ```
367    #[inline]
368    pub fn insert(&mut self, key: K, v: V) -> Option<V> {
369        let previous = self
370            .value
371            .iter()
372            .enumerate()
373            .find(|(_, (k, _))| k == &key)
374            .map(|(index, _)| index)
375            .map(|x| self.value.remove(x));
376        self.value.push_back((key, v));
377        previous.map(|(_, v)| v)
378    }
379
380    /// Remove a key/value pair from a map, if it exists, and return
381    /// the removed value.
382    ///
383    /// This is a copy-on-write operation, so that the parts of the
384    /// set's structure which are shared with other sets will be
385    /// safely copied before mutating.
386    ///
387    /// Time: O(n)
388    ///
389    /// # Examples
390    ///
391    /// ```
392    /// # #[macro_use] extern crate imbl;
393    /// # use imbl_value::InOMap;
394    /// # use imbl_value::inOMap;
395    /// let mut map = inOMap!{123 => "123", 456 => "456"};
396    /// assert_eq!(Some("123"), map.remove(&123));
397    /// assert_eq!(Some("456"), map.remove(&456));
398    /// assert_eq!(None, map.remove(&789));
399    /// assert!(map.is_empty());
400    /// ```
401    pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
402    where
403        BK: Eq + ?Sized,
404        K: Borrow<BK> + PartialEq<BK>,
405    {
406        self.value
407            .iter()
408            .enumerate()
409            .find(|x| &x.1 .0 == &*k)
410            .map(|x| x.0)
411            .map(|x| self.value.remove(x))
412            .map(|x| x.1)
413    }
414
415    /// Remove a key/value pair from a map, if it exists, and return
416    /// the removed key and value.
417    ///
418    /// Time: O(n)
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// # #[macro_use] extern crate imbl;
424    /// # use imbl_value::InOMap;
425    /// # use imbl_value::inOMap;
426    /// let mut map = inOMap!{123 => "123", 456 => "456"};
427    /// assert_eq!(Some((123, "123")), map.remove_with_key(&123));
428    /// assert_eq!(Some((456, "456")), map.remove_with_key(&456));
429    /// assert_eq!(None, map.remove_with_key(&789));
430    /// assert!(map.is_empty());
431    /// ```
432    pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
433    where
434        BK: Eq + ?Sized,
435        K: Borrow<BK> + PartialEq<BK>,
436    {
437        self.value
438            .iter()
439            .enumerate()
440            .find(|x| &x.1 .0 == &*k)
441            .map(|x| x.0)
442            .map(|x| self.value.remove(x))
443    }
444
445    /// Get the [`Entry`][Entry] for a key in the map for in-place manipulation.
446    ///
447    /// Time: O(n)
448    ///
449    /// [Entry]: enum.Entry.html
450    #[must_use]
451    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
452        let found_index = self
453            .value
454            .iter()
455            .enumerate()
456            .find(|x| &x.1 .0 == &key)
457            .map(|x| x.0);
458
459        if let Some(index) = found_index {
460            Entry::Occupied(OccupiedEntry {
461                map: self,
462                key,
463                index,
464            })
465        } else {
466            Entry::Vacant(VacantEntry { map: self, key })
467        }
468    }
469
470    /// Construct a new hash map by inserting a key/value mapping into a map.
471    ///
472    /// If the map already has a mapping for the given key, the previous value
473    /// is overwritten.
474    ///
475    /// Time: O(n)
476    ///
477    /// # Examples
478    ///
479    /// ```
480    /// # #[macro_use] extern crate imbl;
481    /// # use imbl_value::InOMap;
482    /// # use imbl_value::inOMap;
483    /// let map = inOMap!{};
484    /// assert_eq!(
485    ///   map.update(123, "123"),
486    ///   inOMap!{123 => "123"}
487    /// );
488    /// ```
489    #[inline]
490    #[must_use]
491    pub fn update(&self, k: K, v: V) -> Self {
492        let mut out = self.clone();
493        out.insert(k, v);
494        out
495    }
496
497    /// Construct a new hash map by inserting a key/value mapping into
498    /// a map.
499    ///
500    /// If the map already has a mapping for the given key, we call
501    /// the provided function with the old value and the new value,
502    /// and insert the result as the new value.
503    ///
504    /// Time: O(n)
505    #[must_use]
506    pub fn update_with<F>(&self, k: K, v: V, f: F) -> Self
507    where
508        F: FnOnce(V, V) -> V,
509    {
510        match self.extract_with_key(&k) {
511            None => self.update(k, v),
512            Some((_, v2, m)) => m.update(k, f(v2, v)),
513        }
514    }
515
516    /// Construct a new map by inserting a key/value mapping into a
517    /// map.
518    ///
519    /// If the map already has a mapping for the given key, we call
520    /// the provided function with the key, the old value and the new
521    /// value, and insert the result as the new value.
522    ///
523    /// Time: O(n)
524    #[must_use]
525    pub fn update_with_key<F>(&self, k: K, v: V, f: F) -> Self
526    where
527        F: FnOnce(&K, V, V) -> V,
528    {
529        match self.extract_with_key(&k) {
530            None => self.update(k, v),
531            Some((_, v2, m)) => {
532                let out_v = f(&k, v2, v);
533                m.update(k, out_v)
534            }
535        }
536    }
537
538    /// Construct a new map by inserting a key/value mapping into a
539    /// map, returning the old value for the key as well as the new
540    /// map.
541    ///
542    /// If the map already has a mapping for the given key, we call
543    /// the provided function with the key, the old value and the new
544    /// value, and insert the result as the new value.
545    ///
546    /// Time: O(n)
547    #[must_use]
548    pub fn update_lookup_with_key<F>(&self, k: K, v: V, f: F) -> (Option<V>, Self)
549    where
550        F: FnOnce(&K, &V, V) -> V,
551    {
552        match self.extract_with_key(&k) {
553            None => (None, self.update(k, v)),
554            Some((_, v2, m)) => {
555                let out_v = f(&k, &v2, v);
556                (Some(v2), m.update(k, out_v))
557            }
558        }
559    }
560
561    /// Update the value for a given key by calling a function with
562    /// the current value and overwriting it with the function's
563    /// return value.
564    ///
565    /// The function gets an [`Option<V>`][std::option::Option] and
566    /// returns the same, so that it can decide to delete a mapping
567    /// instead of updating the value, and decide what to do if the
568    /// key isn't in the map.
569    ///
570    /// Time: O(n)
571    ///
572    /// [std::option::Option]: https://doc.rust-lang.org/std/option/enum.Option.html
573    #[must_use]
574    pub fn alter<F>(&self, f: F, k: K) -> Self
575    where
576        F: FnOnce(Option<V>) -> Option<V>,
577    {
578        let pop = self.extract_with_key(&k);
579        match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) {
580            (None, None) => self.clone(),
581            (Some(v), None) => self.update(k, v),
582            (None, Some((_, _, m))) => m,
583            (Some(v), Some((_, _, m))) => m.update(k, v),
584        }
585    }
586
587    /// Construct a new map without the given key.
588    ///
589    /// Construct a map that's a copy of the current map, absent the
590    /// mapping for `key` if it's present.
591    ///
592    /// Time: O(n)
593    #[must_use]
594    pub fn without<BK>(&self, k: &BK) -> Self
595    where
596        BK: Eq + ?Sized,
597        K: Borrow<BK> + PartialEq<BK>,
598    {
599        match self.extract_with_key(k) {
600            None => self.clone(),
601            Some((_, _, map)) => map,
602        }
603    }
604
605    /// Filter out values from a map which don't satisfy a predicate.
606    ///
607    /// This is slightly more efficient than filtering using an
608    /// iterator, in that it doesn't need to rehash the retained
609    /// values, but it still needs to reconstruct the entire tree
610    /// structure of the map.
611    ///
612    /// Time: O(n ^ 2)
613    ///
614    /// # Examples
615    ///
616    /// ```
617    /// # #[macro_use] extern crate imbl;
618    /// # use imbl_value;
619    /// # use imbl_value::inOMap;
620    /// let mut map = inOMap!{1 => 1, 2 => 2, 3 => 3};
621    /// map.retain(|k, v| *k > 1);
622    /// let expected = inOMap!{2 => 2, 3 => 3};
623    /// assert_eq!(expected, map);
624    /// ```
625    pub fn retain<F>(&mut self, mut f: F)
626    where
627        F: FnMut(&K, &V) -> bool,
628    {
629        self.value.retain(|(k, v)| f(k, v));
630    }
631
632    /// Remove a key/value pair from a map, if it exists, and return
633    /// the removed value as well as the updated map.
634    ///
635    /// Time: O(n)
636    #[must_use]
637    pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
638    where
639        BK: Eq + ?Sized,
640        K: Borrow<BK> + PartialEq<BK>,
641    {
642        self.extract_with_key(k).map(|(_, v, m)| (v, m))
643    }
644
645    /// Remove a key/value pair from a map, if it exists, and return
646    /// the removed key and value as well as the updated list.
647    ///
648    /// Time: O(n)
649    #[must_use]
650    pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
651    where
652        BK: Eq + ?Sized,
653        K: Borrow<BK> + PartialEq<BK>,
654    {
655        let mut out = self.clone();
656        out.remove_with_key(k).map(|(k, v)| (k, v, out))
657    }
658
659    /// Construct the union of two maps, keeping the values in the
660    /// current map when keys exist in both maps.
661    ///
662    /// Time: O(n ^ 2)
663    ///
664    /// # Examples
665    ///
666    /// ```
667    /// # #[macro_use] extern crate imbl;
668    /// # use imbl_value::InOMap;
669    /// # use imbl_value::inOMap;
670    /// let map1 = inOMap!{1 => 1, 3 => 3};
671    /// let map2 = inOMap!{2 => 2, 3 => 4};
672    /// let expected = inOMap!{ 2 => 2, 3 => 3, 1 => 1,};
673    /// assert_eq!(expected, map1.union(map2));
674    /// ```
675    #[must_use]
676    pub fn union(self, other: Self) -> Self {
677        let (mut to_mutate, to_consume, use_to_consume) = if self.len() >= other.len() {
678            (self, other, false)
679        } else {
680            (other, self, true)
681        };
682        for (k, v) in to_consume.value.into_iter().rev() {
683            match to_mutate.entry(k) {
684                Entry::Occupied(mut e) if use_to_consume => {
685                    e.insert(v);
686                }
687                Entry::Vacant(e) => {
688                    e.insert(v);
689                }
690                _ => {}
691            }
692        }
693        to_mutate.value = to_mutate.value.clone().into_iter().rev().collect();
694        to_mutate
695    }
696
697    /// Construct the union of two maps, using a function to decide
698    /// what to do with the value when a key is in both maps.
699    ///
700    /// The function is called when a value exists in both maps, and
701    /// receives the value from the current map as its first argument,
702    /// and the value from the other map as the second. It should
703    /// return the value to be inserted in the resulting map.
704    ///
705    /// Time: O(n ^ 2)
706    #[inline]
707    #[must_use]
708    pub fn union_with<F>(self, other: Self, mut f: F) -> Self
709    where
710        F: FnMut(V, V) -> V,
711    {
712        self.union_with_key(other, |_, v1, v2| f(v1, v2))
713    }
714
715    /// Construct the union of two maps, using a function to decide
716    /// what to do with the value when a key is in both maps.
717    ///
718    /// The function is called when a value exists in both maps, and
719    /// receives a reference to the key as its first argument, the
720    /// value from the current map as the second argument, and the
721    /// value from the other map as the third argument. It should
722    /// return the value to be inserted in the resulting map.
723    ///
724    /// Time: O(n ^ 2)
725    ///
726    /// # Examples
727    ///
728    /// ```
729    /// # #[macro_use] extern crate imbl;
730    /// # use imbl_value::InOMap;
731    /// # use imbl_value::inOMap;
732    /// let map1 = inOMap!{1 => 1, 3 => 4};
733    /// let map2 = inOMap!{2 => 2, 3 => 5};
734    /// let expected = inOMap!{1 => 1, 2 => 2, 3 => 9};
735    /// assert_eq!(expected, map1.union_with_key(
736    ///     map2,
737    ///     |key, left, right| left + right
738    /// ));
739    /// ```
740    #[must_use]
741    pub fn union_with_key<F>(self, other: Self, mut f: F) -> Self
742    where
743        F: FnMut(&K, V, V) -> V,
744    {
745        if self.len() >= other.len() {
746            self.union_with_key_inner(other, f)
747        } else {
748            other.union_with_key_inner(self, |key, other_value, self_value| {
749                f(key, self_value, other_value)
750            })
751        }
752    }
753
754    fn union_with_key_inner<F>(mut self, other: Self, mut f: F) -> Self
755    where
756        F: FnMut(&K, V, V) -> V,
757    {
758        for (key, right_value) in other {
759            match self.remove(&key) {
760                None => {
761                    self.insert(key, right_value);
762                }
763                Some(left_value) => {
764                    let final_value = f(&key, left_value, right_value);
765                    self.insert(key, final_value);
766                }
767            }
768        }
769        self
770    }
771
772    /// Construct the union of a sequence of maps, selecting the value
773    /// of the leftmost when a key appears in more than one map.
774    ///
775    /// Time: O(n ^ 2)
776    ///
777    /// # Examples
778    ///
779    /// ```
780    /// # #[macro_use] extern crate imbl;
781    /// # use imbl_value::InOMap;
782    /// # use imbl_value::inOMap;
783    /// let map1 = inOMap!{1 => 1, 3 => 3};
784    /// let map2 = inOMap!{2 => 2};
785    /// let expected = inOMap!{2 => 2, 1 => 1, 3 => 3};
786    /// assert_eq!(expected, InOMap::unions(vec![map1, map2]));
787    /// ```
788    #[must_use]
789    pub fn unions<I>(i: I) -> Self
790    where
791        I: IntoIterator<Item = Self>,
792    {
793        i.into_iter().fold(Self::default(), Self::union)
794    }
795
796    /// Construct the union of a sequence of maps, using a function to
797    /// decide what to do with the value when a key is in more than
798    /// one map.
799    ///
800    /// The function is called when a value exists in multiple maps,
801    /// and receives the value from the current map as its first
802    /// argument, and the value from the next map as the second. It
803    /// should return the value to be inserted in the resulting map.
804    ///
805    /// Time: O(n ^ 2)
806    #[must_use]
807    pub fn unions_with<I, F>(i: I, f: F) -> Self
808    where
809        I: IntoIterator<Item = Self>,
810        F: Fn(V, V) -> V,
811    {
812        i.into_iter()
813            .fold(Self::default(), |a, b| a.union_with(b, &f))
814    }
815
816    /// Construct the union of a sequence of maps, using a function to
817    /// decide what to do with the value when a key is in more than
818    /// one map.
819    ///
820    /// The function is called when a value exists in multiple maps,
821    /// and receives a reference to the key as its first argument, the
822    /// value from the current map as the second argument, and the
823    /// value from the next map as the third argument. It should
824    /// return the value to be inserted in the resulting map.
825    ///
826    /// Time: O(n ^ 2)
827    #[must_use]
828    pub fn unions_with_key<I, F>(i: I, f: F) -> Self
829    where
830        I: IntoIterator<Item = Self>,
831        F: Fn(&K, V, V) -> V,
832    {
833        i.into_iter()
834            .fold(Self::default(), |a, b| a.union_with_key(b, &f))
835    }
836
837    /// Construct the symmetric difference between two maps by discarding keys
838    /// which occur in both maps.
839    ///
840    /// This is an alias for the
841    /// [`symmetric_difference`][symmetric_difference] method.
842    ///
843    /// Time: O(n ^ 2)
844    ///
845    /// # Examples
846    ///
847    /// ```
848    /// # #[macro_use] extern crate imbl;
849    /// # use imbl_value::InOMap;
850    /// # use imbl_value::inOMap;
851    /// let map1 = inOMap!{1 => 1, 3 => 4};
852    /// let map2 = inOMap!{2 => 2, 3 => 5};
853    /// let expected = inOMap!{1 => 1, 2 => 2};
854    /// assert_eq!(expected, map1.difference(map2));
855    /// ```
856    ///
857    /// [symmetric_difference]: #method.symmetric_difference
858    #[deprecated(
859        since = "2.0.1",
860        note = "to avoid conflicting behaviors between std and imbl, the `difference` alias for `symmetric_difference` will be removed."
861    )]
862    #[inline]
863    #[must_use]
864    pub fn difference(self, other: Self) -> Self {
865        self.symmetric_difference(other)
866    }
867
868    /// Construct the symmetric difference between two maps by discarding keys
869    /// which occur in both maps.
870    ///
871    /// Time: O(n ^ 2)
872    ///
873    /// # Examples
874    ///
875    /// ```
876    /// # #[macro_use] extern crate imbl;
877    /// # use imbl_value::InOMap;
878    /// # use imbl_value::inOMap;
879    /// let map1 = inOMap!{1 => 1, 3 => 4};
880    /// let map2 = inOMap!{2 => 2, 3 => 5};
881    /// let expected = inOMap!{1 => 1, 2 => 2};
882    /// assert_eq!(expected, map1.symmetric_difference(map2));
883    /// ```
884    #[inline]
885    #[must_use]
886    pub fn symmetric_difference(self, other: Self) -> Self {
887        self.symmetric_difference_with_key(other, |_, _, _| None)
888    }
889
890    /// Construct the symmetric difference between two maps by using a function
891    /// to decide what to do if a key occurs in both.
892    ///
893    /// This is an alias for the
894    /// [`symmetric_difference_with`][symmetric_difference_with] method.
895    ///
896    /// Time: O(n ^ 2)
897    ///
898    /// [symmetric_difference_with]: #method.symmetric_difference_with
899    #[deprecated(
900        since = "2.0.1",
901        note = "to avoid conflicting behaviors between std and imbl, the `difference_with` alias for `symmetric_difference_with` will be removed."
902    )]
903    #[inline]
904    #[must_use]
905    pub fn difference_with<F>(self, other: Self, f: F) -> Self
906    where
907        F: FnMut(V, V) -> Option<V>,
908    {
909        self.symmetric_difference_with(other, f)
910    }
911
912    /// Construct the symmetric difference between two maps by using a function
913    /// to decide what to do if a key occurs in both.
914    ///
915    /// Time: O(n ^ 2)
916    #[inline]
917    #[must_use]
918    pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
919    where
920        F: FnMut(V, V) -> Option<V>,
921    {
922        self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
923    }
924
925    /// Construct the symmetric difference between two maps by using a function
926    /// to decide what to do if a key occurs in both. The function
927    /// receives the key as well as both values.
928    ///
929    /// This is an alias for the
930    /// [`symmetric_difference_with`_key][symmetric_difference_with_key]
931    /// method.
932    ///
933    /// Time: O(n ^ 2)
934    ///
935    /// # Examples
936    ///
937    /// ```
938    /// # #[macro_use] extern crate imbl;
939    /// # use imbl_value::InOMap;
940    /// # use imbl_value::inOMap;
941    /// let map1 = inOMap!{1 => 1, 3 => 4};
942    /// let map2 = inOMap!{2 => 2, 3 => 5};
943    /// let expected = inOMap!{1 => 1, 3 => 9,  2 => 2,};
944    /// assert_eq!(expected, map1.difference_with_key(
945    ///     map2,
946    ///     |key, left, right| Some(left + right)
947    /// ));
948    /// ```
949    ///
950    /// [symmetric_difference_with_key]: #method.symmetric_difference_with_key
951    #[deprecated(
952        since = "2.0.1",
953        note = "to avoid conflicting behaviors between std and imbl, the `difference_with_key` alias for `symmetric_difference_with_key` will be removed."
954    )]
955    #[must_use]
956    pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
957    where
958        F: FnMut(&K, V, V) -> Option<V>,
959    {
960        self.symmetric_difference_with_key(other, f)
961    }
962
963    /// Construct the symmetric difference between two maps by using a function
964    /// to decide what to do if a key occurs in both. The function
965    /// receives the key as well as both values.
966    ///
967    /// Time: O(n ^ 2)
968    ///
969    /// # Examples
970    ///
971    /// ```
972    /// # #[macro_use] extern crate imbl;
973    /// # use imbl_value::InOMap;
974    /// # use imbl_value::inOMap;
975    /// let map1 = inOMap!{1 => 1, 3 => 4};
976    /// let map2 = inOMap!{2 => 2, 3 => 5};
977    /// let expected = inOMap!{1 => 1, 3 => 9,  2 => 2,};
978    /// assert_eq!(expected, map1.symmetric_difference_with_key(
979    ///     map2,
980    ///     |key, left, right| Some(left + right)
981    /// ));
982    /// ```
983    #[must_use]
984    pub fn symmetric_difference_with_key<F>(mut self, other: Self, mut f: F) -> Self
985    where
986        F: FnMut(&K, V, V) -> Option<V>,
987    {
988        let mut out = InOMap::default();
989        for (key, right_value) in other {
990            match self.remove(&key) {
991                None => {
992                    out.insert(key, right_value);
993                }
994                Some(left_value) => {
995                    if let Some(final_value) = f(&key, left_value, right_value) {
996                        out.insert(key, final_value);
997                    }
998                }
999            }
1000        }
1001        out.union(self)
1002    }
1003
1004    /// Construct the relative complement between two maps by discarding keys
1005    /// which occur in `other`.
1006    ///
1007    /// Time: O(m * n) where m is the size of the other map
1008    ///
1009    /// # Examples
1010    ///
1011    /// ```
1012    /// # #[macro_use] extern crate imbl;
1013    /// # use imbl::ordmap::OrdMap;
1014    /// let map1 = ordmap!{1 => 1, 3 => 4};
1015    /// let map2 = ordmap!{2 => 2, 3 => 5};
1016    /// let expected = ordmap!{1 => 1};
1017    /// assert_eq!(expected, map1.relative_complement(map2));
1018    /// ```
1019    #[inline]
1020    #[must_use]
1021    pub fn relative_complement(mut self, other: Self) -> Self {
1022        for (key, _) in other {
1023            let _ = self.remove(&key);
1024        }
1025        self
1026    }
1027
1028    /// Construct the intersection of two maps, keeping the values
1029    /// from the current map.
1030    ///
1031    /// Time: O(n ^ 2)
1032    ///
1033    /// # Examples
1034    ///
1035    /// ```
1036    /// # #[macro_use] extern crate imbl;
1037    /// # use imbl_value::InOMap;
1038    /// # use imbl_value::inOMap;
1039    /// let map1 = inOMap!{1 => 1, 2 => 2};
1040    /// let map2 = inOMap!{2 => 3, 3 => 4};
1041    /// let expected = inOMap!{2 => 2};
1042    /// assert_eq!(expected, map1.intersection(map2));
1043    /// ```
1044    #[inline]
1045    #[must_use]
1046    pub fn intersection(self, other: Self) -> Self {
1047        self.intersection_with_key(other, |_, v, _| v)
1048    }
1049
1050    /// Construct the intersection of two maps, calling a function
1051    /// with both values for each key and using the result as the
1052    /// value for the key.
1053    ///
1054    /// Time: O(n ^ 2)
1055    #[inline]
1056    #[must_use]
1057    pub fn intersection_with<B, C, F>(self, other: InOMap<K, B>, mut f: F) -> InOMap<K, C>
1058    where
1059        B: Clone,
1060        C: Clone,
1061        F: FnMut(V, B) -> C,
1062    {
1063        self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
1064    }
1065
1066    /// Construct the intersection of two maps, calling a function
1067    /// with the key and both values for each key and using the result
1068    /// as the value for the key.
1069    ///
1070    /// Time: O(n ^ 2)
1071    ///
1072    /// # Examples
1073    ///
1074    /// ```
1075    /// # #[macro_use] extern crate imbl;
1076    /// # use imbl_value::InOMap;
1077    /// # use imbl_value::inOMap;
1078    /// let map1 = inOMap!{1 => 1, 2 => 2};
1079    /// let map2 = inOMap!{2 => 3, 3 => 4};
1080    /// let expected = inOMap!{2 => 5};
1081    /// assert_eq!(expected, map1.intersection_with_key(
1082    ///     map2,
1083    ///     |key, left, right| left + right
1084    /// ));
1085    /// ```
1086    #[must_use]
1087    pub fn intersection_with_key<B, C, F>(mut self, other: InOMap<K, B>, mut f: F) -> InOMap<K, C>
1088    where
1089        B: Clone,
1090        C: Clone,
1091        F: FnMut(&K, V, B) -> C,
1092    {
1093        let mut out = InOMap::default();
1094        for (key, right_value) in other {
1095            match self.remove(&key) {
1096                None => (),
1097                Some(left_value) => {
1098                    let result = f(&key, left_value, right_value);
1099                    out.insert(key, result);
1100                }
1101            }
1102        }
1103        out
1104    }
1105}
1106
1107// Entries
1108
1109/// A handle for a key and its associated value.
1110///
1111/// ## Performance Note
1112///
1113/// When using an `Entry`, the key is only ever hashed once, when you
1114/// create the `Entry`. Operations on an `Entry` will never trigger a
1115/// rehash, where eg. a `contains_key(key)` followed by an
1116/// `insert(key, default_value)` (the equivalent of
1117/// `Entry::or_insert()`) would need to hash the key once for the
1118/// `contains_key` and again for the `insert`. The operations
1119/// generally perform similarly otherwise.
1120pub enum Entry<'a, K, V>
1121where
1122    V: Clone,
1123    K: Eq + Clone,
1124{
1125    /// An entry which exists in the map.
1126    Occupied(OccupiedEntry<'a, K, V>),
1127    /// An entry which doesn't exist in the map.
1128    Vacant(VacantEntry<'a, K, V>),
1129}
1130
1131impl<'a, K, V> Entry<'a, K, V>
1132where
1133    V: 'a + Clone,
1134    K: 'a + Eq + Clone,
1135{
1136    /// Insert the default value provided if there was no value
1137    /// already, and return a mutable reference to the value.
1138    pub fn or_insert(self, default: V) -> &'a mut V {
1139        self.or_insert_with(|| default)
1140    }
1141
1142    /// Insert the default value from the provided function if there
1143    /// was no value already, and return a mutable reference to the
1144    /// value.
1145    pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1146    where
1147        F: FnOnce() -> V,
1148    {
1149        match self {
1150            Entry::Occupied(entry) => entry.into_mut(),
1151            Entry::Vacant(entry) => entry.insert(default()),
1152        }
1153    }
1154
1155    /// Insert a default value if there was no value already, and
1156    /// return a mutable reference to the value.
1157    pub fn or_default(self) -> &'a mut V
1158    where
1159        V: Default,
1160    {
1161        self.or_insert_with(Default::default)
1162    }
1163
1164    /// Get the key for this entry.
1165    #[must_use]
1166    pub fn key(&self) -> &K {
1167        match self {
1168            Entry::Occupied(entry) => entry.key(),
1169            Entry::Vacant(entry) => entry.key(),
1170        }
1171    }
1172
1173    /// Call the provided function to modify the value if the value
1174    /// exists.
1175    #[must_use]
1176    pub fn and_modify<F>(mut self, f: F) -> Self
1177    where
1178        F: FnOnce(&mut V),
1179    {
1180        match &mut self {
1181            Entry::Occupied(ref mut entry) => f(entry.get_mut()),
1182            Entry::Vacant(_) => (),
1183        }
1184        self
1185    }
1186}
1187
1188/// An entry for a mapping that already exists in the map.
1189pub struct OccupiedEntry<'a, K, V>
1190where
1191    V: Clone,
1192    K: Eq + Clone,
1193{
1194    map: &'a mut InOMap<K, V>,
1195    index: usize,
1196    key: K,
1197}
1198
1199impl<'a, K, V> OccupiedEntry<'a, K, V>
1200where
1201    K: 'a + Eq + Clone,
1202    V: 'a + Clone,
1203{
1204    /// Get the key for this entry.
1205    #[must_use]
1206    pub fn key(&self) -> &K {
1207        &self.key
1208    }
1209
1210    /// Remove this entry from the map and return the removed mapping.
1211    pub fn remove_entry(self) -> (K, V) {
1212        self.map.remove_with_key(&self.key).unwrap()
1213    }
1214
1215    /// Get the current value.
1216    #[must_use]
1217    pub fn get(&self) -> &V {
1218        &self.map.value.get(self.index).unwrap().1
1219    }
1220
1221    /// Get a mutable reference to the current value.
1222    #[must_use]
1223    pub fn get_mut(&mut self) -> &mut V {
1224        &mut self.map.value.get_mut(self.index).unwrap().1
1225    }
1226
1227    /// Convert this entry into a mutable reference.
1228    #[must_use]
1229    pub fn into_mut(self) -> &'a mut V {
1230        &mut self.map.value.get_mut(self.index).unwrap().1
1231    }
1232
1233    /// Overwrite the current value.
1234    pub fn insert(&mut self, mut value: V) -> V {
1235        ::std::mem::swap(
1236            &mut self.map.value.get_mut(self.index).unwrap().1,
1237            &mut value,
1238        );
1239        value
1240    }
1241
1242    /// Remove this entry from the map and return the removed value.
1243    pub fn remove(self) -> V {
1244        self.remove_entry().1
1245    }
1246}
1247
1248/// An entry for a mapping that does not already exist in the map.
1249pub struct VacantEntry<'a, K, V>
1250where
1251    V: Clone,
1252    K: Eq + Clone,
1253{
1254    map: &'a mut InOMap<K, V>,
1255    key: K,
1256}
1257
1258impl<'a, K, V> VacantEntry<'a, K, V>
1259where
1260    K: 'a + Eq + Clone,
1261    V: 'a + Clone,
1262{
1263    /// Get the key for this entry.
1264    #[must_use]
1265    pub fn key(&self) -> &K {
1266        &self.key
1267    }
1268
1269    /// Convert this entry into its key.
1270    #[must_use]
1271    pub fn into_key(self) -> K {
1272        self.key
1273    }
1274
1275    /// Insert a value into this entry.
1276    pub fn insert(self, value: V) -> &'a mut V {
1277        self.map.insert(self.key.clone(), value);
1278        self.map.get_mut(&self.key).unwrap()
1279    }
1280}
1281
1282impl<K, V> Add for InOMap<K, V>
1283where
1284    V: Clone,
1285    K: Eq + Clone,
1286{
1287    type Output = InOMap<K, V>;
1288
1289    fn add(self, other: Self) -> Self::Output {
1290        self.union(other)
1291    }
1292}
1293
1294impl<'a, K, V> Add for &'a InOMap<K, V>
1295where
1296    V: Clone,
1297    K: Eq + Clone,
1298{
1299    type Output = InOMap<K, V>;
1300
1301    fn add(self, other: Self) -> Self::Output {
1302        self.clone().union(other.clone())
1303    }
1304}
1305
1306impl<K, V> Sum for InOMap<K, V>
1307where
1308    V: Clone,
1309    K: Eq + Clone,
1310{
1311    fn sum<I>(it: I) -> Self
1312    where
1313        I: Iterator<Item = Self>,
1314    {
1315        it.fold(Self::default(), |a, b| a + b)
1316    }
1317}
1318
1319impl<K, V, RK, RV> Extend<(RK, RV)> for InOMap<K, V>
1320where
1321    V: Clone + From<RV>,
1322    K: Eq + Clone + From<RK>,
1323{
1324    fn extend<I>(&mut self, iter: I)
1325    where
1326        I: IntoIterator<Item = (RK, RV)>,
1327    {
1328        for (key, value) in iter {
1329            self.insert(From::from(key), From::from(value));
1330        }
1331    }
1332}
1333
1334impl<'a, BK, K, V> Index<&'a BK> for InOMap<K, V>
1335where
1336    V: Clone,
1337    BK: Eq + ?Sized,
1338    K: Eq + Clone + Borrow<BK> + PartialEq<BK>,
1339{
1340    type Output = V;
1341
1342    fn index(&self, key: &BK) -> &Self::Output {
1343        match self.get::<BK>(key) {
1344            None => panic!("InOMap::index: invalid key"),
1345            Some(v) => v,
1346        }
1347    }
1348}
1349
1350impl<'a, BK, K, V> IndexMut<&'a BK> for InOMap<K, V>
1351where
1352    BK: Eq + ?Sized,
1353    K: Eq + Clone + Borrow<BK> + PartialEq<BK>,
1354    V: Clone,
1355{
1356    fn index_mut(&mut self, key: &BK) -> &mut Self::Output {
1357        match self.get_mut::<BK>(key) {
1358            None => panic!("InOMap::index_mut: invalid key"),
1359            Some(&mut ref mut value) => value,
1360        }
1361    }
1362}
1363
1364impl<K, V> Debug for InOMap<K, V>
1365where
1366    V: Clone,
1367    K: Eq + Debug + Clone,
1368    V: Debug,
1369{
1370    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ::std::fmt::Error> {
1371        let mut d = f.debug_map();
1372        for (k, v) in self {
1373            d.entry(k, v);
1374        }
1375        d.finish()
1376    }
1377}
1378
1379/// An iterator over the elements of a map.
1380pub struct Iter<'a, K, V>
1381where
1382    K: Clone,
1383    V: Clone,
1384{
1385    it: imbl::vector::Iter<'a, (K, V), DefaultSharedPtr>,
1386}
1387
1388// We impl Clone instead of deriving it, because we want Clone even if K and V aren't.
1389impl<'a, K, V> Clone for Iter<'a, K, V>
1390where
1391    K: Clone,
1392    V: Clone,
1393{
1394    fn clone(&self) -> Self {
1395        Iter {
1396            it: self.it.clone(),
1397        }
1398    }
1399}
1400
1401impl<'a, K, V> Iterator for Iter<'a, K, V>
1402where
1403    K: Clone,
1404    V: Clone,
1405{
1406    type Item = (&'a K, &'a V);
1407
1408    fn next(&mut self) -> Option<Self::Item> {
1409        self.it.next().map(|(k, v)| (k, v))
1410    }
1411
1412    fn size_hint(&self) -> (usize, Option<usize>) {
1413        self.it.size_hint()
1414    }
1415}
1416impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V>
1417where
1418    K: Clone,
1419    V: Clone,
1420{
1421}
1422
1423impl<'a, K, V> IntoIterator for &'a InOMap<K, V>
1424where
1425    K: Eq + Clone,
1426    V: Clone,
1427{
1428    type Item = (&'a K, &'a V);
1429    type IntoIter = Iter<'a, K, V>;
1430
1431    #[inline]
1432    fn into_iter(self) -> Self::IntoIter {
1433        Iter {
1434            it: self.value.iter(),
1435        }
1436    }
1437}
1438
1439impl<K, V> IntoIterator for InOMap<K, V>
1440where
1441    K: Eq + Clone,
1442    V: Clone,
1443{
1444    type Item = (K, V);
1445    type IntoIter = imbl::vector::ConsumingIter<(K, V), DefaultSharedPtr>;
1446
1447    #[inline]
1448    fn into_iter(self) -> Self::IntoIter {
1449        self.value.into_iter()
1450    }
1451}
1452
1453// Conversions
1454
1455impl<K, V> FromIterator<(K, V)> for InOMap<K, V>
1456where
1457    V: Clone,
1458    K: Eq + Clone,
1459{
1460    fn from_iter<T>(i: T) -> Self
1461    where
1462        T: IntoIterator<Item = (K, V)>,
1463    {
1464        let mut map = Self::default();
1465        for (k, v) in i {
1466            map.insert(k, v);
1467        }
1468        map
1469    }
1470}
1471
1472impl<K, V> Default for InOMap<K, V>
1473where
1474    K: Clone + Eq,
1475    V: Clone,
1476{
1477    fn default() -> Self {
1478        Self {
1479            value: Default::default(),
1480        }
1481    }
1482}
1483
1484impl<K, V> AsRef<InOMap<K, V>> for InOMap<K, V>
1485where
1486    K: Eq + Clone,
1487    V: Clone,
1488{
1489    #[inline]
1490    fn as_ref(&self) -> &Self {
1491        self
1492    }
1493}