im_rc/ord/
map.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5//! An ordered map.
6//!
7//! An immutable ordered map implemented as a [B-tree] [1].
8//!
9//! Most operations on this type of map are O(log n). A
10//! [`HashMap`][hashmap::HashMap] is usually a better choice for
11//! performance, but the `OrdMap` has the advantage of only requiring
12//! an [`Ord`][std::cmp::Ord] constraint on the key, and of being
13//! ordered, so that keys always come out from lowest to highest,
14//! where a [`HashMap`][hashmap::HashMap] has no guaranteed ordering.
15//!
16//! [1]: https://en.wikipedia.org/wiki/B-tree
17//! [hashmap::HashMap]: ../hashmap/struct.HashMap.html
18//! [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html
19
20use std::borrow::Borrow;
21use std::cmp::Ordering;
22use std::collections;
23use std::fmt::{Debug, Error, Formatter};
24use std::hash::{BuildHasher, Hash, Hasher};
25use std::iter::{FromIterator, Iterator, Sum};
26use std::mem;
27use std::ops::{Add, Index, IndexMut, RangeBounds};
28
29use crate::hashmap::HashMap;
30use crate::nodes::btree::{BTreeValue, Insert, Node, Remove};
31#[cfg(has_specialisation)]
32use crate::util::linear_search_by;
33use crate::util::{Pool, PoolRef};
34
35pub use crate::nodes::btree::{
36    ConsumingIter, DiffItem as NodeDiffItem, DiffIter as NodeDiffIter, Iter as RangedIter,
37};
38
39/// Construct a map from a sequence of key/value pairs.
40///
41/// # Examples
42///
43/// ```
44/// # #[macro_use] extern crate im_rc as im;
45/// # use im::ordmap::OrdMap;
46/// # fn main() {
47/// assert_eq!(
48///   ordmap!{
49///     1 => 11,
50///     2 => 22,
51///     3 => 33
52///   },
53///   OrdMap::from(vec![(1, 11), (2, 22), (3, 33)])
54/// );
55/// # }
56/// ```
57#[macro_export]
58macro_rules! ordmap {
59    () => { $crate::ordmap::OrdMap::new() };
60
61    ( $( $key:expr => $value:expr ),* ) => {{
62        let mut map = $crate::ordmap::OrdMap::new();
63        $({
64            map.insert($key, $value);
65        })*;
66        map
67    }};
68}
69
70#[cfg(not(has_specialisation))]
71impl<K: Ord, V> BTreeValue for (K, V) {
72    type Key = K;
73
74    fn ptr_eq(&self, _other: &Self) -> bool {
75        false
76    }
77
78    fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
79    where
80        BK: Ord + ?Sized,
81        Self::Key: Borrow<BK>,
82    {
83        slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
84    }
85
86    fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
87        slice.binary_search_by(|value| value.0.cmp(&key.0))
88    }
89
90    fn cmp_keys<BK>(&self, other: &BK) -> Ordering
91    where
92        BK: Ord + ?Sized,
93        Self::Key: Borrow<BK>,
94    {
95        Self::Key::borrow(&self.0).cmp(other)
96    }
97
98    fn cmp_values(&self, other: &Self) -> Ordering {
99        self.0.cmp(&other.0)
100    }
101}
102
103#[cfg(has_specialisation)]
104impl<K: Ord, V> BTreeValue for (K, V) {
105    type Key = K;
106
107    fn ptr_eq(&self, _other: &Self) -> bool {
108        false
109    }
110
111    default fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
112    where
113        BK: Ord + ?Sized,
114        Self::Key: Borrow<BK>,
115    {
116        slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
117    }
118
119    default fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
120        slice.binary_search_by(|value| value.0.cmp(&key.0))
121    }
122
123    fn cmp_keys<BK>(&self, other: &BK) -> Ordering
124    where
125        BK: Ord + ?Sized,
126        Self::Key: Borrow<BK>,
127    {
128        Self::Key::borrow(&self.0).cmp(other)
129    }
130
131    fn cmp_values(&self, other: &Self) -> Ordering {
132        self.0.cmp(&other.0)
133    }
134}
135
136#[cfg(has_specialisation)]
137impl<K: Ord + Copy, V> BTreeValue for (K, V) {
138    fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
139    where
140        BK: Ord + ?Sized,
141        Self::Key: Borrow<BK>,
142    {
143        linear_search_by(slice, |value| Self::Key::borrow(&value.0).cmp(key))
144    }
145
146    fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
147        linear_search_by(slice, |value| value.0.cmp(&key.0))
148    }
149}
150
151def_pool!(OrdMapPool<K, V>, Node<(K, V)>);
152
153/// An ordered map.
154///
155/// An immutable ordered map implemented as a B-tree.
156///
157/// Most operations on this type of map are O(log n). A
158/// [`HashMap`][hashmap::HashMap] is usually a better choice for
159/// performance, but the `OrdMap` has the advantage of only requiring
160/// an [`Ord`][std::cmp::Ord] constraint on the key, and of being
161/// ordered, so that keys always come out from lowest to highest,
162/// where a [`HashMap`][hashmap::HashMap] has no guaranteed ordering.
163///
164/// [hashmap::HashMap]: ../hashmap/struct.HashMap.html
165/// [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html
166pub struct OrdMap<K, V> {
167    size: usize,
168    pool: OrdMapPool<K, V>,
169    root: PoolRef<Node<(K, V)>>,
170}
171
172impl<K, V> OrdMap<K, V> {
173    /// Construct an empty map.
174    #[must_use]
175    pub fn new() -> Self {
176        let pool = OrdMapPool::default();
177        let root = PoolRef::default(&pool.0);
178        OrdMap {
179            size: 0,
180            pool,
181            root,
182        }
183    }
184
185    /// Construct an empty map using a specific memory pool.
186    #[cfg(feature = "pool")]
187    #[must_use]
188    pub fn with_pool(pool: &OrdMapPool<K, V>) -> Self {
189        let root = PoolRef::default(&pool.0);
190        OrdMap {
191            size: 0,
192            pool: pool.clone(),
193            root,
194        }
195    }
196
197    /// Construct a map with a single mapping.
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// # #[macro_use] extern crate im_rc as im;
203    /// # use im::ordmap::OrdMap;
204    /// let map = OrdMap::unit(123, "onetwothree");
205    /// assert_eq!(
206    ///   map.get(&123),
207    ///   Some(&"onetwothree")
208    /// );
209    /// ```
210    #[inline]
211    #[must_use]
212    pub fn unit(key: K, value: V) -> Self {
213        let pool = OrdMapPool::default();
214        let root = PoolRef::new(&pool.0, Node::unit((key, value)));
215        OrdMap {
216            size: 1,
217            pool,
218            root,
219        }
220    }
221
222    /// Test whether a map is empty.
223    ///
224    /// Time: O(1)
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// # #[macro_use] extern crate im_rc as im;
230    /// # use im::ordmap::OrdMap;
231    /// assert!(
232    ///   !ordmap!{1 => 2}.is_empty()
233    /// );
234    /// assert!(
235    ///   OrdMap::<i32, i32>::new().is_empty()
236    /// );
237    /// ```
238    #[inline]
239    #[must_use]
240    pub fn is_empty(&self) -> bool {
241        self.len() == 0
242    }
243
244    /// Test whether two maps refer to the same content in memory.
245    ///
246    /// This is true if the two sides are references to the same map,
247    /// or if the two maps refer to the same root node.
248    ///
249    /// This would return true if you're comparing a map to itself, or
250    /// if you're comparing a map to a fresh clone of itself.
251    ///
252    /// Time: O(1)
253    pub fn ptr_eq(&self, other: &Self) -> bool {
254        std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
255    }
256
257    /// Get the size of a map.
258    ///
259    /// Time: O(1)
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// # #[macro_use] extern crate im_rc as im;
265    /// # use im::ordmap::OrdMap;
266    /// assert_eq!(3, ordmap!{
267    ///   1 => 11,
268    ///   2 => 22,
269    ///   3 => 33
270    /// }.len());
271    /// ```
272    #[inline]
273    #[must_use]
274    pub fn len(&self) -> usize {
275        self.size
276    }
277
278    /// Get a reference to the memory pool used by this map.
279    ///
280    /// Note that if you didn't specifically construct it with a pool, you'll
281    /// get back a reference to a pool of size 0.
282    #[cfg(feature = "pool")]
283    pub fn pool(&self) -> &OrdMapPool<K, V> {
284        &self.pool
285    }
286
287    /// Discard all elements from the map.
288    ///
289    /// This leaves you with an empty map, and all elements that
290    /// were previously inside it are dropped.
291    ///
292    /// Time: O(n)
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// # #[macro_use] extern crate im_rc as im;
298    /// # use im::OrdMap;
299    /// let mut map = ordmap![1=>1, 2=>2, 3=>3];
300    /// map.clear();
301    /// assert!(map.is_empty());
302    /// ```
303    pub fn clear(&mut self) {
304        if !self.is_empty() {
305            self.root = PoolRef::default(&self.pool.0);
306            self.size = 0;
307        }
308    }
309}
310
311impl<K, V> OrdMap<K, V>
312where
313    K: Ord,
314{
315    /// Get the largest key in a map, along with its value. If the map
316    /// is empty, return `None`.
317    ///
318    /// Time: O(log n)
319    ///
320    /// # Examples
321    ///
322    /// ```
323    /// # #[macro_use] extern crate im_rc as im;
324    /// # use im::ordmap::OrdMap;
325    /// assert_eq!(Some(&(3, 33)), ordmap!{
326    ///   1 => 11,
327    ///   2 => 22,
328    ///   3 => 33
329    /// }.get_max());
330    /// ```
331    #[must_use]
332    pub fn get_max(&self) -> Option<&(K, V)> {
333        self.root.max()
334    }
335
336    /// Get the smallest key in a map, along with its value. If the
337    /// map is empty, return `None`.
338    ///
339    /// Time: O(log n)
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// # #[macro_use] extern crate im_rc as im;
345    /// # use im::ordmap::OrdMap;
346    /// assert_eq!(Some(&(1, 11)), ordmap!{
347    ///   1 => 11,
348    ///   2 => 22,
349    ///   3 => 33
350    /// }.get_min());
351    /// ```
352    #[must_use]
353    pub fn get_min(&self) -> Option<&(K, V)> {
354        self.root.min()
355    }
356
357    /// Get an iterator over the key/value pairs of a map.
358    #[must_use]
359    pub fn iter(&self) -> Iter<'_, K, V> {
360        Iter {
361            it: RangedIter::new(&self.root, self.size, ..),
362        }
363    }
364
365    /// Create an iterator over a range of key/value pairs.
366    #[must_use]
367    pub fn range<R, BK>(&self, range: R) -> Iter<'_, K, V>
368    where
369        R: RangeBounds<BK>,
370        K: Borrow<BK>,
371        BK: Ord + ?Sized,
372    {
373        Iter {
374            it: RangedIter::new(&self.root, self.size, range),
375        }
376    }
377
378    /// Get an iterator over a map's keys.
379    #[must_use]
380    pub fn keys(&self) -> Keys<'_, K, V> {
381        Keys { it: self.iter() }
382    }
383
384    /// Get an iterator over a map's values.
385    #[must_use]
386    pub fn values(&self) -> Values<'_, K, V> {
387        Values { it: self.iter() }
388    }
389
390    /// Get an iterator over the differences between this map and
391    /// another, i.e. the set of entries to add, update, or remove to
392    /// this map in order to make it equal to the other map.
393    ///
394    /// This function will avoid visiting nodes which are shared
395    /// between the two maps, meaning that even very large maps can be
396    /// compared quickly if most of their structure is shared.
397    ///
398    /// Time: O(n) (where n is the number of unique elements across
399    /// the two maps, minus the number of elements belonging to nodes
400    /// shared between them)
401    #[must_use]
402    pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'a, K, V> {
403        DiffIter {
404            it: NodeDiffIter::new(&self.root, &other.root),
405        }
406    }
407
408    /// Get the value for a key from a map.
409    ///
410    /// Time: O(log n)
411    ///
412    /// # Examples
413    ///
414    /// ```
415    /// # #[macro_use] extern crate im_rc as im;
416    /// # use im::ordmap::OrdMap;
417    /// let map = ordmap!{123 => "lol"};
418    /// assert_eq!(
419    ///   map.get(&123),
420    ///   Some(&"lol")
421    /// );
422    /// ```
423    #[must_use]
424    pub fn get<BK>(&self, key: &BK) -> Option<&V>
425    where
426        BK: Ord + ?Sized,
427        K: Borrow<BK>,
428    {
429        self.root.lookup(key).map(|(_, v)| v)
430    }
431
432    /// Get the key/value pair for a key from a map.
433    ///
434    /// Time: O(log n)
435    ///
436    /// # Examples
437    ///
438    /// ```
439    /// # #[macro_use] extern crate im_rc as im;
440    /// # use im::ordmap::OrdMap;
441    /// let map = ordmap!{123 => "lol"};
442    /// assert_eq!(
443    ///   map.get_key_value(&123),
444    ///   Some((&123, &"lol"))
445    /// );
446    /// ```
447    #[must_use]
448    pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
449    where
450        BK: Ord + ?Sized,
451        K: Borrow<BK>,
452    {
453        self.root.lookup(key).map(|&(ref k, ref v)| (k, v))
454    }
455
456    /// Get the closest smaller entry in a map to a given key
457    /// as a mutable reference.
458    ///
459    /// If the map contains the given key, this is returned.
460    /// Otherwise, the closest key in the map smaller than the
461    /// given value is returned. If the smallest key in the map
462    /// is larger than the given key, `None` is returned.
463    ///
464    /// # Examples
465    ///
466    /// ```rust
467    /// # #[macro_use] extern crate im_rc as im;
468    /// # use im::OrdMap;
469    /// let map = ordmap![1 => 1, 3 => 3, 5 => 5];
470    /// assert_eq!(Some((&3, &3)), map.get_prev(&4));
471    /// ```
472    #[must_use]
473    pub fn get_prev<BK>(&self, key: &BK) -> Option<(&K, &V)>
474    where
475        BK: Ord + ?Sized,
476        K: Borrow<BK>,
477    {
478        self.root.lookup_prev(key).map(|(k, v)| (k, v))
479    }
480
481    /// Get the closest larger entry in a map to a given key
482    /// as a mutable reference.
483    ///
484    /// If the set contains the given value, this is returned.
485    /// Otherwise, the closest value in the set larger than the
486    /// given value is returned. If the largest value in the set
487    /// is smaller than the given value, `None` is returned.
488    ///
489    /// # Examples
490    ///
491    /// ```rust
492    /// # #[macro_use] extern crate im_rc as im;
493    /// # use im::OrdMap;
494    /// let map = ordmap![1 => 1, 3 => 3, 5 => 5];
495    /// assert_eq!(Some((&5, &5)), map.get_next(&4));
496    /// ```
497    #[must_use]
498    pub fn get_next<BK>(&self, key: &BK) -> Option<(&K, &V)>
499    where
500        BK: Ord + ?Sized,
501        K: Borrow<BK>,
502    {
503        self.root.lookup_next(key).map(|(k, v)| (k, v))
504    }
505
506    /// Test for the presence of a key in a map.
507    ///
508    /// Time: O(log n)
509    ///
510    /// # Examples
511    ///
512    /// ```
513    /// # #[macro_use] extern crate im_rc as im;
514    /// # use im::ordmap::OrdMap;
515    /// let map = ordmap!{123 => "lol"};
516    /// assert!(
517    ///   map.contains_key(&123)
518    /// );
519    /// assert!(
520    ///   !map.contains_key(&321)
521    /// );
522    /// ```
523    #[must_use]
524    pub fn contains_key<BK>(&self, k: &BK) -> bool
525    where
526        BK: Ord + ?Sized,
527        K: Borrow<BK>,
528    {
529        self.get(k).is_some()
530    }
531
532    /// Test whether a map is a submap of another map, meaning that
533    /// all keys in our map must also be in the other map, with the
534    /// same values.
535    ///
536    /// Use the provided function to decide whether values are equal.
537    ///
538    /// Time: O(n log n)
539    #[must_use]
540    pub fn is_submap_by<B, RM, F>(&self, other: RM, mut cmp: F) -> bool
541    where
542        F: FnMut(&V, &B) -> bool,
543        RM: Borrow<OrdMap<K, B>>,
544    {
545        self.iter()
546            .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
547    }
548
549    /// Test whether a map is a proper submap of another map, meaning
550    /// that all keys in our map must also be in the other map, with
551    /// the same values. To be a proper submap, ours must also contain
552    /// fewer keys than the other map.
553    ///
554    /// Use the provided function to decide whether values are equal.
555    ///
556    /// Time: O(n log n)
557    #[must_use]
558    pub fn is_proper_submap_by<B, RM, F>(&self, other: RM, cmp: F) -> bool
559    where
560        F: FnMut(&V, &B) -> bool,
561        RM: Borrow<OrdMap<K, B>>,
562    {
563        self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
564    }
565
566    /// Test whether a map is a submap of another map, meaning that
567    /// all keys in our map must also be in the other map, with the
568    /// same values.
569    ///
570    /// Time: O(n log n)
571    ///
572    /// # Examples
573    ///
574    /// ```
575    /// # #[macro_use] extern crate im_rc as im;
576    /// # use im::ordmap::OrdMap;
577    /// let map1 = ordmap!{1 => 1, 2 => 2};
578    /// let map2 = ordmap!{1 => 1, 2 => 2, 3 => 3};
579    /// assert!(map1.is_submap(map2));
580    /// ```
581    #[must_use]
582    pub fn is_submap<RM>(&self, other: RM) -> bool
583    where
584        V: PartialEq,
585        RM: Borrow<Self>,
586    {
587        self.is_submap_by(other.borrow(), PartialEq::eq)
588    }
589
590    /// Test whether a map is a proper submap of another map, meaning
591    /// that all keys in our map must also be in the other map, with
592    /// the same values. To be a proper submap, ours must also contain
593    /// fewer keys than the other map.
594    ///
595    /// Time: O(n log n)
596    ///
597    /// # Examples
598    ///
599    /// ```
600    /// # #[macro_use] extern crate im_rc as im;
601    /// # use im::ordmap::OrdMap;
602    /// let map1 = ordmap!{1 => 1, 2 => 2};
603    /// let map2 = ordmap!{1 => 1, 2 => 2, 3 => 3};
604    /// assert!(map1.is_proper_submap(map2));
605    ///
606    /// let map3 = ordmap!{1 => 1, 2 => 2};
607    /// let map4 = ordmap!{1 => 1, 2 => 2};
608    /// assert!(!map3.is_proper_submap(map4));
609    /// ```
610    #[must_use]
611    pub fn is_proper_submap<RM>(&self, other: RM) -> bool
612    where
613        V: PartialEq,
614        RM: Borrow<Self>,
615    {
616        self.is_proper_submap_by(other.borrow(), PartialEq::eq)
617    }
618}
619
620impl<K, V> OrdMap<K, V>
621where
622    K: Ord + Clone,
623    V: Clone,
624{
625    /// Get a mutable reference to the value for a key from a map.
626    ///
627    /// Time: O(log n)
628    ///
629    /// # Examples
630    ///
631    /// ```
632    /// # #[macro_use] extern crate im_rc as im;
633    /// # use im::ordmap::OrdMap;
634    /// let mut map = ordmap!{123 => "lol"};
635    /// if let Some(value) = map.get_mut(&123) {
636    ///     *value = "omg";
637    /// }
638    /// assert_eq!(
639    ///   map.get(&123),
640    ///   Some(&"omg")
641    /// );
642    /// ```
643    #[must_use]
644    pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
645    where
646        BK: Ord + ?Sized,
647        K: Borrow<BK>,
648    {
649        let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
650        root.lookup_mut(&self.pool.0, key).map(|(_, v)| v)
651    }
652
653    /// Get the closest smaller entry in a map to a given key
654    /// as a mutable reference.
655    ///
656    /// If the map contains the given key, this is returned.
657    /// Otherwise, the closest key in the map smaller than the
658    /// given value is returned. If the smallest key in the map
659    /// is larger than the given key, `None` is returned.
660    ///
661    /// # Examples
662    ///
663    /// ```rust
664    /// # #[macro_use] extern crate im_rc as im;
665    /// # use im::OrdMap;
666    /// let mut map = ordmap![1 => 1, 3 => 3, 5 => 5];
667    /// if let Some((key, value)) = map.get_prev_mut(&4) {
668    ///     *value = 4;
669    /// }
670    /// assert_eq!(ordmap![1 => 1, 3 => 4, 5 => 5], map);
671    /// ```
672    #[must_use]
673    pub fn get_prev_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
674    where
675        BK: Ord + ?Sized,
676        K: Borrow<BK>,
677    {
678        let pool = &self.pool.0;
679        PoolRef::make_mut(pool, &mut self.root)
680            .lookup_prev_mut(pool, key)
681            .map(|(ref k, ref mut v)| (k, v))
682    }
683
684    /// Get the closest larger entry in a map to a given key
685    /// as a mutable reference.
686    ///
687    /// If the set contains the given value, this is returned.
688    /// Otherwise, the closest value in the set larger than the
689    /// given value is returned. If the largest value in the set
690    /// is smaller than the given value, `None` is returned.
691    ///
692    /// # Examples
693    ///
694    /// ```rust
695    /// # #[macro_use] extern crate im_rc as im;
696    /// # use im::OrdMap;
697    /// let mut map = ordmap![1 => 1, 3 => 3, 5 => 5];
698    /// if let Some((key, value)) = map.get_next_mut(&4) {
699    ///     *value = 4;
700    /// }
701    /// assert_eq!(ordmap![1 => 1, 3 => 3, 5 => 4], map);
702    /// ```
703    #[must_use]
704    pub fn get_next_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
705    where
706        BK: Ord + ?Sized,
707        K: Borrow<BK>,
708    {
709        let pool = &self.pool.0;
710        PoolRef::make_mut(pool, &mut self.root)
711            .lookup_next_mut(pool, key)
712            .map(|(ref k, ref mut v)| (k, v))
713    }
714
715    /// Insert a key/value mapping into a map.
716    ///
717    /// This is a copy-on-write operation, so that the parts of the
718    /// map's structure which are shared with other maps will be
719    /// safely copied before mutating.
720    ///
721    /// If the map already has a mapping for the given key, the
722    /// previous value is overwritten.
723    ///
724    /// Time: O(log n)
725    ///
726    /// # Examples
727    ///
728    /// ```
729    /// # #[macro_use] extern crate im_rc as im;
730    /// # use im::ordmap::OrdMap;
731    /// let mut map = ordmap!{};
732    /// map.insert(123, "123");
733    /// map.insert(456, "456");
734    /// assert_eq!(
735    ///   map,
736    ///   ordmap!{123 => "123", 456 => "456"}
737    /// );
738    /// ```
739    ///
740    /// [insert]: #method.insert
741    #[inline]
742    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
743        let new_root = {
744            let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
745            match root.insert(&self.pool.0, (key, value)) {
746                Insert::Replaced((_, old_value)) => return Some(old_value),
747                Insert::Added => {
748                    self.size += 1;
749                    return None;
750                }
751                Insert::Split(left, median, right) => PoolRef::new(
752                    &self.pool.0,
753                    Node::new_from_split(&self.pool.0, left, median, right),
754                ),
755            }
756        };
757        self.size += 1;
758        self.root = new_root;
759        None
760    }
761
762    /// Remove a key/value mapping from a map if it exists.
763    ///
764    /// Time: O(log n)
765    ///
766    /// # Examples
767    ///
768    /// ```
769    /// # #[macro_use] extern crate im_rc as im;
770    /// # use im::ordmap::OrdMap;
771    /// let mut map = ordmap!{123 => "123", 456 => "456"};
772    /// map.remove(&123);
773    /// map.remove(&456);
774    /// assert!(map.is_empty());
775    /// ```
776    ///
777    /// [remove]: #method.remove
778    #[inline]
779    pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
780    where
781        BK: Ord + ?Sized,
782        K: Borrow<BK>,
783    {
784        self.remove_with_key(k).map(|(_, v)| v)
785    }
786
787    /// Remove a key/value pair from a map, if it exists, and return
788    /// the removed key and value.
789    ///
790    /// Time: O(log n)
791    pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
792    where
793        BK: Ord + ?Sized,
794        K: Borrow<BK>,
795    {
796        let (new_root, removed_value) = {
797            let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
798            match root.remove(&self.pool.0, k) {
799                Remove::NoChange => return None,
800                Remove::Removed(pair) => {
801                    self.size -= 1;
802                    return Some(pair);
803                }
804                Remove::Update(pair, root) => (PoolRef::new(&self.pool.0, root), Some(pair)),
805            }
806        };
807        self.size -= 1;
808        self.root = new_root;
809        removed_value
810    }
811
812    /// Construct a new map by inserting a key/value mapping into a
813    /// map.
814    ///
815    /// If the map already has a mapping for the given key, the
816    /// previous value is overwritten.
817    ///
818    /// Time: O(log n)
819    ///
820    /// # Examples
821    ///
822    /// ```
823    /// # #[macro_use] extern crate im_rc as im;
824    /// # use im::ordmap::OrdMap;
825    /// let map = ordmap!{};
826    /// assert_eq!(
827    ///   map.update(123, "123"),
828    ///   ordmap!{123 => "123"}
829    /// );
830    /// ```
831    #[must_use]
832    pub fn update(&self, key: K, value: V) -> Self {
833        let mut out = self.clone();
834        out.insert(key, value);
835        out
836    }
837
838    /// Construct a new map by inserting a key/value mapping into a
839    /// map.
840    ///
841    /// If the map already has a mapping for the given key, we call
842    /// the provided function with the old value and the new value,
843    /// and insert the result as the new value.
844    ///
845    /// Time: O(log n)
846    #[must_use]
847    pub fn update_with<F>(self, k: K, v: V, f: F) -> Self
848    where
849        F: FnOnce(V, V) -> V,
850    {
851        self.update_with_key(k, v, |_, v1, v2| f(v1, v2))
852    }
853
854    /// Construct a new map by inserting a key/value mapping into a
855    /// map.
856    ///
857    /// If the map already has a mapping for the given key, we call
858    /// the provided function with the key, the old value and the new
859    /// value, and insert the result as the new value.
860    ///
861    /// Time: O(log n)
862    #[must_use]
863    pub fn update_with_key<F>(self, k: K, v: V, f: F) -> Self
864    where
865        F: FnOnce(&K, V, V) -> V,
866    {
867        match self.extract_with_key(&k) {
868            None => self.update(k, v),
869            Some((_, v2, m)) => {
870                let out_v = f(&k, v2, v);
871                m.update(k, out_v)
872            }
873        }
874    }
875
876    /// Construct a new map by inserting a key/value mapping into a
877    /// map, returning the old value for the key as well as the new
878    /// map.
879    ///
880    /// If the map already has a mapping for the given key, we call
881    /// the provided function with the key, the old value and the new
882    /// value, and insert the result as the new value.
883    ///
884    /// Time: O(log n)
885    #[must_use]
886    pub fn update_lookup_with_key<F>(self, k: K, v: V, f: F) -> (Option<V>, Self)
887    where
888        F: FnOnce(&K, &V, V) -> V,
889    {
890        match self.extract_with_key(&k) {
891            None => (None, self.update(k, v)),
892            Some((_, v2, m)) => {
893                let out_v = f(&k, &v2, v);
894                (Some(v2), m.update(k, out_v))
895            }
896        }
897    }
898
899    /// Update the value for a given key by calling a function with
900    /// the current value and overwriting it with the function's
901    /// return value.
902    ///
903    /// The function gets an [`Option<V>`][std::option::Option] and
904    /// returns the same, so that it can decide to delete a mapping
905    /// instead of updating the value, and decide what to do if the
906    /// key isn't in the map.
907    ///
908    /// Time: O(log n)
909    ///
910    /// [std::option::Option]: https://doc.rust-lang.org/std/option/enum.Option.html
911    #[must_use]
912    pub fn alter<F>(&self, f: F, k: K) -> Self
913    where
914        F: FnOnce(Option<V>) -> Option<V>,
915    {
916        let pop = self.extract_with_key(&k);
917        match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) {
918            (None, None) => self.clone(),
919            (Some(v), None) => self.update(k, v),
920            (None, Some((_, _, m))) => m,
921            (Some(v), Some((_, _, m))) => m.update(k, v),
922        }
923    }
924
925    /// Remove a key/value pair from a map, if it exists.
926    ///
927    /// Time: O(log n)
928    #[must_use]
929    pub fn without<BK>(&self, k: &BK) -> Self
930    where
931        BK: Ord + ?Sized,
932        K: Borrow<BK>,
933    {
934        self.extract(k)
935            .map(|(_, m)| m)
936            .unwrap_or_else(|| self.clone())
937    }
938
939    /// Remove a key/value pair from a map, if it exists, and return
940    /// the removed value as well as the updated list.
941    ///
942    /// Time: O(log n)
943    #[must_use]
944    pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
945    where
946        BK: Ord + ?Sized,
947        K: Borrow<BK>,
948    {
949        self.extract_with_key(k).map(|(_, v, m)| (v, m))
950    }
951
952    /// Remove a key/value pair from a map, if it exists, and return
953    /// the removed key and value as well as the updated list.
954    ///
955    /// Time: O(log n)
956    #[must_use]
957    pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
958    where
959        BK: Ord + ?Sized,
960        K: Borrow<BK>,
961    {
962        let mut out = self.clone();
963        let result = out.remove_with_key(k);
964        result.map(|(k, v)| (k, v, out))
965    }
966
967    /// Construct the union of two maps, keeping the values in the
968    /// current map when keys exist in both maps.
969    ///
970    /// Time: O(n log n)
971    ///
972    /// # Examples
973    ///
974    /// ```
975    /// # #[macro_use] extern crate im_rc as im;
976    /// # use im::ordmap::OrdMap;
977    /// let map1 = ordmap!{1 => 1, 3 => 3};
978    /// let map2 = ordmap!{2 => 2, 3 => 4};
979    /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 3};
980    /// assert_eq!(expected, map1.union(map2));
981    /// ```
982    #[inline]
983    #[must_use]
984    pub fn union(self, other: Self) -> Self {
985        let (mut to_mutate, to_consume) = if self.len() >= other.len() {
986            (self, other)
987        } else {
988            (other, self)
989        };
990        for (k, v) in to_consume {
991            to_mutate.entry(k).or_insert(v);
992        }
993        to_mutate
994    }
995
996    /// Construct the union of two maps, using a function to decide
997    /// what to do with the value when a key is in both maps.
998    ///
999    /// The function is called when a value exists in both maps, and
1000    /// receives the value from the current map as its first argument,
1001    /// and the value from the other map as the second. It should
1002    /// return the value to be inserted in the resulting map.
1003    ///
1004    /// Time: O(n log n)
1005    #[inline]
1006    #[must_use]
1007    pub fn union_with<F>(self, other: Self, mut f: F) -> Self
1008    where
1009        F: FnMut(V, V) -> V,
1010    {
1011        self.union_with_key(other, |_, v1, v2| f(v1, v2))
1012    }
1013
1014    /// Construct the union of two maps, using a function to decide
1015    /// what to do with the value when a key is in both maps.
1016    ///
1017    /// The function is called when a value exists in both maps, and
1018    /// receives a reference to the key as its first argument, the
1019    /// value from the current map as the second argument, and the
1020    /// value from the other map as the third argument. It should
1021    /// return the value to be inserted in the resulting map.
1022    ///
1023    /// Time: O(n log n)
1024    ///
1025    /// # Examples
1026    ///
1027    /// ```
1028    /// # #[macro_use] extern crate im_rc as im;
1029    /// # use im::ordmap::OrdMap;
1030    /// let map1 = ordmap!{1 => 1, 3 => 4};
1031    /// let map2 = ordmap!{2 => 2, 3 => 5};
1032    /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 9};
1033    /// assert_eq!(expected, map1.union_with_key(
1034    ///     map2,
1035    ///     |key, left, right| left + right
1036    /// ));
1037    /// ```
1038    #[must_use]
1039    pub fn union_with_key<F>(self, other: Self, mut f: F) -> Self
1040    where
1041        F: FnMut(&K, V, V) -> V,
1042    {
1043        if self.len() >= other.len() {
1044            self.union_with_key_inner(other, f)
1045        } else {
1046            other.union_with_key_inner(self, |key, other_value, self_value| {
1047                f(key, self_value, other_value)
1048            })
1049        }
1050    }
1051
1052    fn union_with_key_inner<F>(mut self, other: Self, mut f: F) -> Self
1053    where
1054        F: FnMut(&K, V, V) -> V,
1055    {
1056        for (key, right_value) in other {
1057            match self.remove(&key) {
1058                None => {
1059                    self.insert(key, right_value);
1060                }
1061                Some(left_value) => {
1062                    let final_value = f(&key, left_value, right_value);
1063                    self.insert(key, final_value);
1064                }
1065            }
1066        }
1067        self
1068    }
1069
1070    /// Construct the union of a sequence of maps, selecting the value
1071    /// of the leftmost when a key appears in more than one map.
1072    ///
1073    /// Time: O(n log n)
1074    ///
1075    /// # Examples
1076    ///
1077    /// ```
1078    /// # #[macro_use] extern crate im_rc as im;
1079    /// # use im::ordmap::OrdMap;
1080    /// let map1 = ordmap!{1 => 1, 3 => 3};
1081    /// let map2 = ordmap!{2 => 2};
1082    /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 3};
1083    /// assert_eq!(expected, OrdMap::unions(vec![map1, map2]));
1084    /// ```
1085    #[must_use]
1086    pub fn unions<I>(i: I) -> Self
1087    where
1088        I: IntoIterator<Item = Self>,
1089    {
1090        i.into_iter().fold(Self::default(), Self::union)
1091    }
1092
1093    /// Construct the union of a sequence of maps, using a function to
1094    /// decide what to do with the value when a key is in more than
1095    /// one map.
1096    ///
1097    /// The function is called when a value exists in multiple maps,
1098    /// and receives the value from the current map as its first
1099    /// argument, and the value from the next map as the second. It
1100    /// should return the value to be inserted in the resulting map.
1101    ///
1102    /// Time: O(n log n)
1103    #[must_use]
1104    pub fn unions_with<I, F>(i: I, f: F) -> Self
1105    where
1106        I: IntoIterator<Item = Self>,
1107        F: Fn(V, V) -> V,
1108    {
1109        i.into_iter()
1110            .fold(Self::default(), |a, b| a.union_with(b, &f))
1111    }
1112
1113    /// Construct the union of a sequence of maps, using a function to
1114    /// decide what to do with the value when a key is in more than
1115    /// one map.
1116    ///
1117    /// The function is called when a value exists in multiple maps,
1118    /// and receives a reference to the key as its first argument, the
1119    /// value from the current map as the second argument, and the
1120    /// value from the next map as the third argument. It should
1121    /// return the value to be inserted in the resulting map.
1122    ///
1123    /// Time: O(n log n)
1124    #[must_use]
1125    pub fn unions_with_key<I, F>(i: I, f: F) -> Self
1126    where
1127        I: IntoIterator<Item = Self>,
1128        F: Fn(&K, V, V) -> V,
1129    {
1130        i.into_iter()
1131            .fold(Self::default(), |a, b| a.union_with_key(b, &f))
1132    }
1133
1134    /// Construct the symmetric difference between two maps by discarding keys
1135    /// which occur in both maps.
1136    ///
1137    /// This is an alias for the
1138    /// [`symmetric_difference`][symmetric_difference] method.
1139    ///
1140    /// Time: O(n log n)
1141    ///
1142    /// # Examples
1143    ///
1144    /// ```
1145    /// # #[macro_use] extern crate im_rc as im;
1146    /// # use im::ordmap::OrdMap;
1147    /// let map1 = ordmap!{1 => 1, 3 => 4};
1148    /// let map2 = ordmap!{2 => 2, 3 => 5};
1149    /// let expected = ordmap!{1 => 1, 2 => 2};
1150    /// assert_eq!(expected, map1.difference(map2));
1151    /// ```
1152    ///
1153    /// [symmetric_difference]: #method.symmetric_difference
1154    #[inline]
1155    #[must_use]
1156    pub fn difference(self, other: Self) -> Self {
1157        self.symmetric_difference(other)
1158    }
1159
1160    /// Construct the symmetric difference between two maps by discarding keys
1161    /// which occur in both maps.
1162    ///
1163    /// Time: O(n log n)
1164    ///
1165    /// # Examples
1166    ///
1167    /// ```
1168    /// # #[macro_use] extern crate im_rc as im;
1169    /// # use im::ordmap::OrdMap;
1170    /// let map1 = ordmap!{1 => 1, 3 => 4};
1171    /// let map2 = ordmap!{2 => 2, 3 => 5};
1172    /// let expected = ordmap!{1 => 1, 2 => 2};
1173    /// assert_eq!(expected, map1.symmetric_difference(map2));
1174    /// ```
1175    #[inline]
1176    #[must_use]
1177    pub fn symmetric_difference(self, other: Self) -> Self {
1178        self.symmetric_difference_with_key(other, |_, _, _| None)
1179    }
1180
1181    /// Construct the symmetric difference between two maps by using a function
1182    /// to decide what to do if a key occurs in both.
1183    ///
1184    /// This is an alias for the
1185    /// [`symmetric_difference_with`][symmetric_difference_with] method.
1186    ///
1187    /// Time: O(n log n)
1188    ///
1189    /// [symmetric_difference_with]: #method.symmetric_difference_with
1190    #[inline]
1191    #[must_use]
1192    pub fn difference_with<F>(self, other: Self, f: F) -> Self
1193    where
1194        F: FnMut(V, V) -> Option<V>,
1195    {
1196        self.symmetric_difference_with(other, f)
1197    }
1198
1199    /// Construct the symmetric difference between two maps by using a function
1200    /// to decide what to do if a key occurs in both.
1201    ///
1202    /// Time: O(n log n)
1203    #[inline]
1204    #[must_use]
1205    pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
1206    where
1207        F: FnMut(V, V) -> Option<V>,
1208    {
1209        self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
1210    }
1211
1212    /// Construct the symmetric difference between two maps by using a function
1213    /// to decide what to do if a key occurs in both. The function
1214    /// receives the key as well as both values.
1215    ///
1216    /// This is an alias for the
1217    /// [`symmetric_difference_with_key`][symmetric_difference_with_key]
1218    /// method.
1219    ///
1220    /// Time: O(n log n)
1221    ///
1222    /// # Examples
1223    ///
1224    /// ```
1225    /// # #[macro_use] extern crate im_rc as im;
1226    /// # use im::ordmap::OrdMap;
1227    /// let map1 = ordmap!{1 => 1, 3 => 4};
1228    /// let map2 = ordmap!{2 => 2, 3 => 5};
1229    /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 9};
1230    /// assert_eq!(expected, map1.difference_with_key(
1231    ///     map2,
1232    ///     |key, left, right| Some(left + right)
1233    /// ));
1234    /// ```
1235    /// [symmetric_difference_with_key]: #method.symmetric_difference_with_key
1236    #[must_use]
1237    pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
1238    where
1239        F: FnMut(&K, V, V) -> Option<V>,
1240    {
1241        self.symmetric_difference_with_key(other, f)
1242    }
1243
1244    /// Construct the symmetric difference between two maps by using a function
1245    /// to decide what to do if a key occurs in both. The function
1246    /// receives the key as well as both values.
1247    ///
1248    /// Time: O(n log n)
1249    ///
1250    /// # Examples
1251    ///
1252    /// ```
1253    /// # #[macro_use] extern crate im_rc as im;
1254    /// # use im::ordmap::OrdMap;
1255    /// let map1 = ordmap!{1 => 1, 3 => 4};
1256    /// let map2 = ordmap!{2 => 2, 3 => 5};
1257    /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 9};
1258    /// assert_eq!(expected, map1.symmetric_difference_with_key(
1259    ///     map2,
1260    ///     |key, left, right| Some(left + right)
1261    /// ));
1262    /// ```
1263    #[must_use]
1264    pub fn symmetric_difference_with_key<F>(mut self, other: Self, mut f: F) -> Self
1265    where
1266        F: FnMut(&K, V, V) -> Option<V>,
1267    {
1268        let mut out = Self::default();
1269        for (key, right_value) in other {
1270            match self.remove(&key) {
1271                None => {
1272                    out.insert(key, right_value);
1273                }
1274                Some(left_value) => {
1275                    if let Some(final_value) = f(&key, left_value, right_value) {
1276                        out.insert(key, final_value);
1277                    }
1278                }
1279            }
1280        }
1281        out.union(self)
1282    }
1283
1284    /// Construct the relative complement between two maps by discarding keys
1285    /// which occur in `other`.
1286    ///
1287    /// Time: O(m log n) where m is the size of the other map
1288    ///
1289    /// # Examples
1290    ///
1291    /// ```
1292    /// # #[macro_use] extern crate im_rc as im;
1293    /// # use im::ordmap::OrdMap;
1294    /// let map1 = ordmap!{1 => 1, 3 => 4};
1295    /// let map2 = ordmap!{2 => 2, 3 => 5};
1296    /// let expected = ordmap!{1 => 1};
1297    /// assert_eq!(expected, map1.relative_complement(map2));
1298    /// ```
1299    #[inline]
1300    #[must_use]
1301    pub fn relative_complement(mut self, other: Self) -> Self {
1302        for (key, _) in other {
1303            let _ = self.remove(&key);
1304        }
1305        self
1306    }
1307
1308    /// Construct the intersection of two maps, keeping the values
1309    /// from the current map.
1310    ///
1311    /// Time: O(n log n)
1312    ///
1313    /// # Examples
1314    ///
1315    /// ```
1316    /// # #[macro_use] extern crate im_rc as im;
1317    /// # use im::ordmap::OrdMap;
1318    /// let map1 = ordmap!{1 => 1, 2 => 2};
1319    /// let map2 = ordmap!{2 => 3, 3 => 4};
1320    /// let expected = ordmap!{2 => 2};
1321    /// assert_eq!(expected, map1.intersection(map2));
1322    /// ```
1323    #[inline]
1324    #[must_use]
1325    pub fn intersection(self, other: Self) -> Self {
1326        self.intersection_with_key(other, |_, v, _| v)
1327    }
1328
1329    /// Construct the intersection of two maps, calling a function
1330    /// with both values for each key and using the result as the
1331    /// value for the key.
1332    ///
1333    /// Time: O(n log n)
1334    #[inline]
1335    #[must_use]
1336    pub fn intersection_with<B, C, F>(self, other: OrdMap<K, B>, mut f: F) -> OrdMap<K, C>
1337    where
1338        B: Clone,
1339        C: Clone,
1340        F: FnMut(V, B) -> C,
1341    {
1342        self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
1343    }
1344
1345    /// Construct the intersection of two maps, calling a function
1346    /// with the key and both values for each key and using the result
1347    /// as the value for the key.
1348    ///
1349    /// Time: O(n log n)
1350    ///
1351    /// # Examples
1352    ///
1353    /// ```
1354    /// # #[macro_use] extern crate im_rc as im;
1355    /// # use im::ordmap::OrdMap;
1356    /// let map1 = ordmap!{1 => 1, 2 => 2};
1357    /// let map2 = ordmap!{2 => 3, 3 => 4};
1358    /// let expected = ordmap!{2 => 5};
1359    /// assert_eq!(expected, map1.intersection_with_key(
1360    ///     map2,
1361    ///     |key, left, right| left + right
1362    /// ));
1363    /// ```
1364    #[must_use]
1365    pub fn intersection_with_key<B, C, F>(mut self, other: OrdMap<K, B>, mut f: F) -> OrdMap<K, C>
1366    where
1367        B: Clone,
1368        C: Clone,
1369        F: FnMut(&K, V, B) -> C,
1370    {
1371        let mut out = OrdMap::<K, C>::default();
1372        for (key, right_value) in other {
1373            match self.remove(&key) {
1374                None => (),
1375                Some(left_value) => {
1376                    let result = f(&key, left_value, right_value);
1377                    out.insert(key, result);
1378                }
1379            }
1380        }
1381        out
1382    }
1383
1384    /// Split a map into two, with the left hand map containing keys
1385    /// which are smaller than `split`, and the right hand map
1386    /// containing keys which are larger than `split`.
1387    ///
1388    /// The `split` mapping is discarded.
1389    #[must_use]
1390    pub fn split<BK>(&self, split: &BK) -> (Self, Self)
1391    where
1392        BK: Ord + ?Sized,
1393        K: Borrow<BK>,
1394    {
1395        let (l, _, r) = self.split_lookup(split);
1396        (l, r)
1397    }
1398
1399    /// Split a map into two, with the left hand map containing keys
1400    /// which are smaller than `split`, and the right hand map
1401    /// containing keys which are larger than `split`.
1402    ///
1403    /// Returns both the two maps and the value of `split`.
1404    #[must_use]
1405    pub fn split_lookup<BK>(&self, split: &BK) -> (Self, Option<V>, Self)
1406    where
1407        BK: Ord + ?Sized,
1408        K: Borrow<BK>,
1409    {
1410        // TODO this is atrociously slow, got to be a better way
1411        self.iter()
1412            .fold((ordmap![], None, ordmap![]), |(l, m, r), (k, v)| {
1413                match k.borrow().cmp(split) {
1414                    Ordering::Less => (l.update(k.clone(), v.clone()), m, r),
1415                    Ordering::Equal => (l, Some(v.clone()), r),
1416                    Ordering::Greater => (l, m, r.update(k.clone(), v.clone())),
1417                }
1418            })
1419    }
1420
1421    /// Construct a map with only the `n` smallest keys from a given
1422    /// map.
1423    #[must_use]
1424    pub fn take(&self, n: usize) -> Self {
1425        self.iter()
1426            .take(n)
1427            .map(|(k, v)| (k.clone(), v.clone()))
1428            .collect()
1429    }
1430
1431    /// Construct a map with the `n` smallest keys removed from a
1432    /// given map.
1433    #[must_use]
1434    pub fn skip(&self, n: usize) -> Self {
1435        self.iter()
1436            .skip(n)
1437            .map(|(k, v)| (k.clone(), v.clone()))
1438            .collect()
1439    }
1440
1441    /// Remove the smallest key from a map, and return its value as
1442    /// well as the updated map.
1443    #[must_use]
1444    pub fn without_min(&self) -> (Option<V>, Self) {
1445        let (pop, next) = self.without_min_with_key();
1446        (pop.map(|(_, v)| v), next)
1447    }
1448
1449    /// Remove the smallest key from a map, and return that key, its
1450    /// value as well as the updated map.
1451    #[must_use]
1452    pub fn without_min_with_key(&self) -> (Option<(K, V)>, Self) {
1453        match self.get_min() {
1454            None => (None, self.clone()),
1455            Some((k, _)) => {
1456                let (key, value, next) = self.extract_with_key(k).unwrap();
1457                (Some((key, value)), next)
1458            }
1459        }
1460    }
1461
1462    /// Remove the largest key from a map, and return its value as
1463    /// well as the updated map.
1464    #[must_use]
1465    pub fn without_max(&self) -> (Option<V>, Self) {
1466        let (pop, next) = self.without_max_with_key();
1467        (pop.map(|(_, v)| v), next)
1468    }
1469
1470    /// Remove the largest key from a map, and return that key, its
1471    /// value as well as the updated map.
1472    #[must_use]
1473    pub fn without_max_with_key(&self) -> (Option<(K, V)>, Self) {
1474        match self.get_max() {
1475            None => (None, self.clone()),
1476            Some((k, _)) => {
1477                let (key, value, next) = self.extract_with_key(k).unwrap();
1478                (Some((key, value)), next)
1479            }
1480        }
1481    }
1482
1483    /// Get the [`Entry`][Entry] for a key in the map for in-place manipulation.
1484    ///
1485    /// Time: O(log n)
1486    ///
1487    /// [Entry]: enum.Entry.html
1488    #[must_use]
1489    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1490        if self.contains_key(&key) {
1491            Entry::Occupied(OccupiedEntry { map: self, key })
1492        } else {
1493            Entry::Vacant(VacantEntry { map: self, key })
1494        }
1495    }
1496}
1497
1498// Entries
1499
1500/// A handle for a key and its associated value.
1501pub enum Entry<'a, K, V>
1502where
1503    K: Ord + Clone,
1504    V: Clone,
1505{
1506    /// An entry which exists in the map.
1507    Occupied(OccupiedEntry<'a, K, V>),
1508    /// An entry which doesn't exist in the map.
1509    Vacant(VacantEntry<'a, K, V>),
1510}
1511
1512impl<'a, K, V> Entry<'a, K, V>
1513where
1514    K: Ord + Clone,
1515    V: Clone,
1516{
1517    /// Insert the default value provided if there was no value
1518    /// already, and return a mutable reference to the value.
1519    pub fn or_insert(self, default: V) -> &'a mut V {
1520        self.or_insert_with(|| default)
1521    }
1522
1523    /// Insert the default value from the provided function if there
1524    /// was no value already, and return a mutable reference to the
1525    /// value.
1526    pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1527    where
1528        F: FnOnce() -> V,
1529    {
1530        match self {
1531            Entry::Occupied(entry) => entry.into_mut(),
1532            Entry::Vacant(entry) => entry.insert(default()),
1533        }
1534    }
1535
1536    /// Insert a default value if there was no value already, and
1537    /// return a mutable reference to the value.
1538    pub fn or_default(self) -> &'a mut V
1539    where
1540        V: Default,
1541    {
1542        self.or_insert_with(Default::default)
1543    }
1544
1545    /// Get the key for this entry.
1546    #[must_use]
1547    pub fn key(&self) -> &K {
1548        match self {
1549            Entry::Occupied(entry) => entry.key(),
1550            Entry::Vacant(entry) => entry.key(),
1551        }
1552    }
1553
1554    /// Call the provided function to modify the value if the value
1555    /// exists.
1556    pub fn and_modify<F>(mut self, f: F) -> Self
1557    where
1558        F: FnOnce(&mut V),
1559    {
1560        match &mut self {
1561            Entry::Occupied(ref mut entry) => f(entry.get_mut()),
1562            Entry::Vacant(_) => (),
1563        }
1564        self
1565    }
1566}
1567
1568/// An entry for a mapping that already exists in the map.
1569pub struct OccupiedEntry<'a, K, V>
1570where
1571    K: Ord + Clone,
1572    V: Clone,
1573{
1574    map: &'a mut OrdMap<K, V>,
1575    key: K,
1576}
1577
1578impl<'a, K, V> OccupiedEntry<'a, K, V>
1579where
1580    K: 'a + Ord + Clone,
1581    V: 'a + Clone,
1582{
1583    /// Get the key for this entry.
1584    #[must_use]
1585    pub fn key(&self) -> &K {
1586        &self.key
1587    }
1588
1589    /// Remove this entry from the map and return the removed mapping.
1590    pub fn remove_entry(self) -> (K, V) {
1591        self.map
1592            .remove_with_key(&self.key)
1593            .expect("ordmap::OccupiedEntry::remove_entry: key has vanished!")
1594    }
1595
1596    /// Get the current value.
1597    #[must_use]
1598    pub fn get(&self) -> &V {
1599        self.map.get(&self.key).unwrap()
1600    }
1601
1602    /// Get a mutable reference to the current value.
1603    #[must_use]
1604    pub fn get_mut(&mut self) -> &mut V {
1605        self.map.get_mut(&self.key).unwrap()
1606    }
1607
1608    /// Convert this entry into a mutable reference.
1609    #[must_use]
1610    pub fn into_mut(self) -> &'a mut V {
1611        self.map.get_mut(&self.key).unwrap()
1612    }
1613
1614    /// Overwrite the current value.
1615    pub fn insert(&mut self, value: V) -> V {
1616        mem::replace(self.get_mut(), value)
1617    }
1618
1619    /// Remove this entry from the map and return the removed value.
1620    pub fn remove(self) -> V {
1621        self.remove_entry().1
1622    }
1623}
1624
1625/// An entry for a mapping that does not already exist in the map.
1626pub struct VacantEntry<'a, K, V>
1627where
1628    K: Ord + Clone,
1629    V: Clone,
1630{
1631    map: &'a mut OrdMap<K, V>,
1632    key: K,
1633}
1634
1635impl<'a, K, V> VacantEntry<'a, K, V>
1636where
1637    K: 'a + Ord + Clone,
1638    V: 'a + Clone,
1639{
1640    /// Get the key for this entry.
1641    #[must_use]
1642    pub fn key(&self) -> &K {
1643        &self.key
1644    }
1645
1646    /// Convert this entry into its key.
1647    #[must_use]
1648    pub fn into_key(self) -> K {
1649        self.key
1650    }
1651
1652    /// Insert a value into this entry.
1653    pub fn insert(self, value: V) -> &'a mut V {
1654        self.map.insert(self.key.clone(), value);
1655        // TODO insert_mut ought to return this reference
1656        self.map.get_mut(&self.key).unwrap()
1657    }
1658}
1659
1660// Core traits
1661
1662impl<K, V> Clone for OrdMap<K, V> {
1663    /// Clone a map.
1664    ///
1665    /// Time: O(1)
1666    #[inline]
1667    fn clone(&self) -> Self {
1668        OrdMap {
1669            size: self.size,
1670            pool: self.pool.clone(),
1671            root: self.root.clone(),
1672        }
1673    }
1674}
1675
1676#[cfg(not(has_specialisation))]
1677impl<K, V> PartialEq for OrdMap<K, V>
1678where
1679    K: Ord + PartialEq,
1680    V: PartialEq,
1681{
1682    fn eq(&self, other: &Self) -> bool {
1683        self.len() == other.len() && self.diff(other).next().is_none()
1684    }
1685}
1686
1687#[cfg(has_specialisation)]
1688impl<K, V> PartialEq for OrdMap<K, V>
1689where
1690    K: Ord + PartialEq,
1691    V: PartialEq,
1692{
1693    default fn eq(&self, other: &Self) -> bool {
1694        self.len() == other.len() && self.diff(other).next().is_none()
1695    }
1696}
1697
1698#[cfg(has_specialisation)]
1699impl<K, V> PartialEq for OrdMap<K, V>
1700where
1701    K: Ord + Eq,
1702    V: Eq,
1703{
1704    fn eq(&self, other: &Self) -> bool {
1705        PoolRef::ptr_eq(&self.root, &other.root)
1706            || (self.len() == other.len() && self.diff(other).next().is_none())
1707    }
1708}
1709
1710impl<K: Ord + Eq, V: Eq> Eq for OrdMap<K, V> {}
1711
1712impl<K, V> PartialOrd for OrdMap<K, V>
1713where
1714    K: Ord,
1715    V: PartialOrd,
1716{
1717    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1718        self.iter().partial_cmp(other.iter())
1719    }
1720}
1721
1722impl<K, V> Ord for OrdMap<K, V>
1723where
1724    K: Ord,
1725    V: Ord,
1726{
1727    fn cmp(&self, other: &Self) -> Ordering {
1728        self.iter().cmp(other.iter())
1729    }
1730}
1731
1732impl<K, V> Hash for OrdMap<K, V>
1733where
1734    K: Ord + Hash,
1735    V: Hash,
1736{
1737    fn hash<H>(&self, state: &mut H)
1738    where
1739        H: Hasher,
1740    {
1741        for i in self.iter() {
1742            i.hash(state);
1743        }
1744    }
1745}
1746
1747impl<K, V> Default for OrdMap<K, V> {
1748    fn default() -> Self {
1749        Self::new()
1750    }
1751}
1752
1753impl<'a, K, V> Add for &'a OrdMap<K, V>
1754where
1755    K: Ord + Clone,
1756    V: Clone,
1757{
1758    type Output = OrdMap<K, V>;
1759
1760    fn add(self, other: Self) -> Self::Output {
1761        self.clone().union(other.clone())
1762    }
1763}
1764
1765impl<K, V> Add for OrdMap<K, V>
1766where
1767    K: Ord + Clone,
1768    V: Clone,
1769{
1770    type Output = OrdMap<K, V>;
1771
1772    fn add(self, other: Self) -> Self::Output {
1773        self.union(other)
1774    }
1775}
1776
1777impl<K, V> Sum for OrdMap<K, V>
1778where
1779    K: Ord + Clone,
1780    V: Clone,
1781{
1782    fn sum<I>(it: I) -> Self
1783    where
1784        I: Iterator<Item = Self>,
1785    {
1786        it.fold(Self::default(), |a, b| a + b)
1787    }
1788}
1789
1790impl<K, V, RK, RV> Extend<(RK, RV)> for OrdMap<K, V>
1791where
1792    K: Ord + Clone + From<RK>,
1793    V: Clone + From<RV>,
1794{
1795    fn extend<I>(&mut self, iter: I)
1796    where
1797        I: IntoIterator<Item = (RK, RV)>,
1798    {
1799        for (key, value) in iter {
1800            self.insert(From::from(key), From::from(value));
1801        }
1802    }
1803}
1804
1805impl<'a, BK, K, V> Index<&'a BK> for OrdMap<K, V>
1806where
1807    BK: Ord + ?Sized,
1808    K: Ord + Borrow<BK>,
1809{
1810    type Output = V;
1811
1812    fn index(&self, key: &BK) -> &Self::Output {
1813        match self.root.lookup(key) {
1814            None => panic!("OrdMap::index: invalid key"),
1815            Some(&(_, ref value)) => value,
1816        }
1817    }
1818}
1819
1820impl<'a, BK, K, V> IndexMut<&'a BK> for OrdMap<K, V>
1821where
1822    BK: Ord + ?Sized,
1823    K: Ord + Clone + Borrow<BK>,
1824    V: Clone,
1825{
1826    fn index_mut(&mut self, key: &BK) -> &mut Self::Output {
1827        let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
1828        match root.lookup_mut(&self.pool.0, key) {
1829            None => panic!("OrdMap::index: invalid key"),
1830            Some(&mut (_, ref mut value)) => value,
1831        }
1832    }
1833}
1834
1835impl<K, V> Debug for OrdMap<K, V>
1836where
1837    K: Ord + Debug,
1838    V: Debug,
1839{
1840    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1841        let mut d = f.debug_map();
1842        for (k, v) in self.iter() {
1843            d.entry(k, v);
1844        }
1845        d.finish()
1846    }
1847}
1848
1849// Iterators
1850
1851/// An iterator over the key/value pairs of a map.
1852pub struct Iter<'a, K, V> {
1853    it: RangedIter<'a, (K, V)>,
1854}
1855
1856impl<'a, K, V> Iterator for Iter<'a, K, V>
1857where
1858    (K, V): 'a + BTreeValue,
1859{
1860    type Item = (&'a K, &'a V);
1861
1862    fn next(&mut self) -> Option<Self::Item> {
1863        self.it.next().map(|(k, v)| (k, v))
1864    }
1865
1866    fn size_hint(&self) -> (usize, Option<usize>) {
1867        (self.it.remaining, Some(self.it.remaining))
1868    }
1869}
1870
1871impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V>
1872where
1873    (K, V): 'a + BTreeValue,
1874{
1875    fn next_back(&mut self) -> Option<Self::Item> {
1876        self.it.next_back().map(|(k, v)| (k, v))
1877    }
1878}
1879
1880impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> where (K, V): 'a + BTreeValue {}
1881
1882/// An iterator over the differences between two maps.
1883pub struct DiffIter<'a, K, V> {
1884    it: NodeDiffIter<'a, (K, V)>,
1885}
1886
1887/// A description of a difference between two ordered maps.
1888#[derive(PartialEq, Eq, Debug)]
1889pub enum DiffItem<'a, K, V> {
1890    /// This value has been added to the new map.
1891    Add(&'a K, &'a V),
1892    /// This value has been changed between the two maps.
1893    Update {
1894        /// The old value.
1895        old: (&'a K, &'a V),
1896        /// The new value.
1897        new: (&'a K, &'a V),
1898    },
1899    /// This value has been removed from the new map.
1900    Remove(&'a K, &'a V),
1901}
1902
1903impl<'a, K, V> Iterator for DiffIter<'a, K, V>
1904where
1905    (K, V): 'a + BTreeValue + PartialEq,
1906{
1907    type Item = DiffItem<'a, K, V>;
1908
1909    fn next(&mut self) -> Option<Self::Item> {
1910        self.it.next().map(|item| match item {
1911            NodeDiffItem::Add((k, v)) => DiffItem::Add(k, v),
1912            NodeDiffItem::Update {
1913                old: (oldk, oldv),
1914                new: (newk, newv),
1915            } => DiffItem::Update {
1916                old: (oldk, oldv),
1917                new: (newk, newv),
1918            },
1919            NodeDiffItem::Remove((k, v)) => DiffItem::Remove(k, v),
1920        })
1921    }
1922}
1923
1924/// An iterator ove the keys of a map.
1925pub struct Keys<'a, K, V> {
1926    it: Iter<'a, K, V>,
1927}
1928
1929impl<'a, K, V> Iterator for Keys<'a, K, V>
1930where
1931    K: 'a + Ord,
1932    V: 'a,
1933{
1934    type Item = &'a K;
1935
1936    fn next(&mut self) -> Option<Self::Item> {
1937        self.it.next().map(|(k, _)| k)
1938    }
1939
1940    fn size_hint(&self) -> (usize, Option<usize>) {
1941        self.it.size_hint()
1942    }
1943}
1944
1945impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V>
1946where
1947    K: 'a + Ord,
1948    V: 'a,
1949{
1950    fn next_back(&mut self) -> Option<Self::Item> {
1951        self.it.next_back().map(|(k, _)| k)
1952    }
1953}
1954
1955impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V>
1956where
1957    K: 'a + Ord,
1958    V: 'a,
1959{
1960}
1961
1962/// An iterator over the values of a map.
1963pub struct Values<'a, K, V> {
1964    it: Iter<'a, K, V>,
1965}
1966
1967impl<'a, K, V> Iterator for Values<'a, K, V>
1968where
1969    K: 'a + Ord,
1970    V: 'a,
1971{
1972    type Item = &'a V;
1973
1974    fn next(&mut self) -> Option<Self::Item> {
1975        self.it.next().map(|(_, v)| v)
1976    }
1977
1978    fn size_hint(&self) -> (usize, Option<usize>) {
1979        self.it.size_hint()
1980    }
1981}
1982
1983impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V>
1984where
1985    K: 'a + Ord,
1986    V: 'a,
1987{
1988    fn next_back(&mut self) -> Option<Self::Item> {
1989        self.it.next_back().map(|(_, v)| v)
1990    }
1991}
1992
1993impl<'a, K, V> ExactSizeIterator for Values<'a, K, V>
1994where
1995    K: 'a + Ord,
1996    V: 'a,
1997{
1998}
1999
2000impl<K, V, RK, RV> FromIterator<(RK, RV)> for OrdMap<K, V>
2001where
2002    K: Ord + Clone + From<RK>,
2003    V: Clone + From<RV>,
2004{
2005    fn from_iter<T>(i: T) -> Self
2006    where
2007        T: IntoIterator<Item = (RK, RV)>,
2008    {
2009        let mut m = OrdMap::default();
2010        for (k, v) in i {
2011            m.insert(From::from(k), From::from(v));
2012        }
2013        m
2014    }
2015}
2016
2017impl<'a, K, V> IntoIterator for &'a OrdMap<K, V>
2018where
2019    K: Ord,
2020{
2021    type Item = (&'a K, &'a V);
2022    type IntoIter = Iter<'a, K, V>;
2023
2024    fn into_iter(self) -> Self::IntoIter {
2025        self.iter()
2026    }
2027}
2028
2029impl<K, V> IntoIterator for OrdMap<K, V>
2030where
2031    K: Ord + Clone,
2032    V: Clone,
2033{
2034    type Item = (K, V);
2035    type IntoIter = ConsumingIter<(K, V)>;
2036
2037    fn into_iter(self) -> Self::IntoIter {
2038        ConsumingIter::new(&self.root, self.size)
2039    }
2040}
2041
2042// Conversions
2043
2044impl<K, V> AsRef<OrdMap<K, V>> for OrdMap<K, V> {
2045    fn as_ref(&self) -> &Self {
2046        self
2047    }
2048}
2049
2050impl<'m, 'k, 'v, K, V, OK, OV> From<&'m OrdMap<&'k K, &'v V>> for OrdMap<OK, OV>
2051where
2052    K: Ord + ToOwned<Owned = OK> + ?Sized,
2053    V: ToOwned<Owned = OV> + ?Sized,
2054    OK: Ord + Clone + Borrow<K>,
2055    OV: Clone + Borrow<V>,
2056{
2057    fn from(m: &OrdMap<&K, &V>) -> Self {
2058        m.iter()
2059            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
2060            .collect()
2061    }
2062}
2063
2064impl<'a, K, V, RK, RV, OK, OV> From<&'a [(RK, RV)]> for OrdMap<K, V>
2065where
2066    K: Ord + Clone + From<OK>,
2067    V: Clone + From<OV>,
2068    OK: Borrow<RK>,
2069    OV: Borrow<RV>,
2070    RK: ToOwned<Owned = OK>,
2071    RV: ToOwned<Owned = OV>,
2072{
2073    fn from(m: &'a [(RK, RV)]) -> OrdMap<K, V> {
2074        m.iter()
2075            .map(|&(ref k, ref v)| (k.to_owned(), v.to_owned()))
2076            .collect()
2077    }
2078}
2079
2080impl<K, V, RK, RV> From<Vec<(RK, RV)>> for OrdMap<K, V>
2081where
2082    K: Ord + Clone + From<RK>,
2083    V: Clone + From<RV>,
2084{
2085    fn from(m: Vec<(RK, RV)>) -> OrdMap<K, V> {
2086        m.into_iter().collect()
2087    }
2088}
2089
2090impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a Vec<(RK, RV)>> for OrdMap<K, V>
2091where
2092    K: Ord + Clone + From<OK>,
2093    V: Clone + From<OV>,
2094    OK: Borrow<RK>,
2095    OV: Borrow<RV>,
2096    RK: ToOwned<Owned = OK>,
2097    RV: ToOwned<Owned = OV>,
2098{
2099    fn from(m: &'a Vec<(RK, RV)>) -> OrdMap<K, V> {
2100        m.iter()
2101            .map(|&(ref k, ref v)| (k.to_owned(), v.to_owned()))
2102            .collect()
2103    }
2104}
2105
2106impl<K: Ord, V, RK: Eq + Hash, RV> From<collections::HashMap<RK, RV>> for OrdMap<K, V>
2107where
2108    K: Ord + Clone + From<RK>,
2109    V: Clone + From<RV>,
2110{
2111    fn from(m: collections::HashMap<RK, RV>) -> OrdMap<K, V> {
2112        m.into_iter().collect()
2113    }
2114}
2115
2116impl<'a, K, V, OK, OV, RK, RV> From<&'a collections::HashMap<RK, RV>> for OrdMap<K, V>
2117where
2118    K: Ord + Clone + From<OK>,
2119    V: Clone + From<OV>,
2120    OK: Borrow<RK>,
2121    OV: Borrow<RV>,
2122    RK: Hash + Eq + ToOwned<Owned = OK>,
2123    RV: ToOwned<Owned = OV>,
2124{
2125    fn from(m: &'a collections::HashMap<RK, RV>) -> OrdMap<K, V> {
2126        m.iter()
2127            .map(|(k, v)| (k.to_owned(), v.to_owned()))
2128            .collect()
2129    }
2130}
2131
2132impl<K: Ord, V, RK, RV> From<collections::BTreeMap<RK, RV>> for OrdMap<K, V>
2133where
2134    K: Ord + Clone + From<RK>,
2135    V: Clone + From<RV>,
2136{
2137    fn from(m: collections::BTreeMap<RK, RV>) -> OrdMap<K, V> {
2138        m.into_iter().collect()
2139    }
2140}
2141
2142impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a collections::BTreeMap<RK, RV>> for OrdMap<K, V>
2143where
2144    K: Ord + Clone + From<OK>,
2145    V: Clone + From<OV>,
2146    OK: Borrow<RK>,
2147    OV: Borrow<RV>,
2148    RK: Ord + ToOwned<Owned = OK>,
2149    RV: ToOwned<Owned = OV>,
2150{
2151    fn from(m: &'a collections::BTreeMap<RK, RV>) -> OrdMap<K, V> {
2152        m.iter()
2153            .map(|(k, v)| (k.to_owned(), v.to_owned()))
2154            .collect()
2155    }
2156}
2157
2158impl<K: Ord + Hash + Eq + Clone, V: Clone, S: BuildHasher> From<HashMap<K, V, S>> for OrdMap<K, V> {
2159    fn from(m: HashMap<K, V, S>) -> Self {
2160        m.into_iter().collect()
2161    }
2162}
2163
2164impl<'a, K: Ord + Hash + Eq + Clone, V: Clone, S: BuildHasher> From<&'a HashMap<K, V, S>>
2165    for OrdMap<K, V>
2166{
2167    fn from(m: &'a HashMap<K, V, S>) -> Self {
2168        m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
2169    }
2170}
2171
2172// Proptest
2173#[cfg(any(test, feature = "proptest"))]
2174#[doc(hidden)]
2175pub mod proptest {
2176    #[deprecated(
2177        since = "14.3.0",
2178        note = "proptest strategies have moved to im::proptest"
2179    )]
2180    pub use crate::proptest::ord_map;
2181}
2182
2183// Tests
2184
2185#[cfg(test)]
2186mod test {
2187    use super::*;
2188    use crate::proptest::*;
2189    use crate::test::is_sorted;
2190    use ::proptest::num::{i16, usize};
2191    use ::proptest::{bool, collection, proptest};
2192
2193    #[test]
2194    fn iterates_in_order() {
2195        let map = ordmap! {
2196            2 => 22,
2197            1 => 11,
2198            3 => 33,
2199            8 => 88,
2200            9 => 99,
2201            4 => 44,
2202            5 => 55,
2203            7 => 77,
2204            6 => 66
2205        };
2206        let mut it = map.iter();
2207        assert_eq!(it.next(), Some((&1, &11)));
2208        assert_eq!(it.next(), Some((&2, &22)));
2209        assert_eq!(it.next(), Some((&3, &33)));
2210        assert_eq!(it.next(), Some((&4, &44)));
2211        assert_eq!(it.next(), Some((&5, &55)));
2212        assert_eq!(it.next(), Some((&6, &66)));
2213        assert_eq!(it.next(), Some((&7, &77)));
2214        assert_eq!(it.next(), Some((&8, &88)));
2215        assert_eq!(it.next(), Some((&9, &99)));
2216        assert_eq!(it.next(), None);
2217    }
2218
2219    #[test]
2220    fn into_iter() {
2221        let map = ordmap! {
2222            2 => 22,
2223            1 => 11,
2224            3 => 33,
2225            8 => 88,
2226            9 => 99,
2227            4 => 44,
2228            5 => 55,
2229            7 => 77,
2230            6 => 66
2231        };
2232        let mut vec = vec![];
2233        for (k, v) in map {
2234            assert_eq!(k * 11, v);
2235            vec.push(k)
2236        }
2237        assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
2238    }
2239
2240    #[test]
2241    fn deletes_correctly() {
2242        let map = ordmap! {
2243            2 => 22,
2244            1 => 11,
2245            3 => 33,
2246            8 => 88,
2247            9 => 99,
2248            4 => 44,
2249            5 => 55,
2250            7 => 77,
2251            6 => 66
2252        };
2253        assert_eq!(map.extract(&11), None);
2254        let (popped, less) = map.extract(&5).unwrap();
2255        assert_eq!(popped, 55);
2256        let mut it = less.iter();
2257        assert_eq!(it.next(), Some((&1, &11)));
2258        assert_eq!(it.next(), Some((&2, &22)));
2259        assert_eq!(it.next(), Some((&3, &33)));
2260        assert_eq!(it.next(), Some((&4, &44)));
2261        assert_eq!(it.next(), Some((&6, &66)));
2262        assert_eq!(it.next(), Some((&7, &77)));
2263        assert_eq!(it.next(), Some((&8, &88)));
2264        assert_eq!(it.next(), Some((&9, &99)));
2265        assert_eq!(it.next(), None);
2266    }
2267
2268    #[test]
2269    fn debug_output() {
2270        assert_eq!(
2271            format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }),
2272            "{1: 2, 3: 4, 5: 6}"
2273        );
2274    }
2275
2276    #[test]
2277    fn equality2() {
2278        let v1 = "1".to_string();
2279        let v2 = "1".to_string();
2280        assert_eq!(v1, v2);
2281        let p1 = Vec::<String>::new();
2282        let p2 = Vec::<String>::new();
2283        assert_eq!(p1, p2);
2284        let c1 = OrdMap::unit(v1, p1);
2285        let c2 = OrdMap::unit(v2, p2);
2286        assert_eq!(c1, c2);
2287    }
2288
2289    #[test]
2290    fn insert_remove_single_mut() {
2291        let mut m = OrdMap::new();
2292        m.insert(0, 0);
2293        assert_eq!(OrdMap::unit(0, 0), m);
2294        m.remove(&0);
2295        assert_eq!(OrdMap::new(), m);
2296    }
2297
2298    #[test]
2299    fn double_ended_iterator_1() {
2300        let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2301        let mut it = m.iter();
2302        assert_eq!(Some((&1, &1)), it.next());
2303        assert_eq!(Some((&4, &4)), it.next_back());
2304        assert_eq!(Some((&2, &2)), it.next());
2305        assert_eq!(Some((&3, &3)), it.next_back());
2306        assert_eq!(None, it.next());
2307    }
2308
2309    #[test]
2310    fn double_ended_iterator_2() {
2311        let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2312        let mut it = m.iter();
2313        assert_eq!(Some((&1, &1)), it.next());
2314        assert_eq!(Some((&4, &4)), it.next_back());
2315        assert_eq!(Some((&2, &2)), it.next());
2316        assert_eq!(Some((&3, &3)), it.next_back());
2317        assert_eq!(None, it.next_back());
2318    }
2319
2320    #[test]
2321    fn safe_mutation() {
2322        let v1 = (0..131_072).map(|i| (i, i)).collect::<OrdMap<_, _>>();
2323        let mut v2 = v1.clone();
2324        v2.insert(131_000, 23);
2325        assert_eq!(Some(&23), v2.get(&131_000));
2326        assert_eq!(Some(&131_000), v1.get(&131_000));
2327    }
2328
2329    #[test]
2330    fn index_operator() {
2331        let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6};
2332        assert_eq!(4, map[&3]);
2333        map[&3] = 8;
2334        assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map);
2335    }
2336
2337    #[test]
2338    fn entry_api() {
2339        let mut map = ordmap! {"bar" => 5};
2340        map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2341        assert_eq!(1, map[&"foo"]);
2342        map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2343        assert_eq!(6, map[&"foo"]);
2344        map.entry("bar").and_modify(|v| *v += 5).or_insert(1);
2345        assert_eq!(10, map[&"bar"]);
2346        assert_eq!(
2347            10,
2348            match map.entry("bar") {
2349                Entry::Occupied(entry) => entry.remove(),
2350                _ => panic!(),
2351            }
2352        );
2353        assert!(!map.contains_key(&"bar"));
2354    }
2355
2356    #[test]
2357    fn match_string_keys_with_string_slices() {
2358        let mut map: OrdMap<String, i32> =
2359            From::from(&ordmap! { "foo" => &1, "bar" => &2, "baz" => &3 });
2360        assert_eq!(Some(&1), map.get("foo"));
2361        map = map.without("foo");
2362        assert_eq!(Some(3), map.remove("baz"));
2363        map["bar"] = 8;
2364        assert_eq!(8, map["bar"]);
2365    }
2366
2367    #[test]
2368    fn ranged_iter() {
2369        let map: OrdMap<i32, i32> = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6, 7=>8];
2370        let range: Vec<(i32, i32)> = map.range(..).map(|(k, v)| (*k, *v)).collect();
2371        assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (7, 8)], range);
2372        let range: Vec<(i32, i32)> = map.range(..).rev().map(|(k, v)| (*k, *v)).collect();
2373        assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
2374        let range: Vec<(i32, i32)> = map.range(2..5).map(|(k, v)| (*k, *v)).collect();
2375        assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
2376        let range: Vec<(i32, i32)> = map.range(2..5).rev().map(|(k, v)| (*k, *v)).collect();
2377        assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
2378        let range: Vec<(i32, i32)> = map.range(3..).map(|(k, v)| (*k, *v)).collect();
2379        assert_eq!(vec![(3, 4), (4, 5), (5, 6), (7, 8)], range);
2380        let range: Vec<(i32, i32)> = map.range(3..).rev().map(|(k, v)| (*k, *v)).collect();
2381        assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4)], range);
2382        let range: Vec<(i32, i32)> = map.range(..4).map(|(k, v)| (*k, *v)).collect();
2383        assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2384        let range: Vec<(i32, i32)> = map.range(..4).rev().map(|(k, v)| (*k, *v)).collect();
2385        assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2386        let range: Vec<(i32, i32)> = map.range(..=3).map(|(k, v)| (*k, *v)).collect();
2387        assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2388        let range: Vec<(i32, i32)> = map.range(..=3).rev().map(|(k, v)| (*k, *v)).collect();
2389        assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2390        let range: Vec<(i32, i32)> = map.range(..6).map(|(k, v)| (*k, *v)).collect();
2391        assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2392        let range: Vec<(i32, i32)> = map.range(..=6).map(|(k, v)| (*k, *v)).collect();
2393        assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2394    }
2395
2396    #[test]
2397    fn range_iter_big() {
2398        use crate::nodes::btree::NODE_SIZE;
2399        use std::ops::Bound::Included;
2400        const N: usize = NODE_SIZE * NODE_SIZE * 5; // enough for a sizeable 3 level tree
2401
2402        let data = (1usize..N).filter(|i| i % 2 == 0).map(|i| (i, ()));
2403        let bmap = data
2404            .clone()
2405            .collect::<std::collections::BTreeMap<usize, ()>>();
2406        let omap = data.collect::<OrdMap<usize, ()>>();
2407
2408        for i in (0..NODE_SIZE * 5).chain(N - NODE_SIZE * 5..=N + 1) {
2409            assert_eq!(omap.range(i..).count(), bmap.range(i..).count());
2410            assert_eq!(omap.range(..i).count(), bmap.range(..i).count());
2411            assert_eq!(omap.range(i..i + 7).count(), bmap.range(i..i + 7).count());
2412            assert_eq!(omap.range(i..=i + 7).count(), bmap.range(i..=i + 7).count());
2413            assert_eq!(
2414                omap.range((Included(i), Included(i + 7))).count(),
2415                bmap.range((Included(i), Included(i + 7))).count(),
2416            );
2417        }
2418    }
2419
2420    #[test]
2421    fn issue_124() {
2422        let mut map = OrdMap::new();
2423        let contents = include_str!("test-fixtures/issue_124.txt");
2424        for line in contents.lines() {
2425            if line.starts_with("insert ") {
2426                map.insert(line[7..].parse::<u32>().unwrap(), 0);
2427            } else if line.starts_with("remove ") {
2428                map.remove(&line[7..].parse::<u32>().unwrap());
2429            }
2430        }
2431    }
2432
2433    proptest! {
2434        #[test]
2435        fn length(ref input in collection::btree_map(i16::ANY, i16::ANY, 0..1000)) {
2436            let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
2437            assert_eq!(input.len(), map.len());
2438        }
2439
2440        #[test]
2441        fn order(ref input in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2442            let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
2443            assert!(is_sorted(map.keys()));
2444        }
2445
2446        #[test]
2447        fn overwrite_values(ref vec in collection::vec((i16::ANY, i16::ANY), 1..1000), index_rand in usize::ANY, new_val in i16::ANY) {
2448            let index = vec[index_rand % vec.len()].0;
2449            let map1 = OrdMap::from_iter(vec.clone());
2450            let map2 = map1.update(index, new_val);
2451            for (k, v) in map2 {
2452                if k == index {
2453                    assert_eq!(v, new_val);
2454                } else {
2455                    match map1.get(&k) {
2456                        None => panic!("map1 didn't have key {:?}", k),
2457                        Some(other_v) => {
2458                            assert_eq!(v, *other_v);
2459                        }
2460                    }
2461                }
2462            }
2463        }
2464
2465        #[test]
2466        fn delete_values(ref vec in collection::vec((usize::ANY, usize::ANY), 1..1000), index_rand in usize::ANY) {
2467            let index = vec[index_rand % vec.len()].0;
2468            let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
2469            let map2 = map1.without(&index);
2470            assert_eq!(map1.len(), map2.len() + 1);
2471            for k in map2.keys() {
2472                assert_ne!(*k, index);
2473            }
2474        }
2475
2476        #[test]
2477        fn insert_and_delete_values(
2478            ref input in ord_map(0usize..64, 0usize..64, 1..1000),
2479            ref ops in collection::vec((bool::ANY, usize::ANY, usize::ANY), 1..1000)
2480        ) {
2481            let mut map = input.clone();
2482            let mut tree: collections::BTreeMap<usize, usize> = input.iter().map(|(k, v)| (*k, *v)).collect();
2483            for (ins, key, val) in ops {
2484                if *ins {
2485                    tree.insert(*key, *val);
2486                    map = map.update(*key, *val)
2487                } else {
2488                    tree.remove(key);
2489                    map = map.without(key)
2490                }
2491            }
2492            assert!(map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v))));
2493        }
2494
2495        #[test]
2496        fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) {
2497            assert!(m.len() < 100);
2498            assert!(m.len() >= 10);
2499        }
2500
2501        #[test]
2502        fn insert_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2503            let mut map: OrdMap<i16, i16> = OrdMap::new();
2504            for (k, v) in m.iter() {
2505                map = map.update(*k, *v)
2506            }
2507            assert_eq!(m.len(), map.len());
2508        }
2509
2510        #[test]
2511        fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2512            let map: OrdMap<i16, i16> =
2513                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2514            assert_eq!(m.len(), map.len());
2515        }
2516
2517        #[test]
2518        fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2519            let map: OrdMap<i16, i16> =
2520                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2521            assert_eq!(m.len(), map.iter().count());
2522        }
2523
2524        #[test]
2525        fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2526            let map1: OrdMap<i16, i16> =
2527                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2528            let map2: OrdMap<i16, i16> =
2529                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2530            assert_eq!(map1, map2);
2531        }
2532
2533        #[test]
2534        fn lookup(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2535            let map: OrdMap<i16, i16> =
2536                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2537            for (k, v) in m.iter() {
2538                assert_eq!(Some(*v), map.get(k).cloned());
2539            }
2540        }
2541
2542        #[test]
2543        fn remove(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2544            let mut map: OrdMap<i16, i16> =
2545                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2546            for k in m.keys() {
2547                let l = map.len();
2548                assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2549                map = map.without(k);
2550                assert_eq!(None, map.get(k));
2551                assert_eq!(l - 1, map.len());
2552            }
2553        }
2554
2555        #[test]
2556        fn insert_mut(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2557            let mut mut_map = OrdMap::new();
2558            let mut map = OrdMap::new();
2559            for (k, v) in m.iter() {
2560                map = map.update(*k, *v);
2561                mut_map.insert(*k, *v);
2562            }
2563            assert_eq!(map, mut_map);
2564        }
2565
2566        #[test]
2567        fn remove_mut(ref orig in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2568            let mut map = orig.clone();
2569            for key in orig.keys() {
2570                let len = map.len();
2571                assert_eq!(orig.get(key), map.get(key));
2572                assert_eq!(orig.get(key).cloned(), map.remove(key));
2573                assert_eq!(None, map.get(key));
2574                assert_eq!(len - 1, map.len());
2575            }
2576        }
2577
2578        #[test]
2579        fn remove_alien(ref orig in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2580            let mut map = OrdMap::<i16, i16>::from(orig.clone());
2581            for key in orig.keys() {
2582                let len = map.len();
2583                assert_eq!(orig.get(key), map.get(key));
2584                assert_eq!(orig.get(key).cloned(), map.remove(key));
2585                assert_eq!(None, map.get(key));
2586                assert_eq!(len - 1, map.len());
2587            }
2588        }
2589
2590        #[test]
2591        fn delete_and_reinsert(
2592            ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000),
2593            index_rand in usize::ANY
2594        ) {
2595            let index = *input.keys().nth(index_rand % input.len()).unwrap();
2596            let map1 = OrdMap::from_iter(input.clone());
2597            let (val, map2): (i16, _) = map1.extract(&index).unwrap();
2598            let map3 = map2.update(index, val);
2599            for key in map2.keys() {
2600                assert!(*key != index);
2601            }
2602            assert_eq!(map1.len(), map2.len() + 1);
2603            assert_eq!(map1, map3);
2604        }
2605
2606        #[test]
2607        fn exact_size_iterator(ref m in ord_map(i16::ANY, i16::ANY, 1..1000)) {
2608            let mut should_be = m.len();
2609            let mut it = m.iter();
2610            loop {
2611                assert_eq!(should_be, it.len());
2612                match it.next() {
2613                    None => break,
2614                    Some(_) => should_be -= 1,
2615                }
2616            }
2617            assert_eq!(0, it.len());
2618        }
2619
2620        #[test]
2621        fn diff_all_values(a in collection::vec((usize::ANY, usize::ANY), 1..1000), b in collection::vec((usize::ANY, usize::ANY), 1..1000)) {
2622            let a: OrdMap<usize, usize> = OrdMap::from(a);
2623            let b: OrdMap<usize, usize> = OrdMap::from(b);
2624
2625            let diff: Vec<_> = a.diff(&b).collect();
2626            let union = b.clone().union(a.clone());
2627            let expected: Vec<_> = union.iter().filter_map(|(k, v)| {
2628                if a.contains_key(k) {
2629                    if b.contains_key(k) {
2630                        let old = a.get(k).unwrap();
2631                        if old != v	{
2632                            Some(DiffItem::Update {
2633                                old: (k, old),
2634                                new: (k, v),
2635                            })
2636                        } else {
2637                            None
2638                        }
2639                    } else {
2640                        Some(DiffItem::Remove(k, v))
2641                    }
2642                } else {
2643                    Some(DiffItem::Add(k, v))
2644                }
2645            }).collect();
2646            assert_eq!(expected, diff);
2647        }
2648    }
2649}