[go: up one dir, main page]

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