Skip to main content

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