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