imbl_value/in_order_map/
mod.rs

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