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: SharedPointerKind> Clone for ConsumingIter<K, V, P> {
2131    fn clone(&self) -> Self {
2132        Self {
2133            it: self.it.clone(),
2134        }
2135    }
2136}
2137
2138impl<K, V, P> Iterator for ConsumingIter<K, V, P>
2139where
2140    K: Clone,
2141    V: Clone,
2142    P: SharedPointerKind,
2143{
2144    type Item = (K, V);
2145    fn next(&mut self) -> Option<Self::Item> {
2146        self.it.next()
2147    }
2148    fn size_hint(&self) -> (usize, Option<usize>) {
2149        self.it.size_hint()
2150    }
2151}
2152
2153impl<K: Clone, V: Clone, P: SharedPointerKind> DoubleEndedIterator for ConsumingIter<K, V, P> {
2154    fn next_back(&mut self) -> Option<Self::Item> {
2155        self.it.next_back()
2156    }
2157}
2158
2159impl<K, V, P> ExactSizeIterator for ConsumingIter<K, V, P>
2160where
2161    K: Clone,
2162    V: Clone,
2163    P: SharedPointerKind,
2164{
2165}
2166impl<K, V, P> FusedIterator for ConsumingIter<K, V, P>
2167where
2168    K: Clone,
2169    V: Clone,
2170    P: SharedPointerKind,
2171{
2172}
2173
2174// Conversions
2175
2176impl<K, V, P: SharedPointerKind> AsRef<GenericOrdMap<K, V, P>> for GenericOrdMap<K, V, P> {
2177    fn as_ref(&self) -> &Self {
2178        self
2179    }
2180}
2181
2182impl<K, V, OK, OV, P1, P2> From<&GenericOrdMap<&K, &V, P2>> for GenericOrdMap<OK, OV, P1>
2183where
2184    K: Ord + ToOwned<Owned = OK> + ?Sized,
2185    V: ToOwned<Owned = OV> + ?Sized,
2186    OK: Ord + Clone,
2187    OV: Clone + Borrow<V>,
2188    P1: SharedPointerKind,
2189    P2: SharedPointerKind,
2190{
2191    fn from(m: &GenericOrdMap<&K, &V, P2>) -> Self {
2192        m.iter()
2193            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
2194            .collect()
2195    }
2196}
2197
2198impl<'a, K, V, RK, RV, OK, OV, P> From<&'a [(RK, RV)]> for GenericOrdMap<K, V, P>
2199where
2200    K: Ord + Clone + From<OK>,
2201    V: Clone + From<OV>,
2202    OV: Borrow<RV>,
2203    RK: ToOwned<Owned = OK>,
2204    RV: ToOwned<Owned = OV>,
2205    P: SharedPointerKind,
2206{
2207    fn from(m: &'a [(RK, RV)]) -> GenericOrdMap<K, V, P> {
2208        m.iter()
2209            .map(|(k, v)| (k.to_owned(), v.to_owned()))
2210            .collect()
2211    }
2212}
2213
2214impl<K, V, RK, RV, P> From<Vec<(RK, RV)>> for GenericOrdMap<K, V, P>
2215where
2216    K: Ord + Clone + From<RK>,
2217    V: Clone + From<RV>,
2218    P: SharedPointerKind,
2219{
2220    fn from(m: Vec<(RK, RV)>) -> GenericOrdMap<K, V, P> {
2221        m.into_iter().collect()
2222    }
2223}
2224
2225impl<'a, K, V, RK, RV, OK, OV, P> From<&'a Vec<(RK, RV)>> for GenericOrdMap<K, V, P>
2226where
2227    K: Ord + Clone + From<OK>,
2228    V: Clone + From<OV>,
2229    OV: Borrow<RV>,
2230    RK: ToOwned<Owned = OK>,
2231    RV: ToOwned<Owned = OV>,
2232    P: SharedPointerKind,
2233{
2234    fn from(m: &'a Vec<(RK, RV)>) -> GenericOrdMap<K, V, P> {
2235        m.iter()
2236            .map(|(k, v)| (k.to_owned(), v.to_owned()))
2237            .collect()
2238    }
2239}
2240
2241impl<K, V, RK, RV, P> From<collections::HashMap<RK, RV>> for GenericOrdMap<K, V, P>
2242where
2243    K: Ord + Clone + From<RK>,
2244    V: Clone + From<RV>,
2245    P: SharedPointerKind,
2246    RK: Eq + Hash,
2247{
2248    fn from(m: collections::HashMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2249        m.into_iter().collect()
2250    }
2251}
2252
2253impl<'a, K, V, OK, OV, RK, RV, P> From<&'a collections::HashMap<RK, RV>> for GenericOrdMap<K, V, P>
2254where
2255    K: Ord + Clone + From<OK>,
2256    V: Clone + From<OV>,
2257    OV: Borrow<RV>,
2258    RK: Hash + Eq + ToOwned<Owned = OK>,
2259    RV: ToOwned<Owned = OV>,
2260    P: SharedPointerKind,
2261{
2262    fn from(m: &'a collections::HashMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2263        m.iter()
2264            .map(|(k, v)| (k.to_owned(), v.to_owned()))
2265            .collect()
2266    }
2267}
2268
2269impl<K, V, RK, RV, P> From<collections::BTreeMap<RK, RV>> for GenericOrdMap<K, V, P>
2270where
2271    K: Ord + Clone + From<RK>,
2272    V: Clone + From<RV>,
2273    P: SharedPointerKind,
2274{
2275    fn from(m: collections::BTreeMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2276        m.into_iter().collect()
2277    }
2278}
2279
2280impl<'a, K, V, RK, RV, OK, OV, P> From<&'a collections::BTreeMap<RK, RV>> for GenericOrdMap<K, V, P>
2281where
2282    K: Ord + Clone + From<OK>,
2283    V: Clone + From<OV>,
2284    OV: Borrow<RV>,
2285    RK: Comparable<OK> + ToOwned<Owned = OK>,
2286    RV: ToOwned<Owned = OV>,
2287    P: SharedPointerKind,
2288{
2289    fn from(m: &'a collections::BTreeMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2290        m.iter()
2291            .map(|(k, v)| (k.to_owned(), v.to_owned()))
2292            .collect()
2293    }
2294}
2295
2296impl<K, V, S, P1, P2> From<GenericHashMap<K, V, S, P2>> for GenericOrdMap<K, V, P1>
2297where
2298    K: Ord + Hash + Eq + Clone,
2299    V: Clone,
2300    S: BuildHasher + Clone,
2301    P1: SharedPointerKind,
2302    P2: SharedPointerKind,
2303{
2304    fn from(m: GenericHashMap<K, V, S, P2>) -> Self {
2305        m.into_iter().collect()
2306    }
2307}
2308
2309impl<'a, K, V, S, P1, P2> From<&'a GenericHashMap<K, V, S, P2>> for GenericOrdMap<K, V, P1>
2310where
2311    K: Ord + Hash + Eq + Clone,
2312    V: Clone,
2313    S: BuildHasher + Clone,
2314    P1: SharedPointerKind,
2315    P2: SharedPointerKind,
2316{
2317    fn from(m: &'a GenericHashMap<K, V, S, P2>) -> Self {
2318        m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
2319    }
2320}
2321
2322// Proptest
2323#[cfg(any(test, feature = "proptest"))]
2324#[doc(hidden)]
2325pub mod proptest {
2326    #[deprecated(
2327        since = "14.3.0",
2328        note = "proptest strategies have moved to imbl::proptest"
2329    )]
2330    pub use crate::proptest::ord_map;
2331}
2332
2333// Tests
2334
2335#[cfg(test)]
2336mod test {
2337    use std::collections::BTreeMap;
2338
2339    use super::*;
2340    use crate::proptest::*;
2341    #[rustfmt::skip]
2342    use ::proptest::num::{i16, usize};
2343    #[rustfmt::skip]
2344    use ::proptest::{bool, collection, proptest};
2345    use static_assertions::{assert_impl_all, assert_not_impl_any};
2346
2347    assert_impl_all!(OrdMap<i32, i32>: Send, Sync);
2348    assert_not_impl_any!(OrdMap<i32, *const i32>: Send, Sync);
2349    assert_not_impl_any!(OrdMap<*const i32, i32>: Send, Sync);
2350    assert_covariant!(OrdMap<T, i32> in T);
2351    assert_covariant!(OrdMap<i32, T> in T);
2352
2353    #[test]
2354    fn iterates_in_order() {
2355        let map = ordmap! {
2356            2 => 22,
2357            1 => 11,
2358            3 => 33,
2359            8 => 88,
2360            9 => 99,
2361            4 => 44,
2362            5 => 55,
2363            7 => 77,
2364            6 => 66
2365        };
2366        let mut it = map.iter();
2367        assert_eq!(it.next(), Some((&1, &11)));
2368        assert_eq!(it.next(), Some((&2, &22)));
2369        assert_eq!(it.next(), Some((&3, &33)));
2370        assert_eq!(it.next(), Some((&4, &44)));
2371        assert_eq!(it.next(), Some((&5, &55)));
2372        assert_eq!(it.next(), Some((&6, &66)));
2373        assert_eq!(it.next(), Some((&7, &77)));
2374        assert_eq!(it.next(), Some((&8, &88)));
2375        assert_eq!(it.next(), Some((&9, &99)));
2376        assert_eq!(it.next(), None);
2377    }
2378
2379    #[test]
2380    fn into_iter() {
2381        let map = ordmap! {
2382            2 => 22,
2383            1 => 11,
2384            3 => 33,
2385            8 => 88,
2386            9 => 99,
2387            4 => 44,
2388            5 => 55,
2389            7 => 77,
2390            6 => 66
2391        };
2392        let mut vec = vec![];
2393        for (k, v) in map {
2394            assert_eq!(k * 11, v);
2395            vec.push(k)
2396        }
2397        assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
2398    }
2399
2400    struct PanicOnClone;
2401
2402    impl Clone for PanicOnClone {
2403        fn clone(&self) -> Self {
2404            panic!("PanicOnClone::clone called")
2405        }
2406    }
2407
2408    #[test]
2409    fn into_iter_no_clone() {
2410        let mut map = OrdMap::new();
2411        let mut map_rev = OrdMap::new();
2412        for i in 0..10_000 {
2413            map.insert(i, PanicOnClone);
2414            map_rev.insert(i, PanicOnClone);
2415        }
2416        let _ = map.into_iter().collect::<Vec<_>>();
2417        let _ = map_rev.into_iter().rev().collect::<Vec<_>>();
2418    }
2419
2420    #[test]
2421    fn iter_no_clone() {
2422        let mut map = OrdMap::new();
2423        for i in 0..10_000 {
2424            map.insert(i, PanicOnClone);
2425        }
2426        let _ = map.iter().collect::<Vec<_>>();
2427        let _ = map.iter().rev().collect::<Vec<_>>();
2428    }
2429
2430    #[test]
2431    fn deletes_correctly() {
2432        let map = ordmap! {
2433            2 => 22,
2434            1 => 11,
2435            3 => 33,
2436            8 => 88,
2437            9 => 99,
2438            4 => 44,
2439            5 => 55,
2440            7 => 77,
2441            6 => 66
2442        };
2443        assert_eq!(map.extract(&11), None);
2444        let (popped, less) = map.extract(&5).unwrap();
2445        assert_eq!(popped, 55);
2446        let mut it = less.iter();
2447        assert_eq!(it.next(), Some((&1, &11)));
2448        assert_eq!(it.next(), Some((&2, &22)));
2449        assert_eq!(it.next(), Some((&3, &33)));
2450        assert_eq!(it.next(), Some((&4, &44)));
2451        assert_eq!(it.next(), Some((&6, &66)));
2452        assert_eq!(it.next(), Some((&7, &77)));
2453        assert_eq!(it.next(), Some((&8, &88)));
2454        assert_eq!(it.next(), Some((&9, &99)));
2455        assert_eq!(it.next(), None);
2456    }
2457
2458    #[test]
2459    fn debug_output() {
2460        assert_eq!(
2461            format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }),
2462            "{1: 2, 3: 4, 5: 6}"
2463        );
2464    }
2465
2466    #[test]
2467    fn equality2() {
2468        let v1 = "1".to_string();
2469        let v2 = "1".to_string();
2470        assert_eq!(v1, v2);
2471        let p1 = Vec::<String>::new();
2472        let p2 = Vec::<String>::new();
2473        assert_eq!(p1, p2);
2474        let c1: OrdMap<_, _> = OrdMap::unit(v1, p1);
2475        let c2: OrdMap<_, _> = OrdMap::unit(v2, p2);
2476        assert_eq!(c1, c2);
2477    }
2478
2479    #[test]
2480    fn insert_remove_single_mut() {
2481        let mut m = OrdMap::new();
2482        m.insert(0, 0);
2483        assert_eq!(OrdMap::<_, _>::unit(0, 0), m);
2484        m.remove(&0);
2485        assert_eq!(OrdMap::new(), m);
2486    }
2487
2488    #[test]
2489    fn double_ended_iterator_1() {
2490        let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2491        let mut it = m.iter();
2492        assert_eq!(Some((&1, &1)), it.next());
2493        assert_eq!(Some((&4, &4)), it.next_back());
2494        assert_eq!(Some((&2, &2)), it.next());
2495        assert_eq!(Some((&3, &3)), it.next_back());
2496        assert_eq!(None, it.next());
2497    }
2498
2499    #[test]
2500    fn double_ended_iterator_2() {
2501        let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2502        let mut it = m.iter();
2503        assert_eq!(Some((&1, &1)), it.next());
2504        assert_eq!(Some((&4, &4)), it.next_back());
2505        assert_eq!(Some((&2, &2)), it.next());
2506        assert_eq!(Some((&3, &3)), it.next_back());
2507        assert_eq!(None, it.next_back());
2508    }
2509
2510    #[test]
2511    fn safe_mutation() {
2512        let v1 = OrdMap::<_, _>::from_iter((0..131_072).map(|i| (i, i)));
2513        let mut v2 = v1.clone();
2514        v2.insert(131_000, 23);
2515        assert_eq!(Some(&23), v2.get(&131_000));
2516        assert_eq!(Some(&131_000), v1.get(&131_000));
2517    }
2518
2519    #[test]
2520    fn index_operator() {
2521        let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6};
2522        assert_eq!(4, map[&3]);
2523        map[&3] = 8;
2524        assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map);
2525    }
2526
2527    #[test]
2528    fn entry_api() {
2529        let mut map = ordmap! {"bar" => 5};
2530        map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2531        assert_eq!(1, map[&"foo"]);
2532        map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2533        assert_eq!(6, map[&"foo"]);
2534        map.entry("bar").and_modify(|v| *v += 5).or_insert(1);
2535        assert_eq!(10, map[&"bar"]);
2536        assert_eq!(
2537            10,
2538            match map.entry("bar") {
2539                Entry::Occupied(entry) => entry.remove(),
2540                _ => panic!(),
2541            }
2542        );
2543        assert!(!map.contains_key(&"bar"));
2544    }
2545
2546    #[test]
2547    fn match_string_keys_with_string_slices() {
2548        let mut map: OrdMap<String, i32> =
2549            From::from(&ordmap! { "foo" => &1, "bar" => &2, "baz" => &3 });
2550        assert_eq!(Some(&1), map.get("foo"));
2551        map = map.without("foo");
2552        assert_eq!(Some(3), map.remove("baz"));
2553        map["bar"] = 8;
2554        assert_eq!(8, map["bar"]);
2555    }
2556
2557    #[test]
2558    fn ranged_iter() {
2559        let map: OrdMap<i32, i32> = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6, 7=>8];
2560        let range: Vec<(i32, i32)> = map.range::<_, i32>(..).map(|(k, v)| (*k, *v)).collect();
2561        assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (7, 8)], range);
2562        let range: Vec<(i32, i32)> = map
2563            .range::<_, i32>(..)
2564            .rev()
2565            .map(|(k, v)| (*k, *v))
2566            .collect();
2567        assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
2568        let range: Vec<(i32, i32)> = map.range(2..5).map(|(k, v)| (*k, *v)).collect();
2569        assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
2570        let range: Vec<(i32, i32)> = map.range(2..5).rev().map(|(k, v)| (*k, *v)).collect();
2571        assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
2572        let range: Vec<(i32, i32)> = map.range(3..).map(|(k, v)| (*k, *v)).collect();
2573        assert_eq!(vec![(3, 4), (4, 5), (5, 6), (7, 8)], range);
2574        let range: Vec<(i32, i32)> = map.range(3..).rev().map(|(k, v)| (*k, *v)).collect();
2575        assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4)], range);
2576        let range: Vec<(i32, i32)> = map.range(..4).map(|(k, v)| (*k, *v)).collect();
2577        assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2578        let range: Vec<(i32, i32)> = map.range(..4).rev().map(|(k, v)| (*k, *v)).collect();
2579        assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2580        let range: Vec<(i32, i32)> = map.range(..=3).map(|(k, v)| (*k, *v)).collect();
2581        assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2582        let range: Vec<(i32, i32)> = map.range(..=3).rev().map(|(k, v)| (*k, *v)).collect();
2583        assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2584        let range: Vec<(i32, i32)> = map.range(..6).map(|(k, v)| (*k, *v)).collect();
2585        assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2586        let range: Vec<(i32, i32)> = map.range(..=6).map(|(k, v)| (*k, *v)).collect();
2587        assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2588
2589        assert_eq!(map.range(2..5).size_hint(), (0, Some(6)));
2590        let mut iter = map.range(2..5);
2591        iter.next();
2592        assert_eq!(iter.size_hint(), (0, Some(5)));
2593    }
2594
2595    #[test]
2596    fn range_iter_big() {
2597        use crate::nodes::btree::NODE_SIZE;
2598        use std::ops::Bound::Included;
2599        const N: usize = NODE_SIZE * NODE_SIZE * NODE_SIZE / 2; // enough for a sizeable 3 level tree
2600
2601        let data = (1usize..N).filter(|i| i % 2 == 0).map(|i| (i, ()));
2602        let bmap = data
2603            .clone()
2604            .collect::<std::collections::BTreeMap<usize, ()>>();
2605        let omap = data.collect::<OrdMap<usize, ()>>();
2606        assert_eq!(bmap.len(), omap.len());
2607
2608        for i in (0..NODE_SIZE * 5).chain(N - NODE_SIZE * 5..=N + 1) {
2609            assert_eq!(omap.range(i..).count(), bmap.range(i..).count());
2610            assert_eq!(omap.range(..i).count(), bmap.range(..i).count());
2611            assert_eq!(
2612                omap.range(i..(i + 7)).count(),
2613                bmap.range(i..(i + 7)).count()
2614            );
2615            assert_eq!(
2616                omap.range(i..=(i + 7)).count(),
2617                bmap.range(i..=(i + 7)).count()
2618            );
2619            assert_eq!(
2620                omap.range((Included(i), Included(i + 7))).count(),
2621                bmap.range((Included(i), Included(i + 7))).count(),
2622            );
2623            assert_eq!(omap.range(..=i).next_back(), omap.get_prev(&i));
2624            assert_eq!(omap.range(i..).next(), omap.get_next(&i));
2625        }
2626    }
2627
2628    #[test]
2629    fn issue_124() {
2630        let mut map = OrdMap::new();
2631        let contents = include_str!("test-fixtures/issue_124.txt");
2632        for line in contents.lines() {
2633            if let Some(tail) = line.strip_prefix("insert ") {
2634                map.insert(tail.parse::<u32>().unwrap(), 0);
2635            } else if let Some(tail) = line.strip_prefix("remove ") {
2636                map.remove(&tail.parse::<u32>().unwrap());
2637            }
2638        }
2639    }
2640
2641    /// Diffing a map against a clone-derived sibling must report every
2642    /// difference (issue #161). An entry sitting right after a run of
2643    /// structurally shared nodes must still be compared, whichever kind of
2644    /// difference it holds:
2645    ///
2646    /// - an updated value there was silently dropped from the diff (and,
2647    ///   since `PartialEq` is diff-backed, the unequal maps compared equal);
2648    /// - a removed entry there was reported as a `Remove` of the *wrong*
2649    ///   key (its successor);
2650    /// - a removal of a leaf's first key followed by an insert between the
2651    ///   now-stale parent separator and the new first key lost both the
2652    ///   `Remove` and the `Add` outright.
2653    #[test]
2654    fn diff_clone_derived_shared_structure() {
2655        for n in [17usize, 40, 100] {
2656            let a: OrdMap<usize, usize> = (0..n).map(|i| (i * 10, 0usize)).collect();
2657            // Update every key, one at a time.
2658            for k in (0..n).map(|k| k * 10) {
2659                let b = a.update(k, 1);
2660                let diff: Vec<_> = a.diff(&b).collect();
2661                assert_eq!(expected_diff(&a, &b), diff, "update {k} of {n}");
2662                assert_ne!(a, b, "eq is diff-backed and must see update {k} of {n}");
2663            }
2664            // Remove every key, one at a time.
2665            for k in (0..n).map(|k| k * 10) {
2666                let b = a.without(&k);
2667                let diff: Vec<_> = a.diff(&b).collect();
2668                assert_eq!(expected_diff(&a, &b), diff, "remove {k} of {n}");
2669            }
2670            // Remove every key and insert a fresh key just above it: when
2671            // k headed a leaf, the parent separator still reads k, so the
2672            // inserted key becomes the new head of an unshared leaf.
2673            for k in (0..n).map(|k| k * 10) {
2674                let mut b = a.clone();
2675                b.remove(&k);
2676                b.insert(k + 5, 7);
2677                let diff: Vec<_> = a.diff(&b).collect();
2678                assert_eq!(
2679                    expected_diff(&a, &b),
2680                    diff,
2681                    "remove {k} insert {} of {n}",
2682                    k + 5
2683                );
2684            }
2685        }
2686    }
2687
2688    fn expected_diff<'a, K, V, P>(
2689        a: &'a GenericOrdMap<K, V, P>,
2690        b: &'a GenericOrdMap<K, V, P>,
2691    ) -> Vec<DiffItem<'a, 'a, K, V>>
2692    where
2693        K: Ord + Clone,
2694        V: PartialEq + Clone,
2695        P: SharedPointerKind,
2696    {
2697        let mut diff = Vec::new();
2698        for (k, v) in a.iter() {
2699            if let Some(v2) = b.get(k) {
2700                if v != v2 {
2701                    diff.push(DiffItem::Update {
2702                        old: (k, v),
2703                        new: (k, v2),
2704                    });
2705                }
2706            } else {
2707                diff.push(DiffItem::Remove(k, v));
2708            }
2709        }
2710        for (k, v) in b.iter() {
2711            if a.get(k).is_none() {
2712                diff.push(DiffItem::Add(k, v));
2713            }
2714        }
2715        fn diff_item_key<'b, K, V>(di: &DiffItem<'b, 'b, K, V>) -> &'b K {
2716            match di {
2717                DiffItem::Add(k, _) => k,
2718                DiffItem::Remove(k, _) => k,
2719                DiffItem::Update { old: (k, _), .. } => k,
2720            }
2721        }
2722        diff.sort_unstable_by(|a, b| diff_item_key(a).cmp(diff_item_key(b)));
2723        diff
2724    }
2725
2726    proptest! {
2727        #[test]
2728        fn length(ref input in collection::btree_map(i16::ANY, i16::ANY, 0..1000)) {
2729            let map: OrdMap<i16, i16> = OrdMap::from(input.clone());
2730            assert_eq!(input.len(), map.len());
2731        }
2732
2733        #[test]
2734        fn order(ref input in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2735            let map: OrdMap<i16, i16> = OrdMap::from(input.clone());
2736            let keys = map.keys().cloned().collect::<Vec<_>>();
2737            let mut expected_keys = input.keys().cloned().collect::<Vec<_>>();
2738            expected_keys.sort();
2739            assert_eq!(keys, expected_keys);
2740        }
2741
2742        #[test]
2743        fn overwrite_values(ref vec in collection::vec((i16::ANY, i16::ANY), 1..1000), index_rand in usize::ANY, new_val in i16::ANY) {
2744            let index = vec[index_rand % vec.len()].0;
2745            let map1 = OrdMap::<_, _>::from_iter(vec.clone());
2746            let map2 = map1.update(index, new_val);
2747            for (k, v) in map2 {
2748                if k == index {
2749                    assert_eq!(v, new_val);
2750                } else {
2751                    match map1.get(&k) {
2752                        None => panic!("map1 didn't have key {:?}", k),
2753                        Some(other_v) => {
2754                            assert_eq!(v, *other_v);
2755                        }
2756                    }
2757                }
2758            }
2759        }
2760
2761        #[test]
2762        fn delete_values(ref vec in collection::vec((usize::ANY, usize::ANY), 1..1000), index_rand in usize::ANY) {
2763            let index = vec[index_rand % vec.len()].0;
2764            let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
2765            let map2 = map1.without(&index);
2766            assert_eq!(map1.len(), map2.len() + 1);
2767            for k in map2.keys() {
2768                assert_ne!(*k, index);
2769            }
2770        }
2771
2772        #[test]
2773        fn insert_and_delete_values(
2774            ref input in ord_map(0usize..64, 0usize..64, 1..1000),
2775            ref ops in collection::vec((bool::ANY, usize::ANY, usize::ANY), 1..1000)
2776        ) {
2777            let mut map = input.clone();
2778            let mut tree: collections::BTreeMap<usize, usize> = input.iter().map(|(k, v)| (*k, *v)).collect();
2779            for (ins, key, val) in ops {
2780                if *ins {
2781                    tree.insert(*key, *val);
2782                    map = map.update(*key, *val)
2783                } else {
2784                    tree.remove(key);
2785                    map = map.without(key)
2786                }
2787            }
2788            assert!(map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v))));
2789        }
2790
2791        #[test]
2792        fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) {
2793            assert!(m.len() < 100);
2794            assert!(m.len() >= 10);
2795        }
2796
2797        #[test]
2798        fn insert_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2799            let mut map = OrdMap::new();
2800            for (k, v) in m.iter() {
2801                map = map.update(*k, *v)
2802            }
2803            assert_eq!(m.len(), map.len());
2804        }
2805
2806        #[test]
2807        fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2808            let map: OrdMap<i16, i16> =
2809                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2810            assert_eq!(m.len(), map.len());
2811        }
2812
2813        #[test]
2814        fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2815            let map: OrdMap<i16, i16> =
2816                OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2817            let expected = m.iter().map(|(k, v)| (*k, *v)).collect::<BTreeMap<_, _>>();
2818            assert!(map.iter().eq(expected.iter()));
2819        }
2820
2821        #[test]
2822        fn iterate_over_rev(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2823            let map: OrdMap<i16, i16> =
2824                OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2825            let expected = m.iter().map(|(k, v)| (*k, *v)).collect::<BTreeMap<_, _>>();
2826            assert!(map.iter().rev().eq(expected.iter().rev()));
2827        }
2828
2829        #[test]
2830        fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2831            let map1: OrdMap<i16, i16> =
2832                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2833            let map2: OrdMap<i16, i16> =
2834                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2835            assert_eq!(map1, map2);
2836        }
2837
2838        #[test]
2839        fn lookup(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2840            let map: OrdMap<i16, i16> =
2841                FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2842            for (k, v) in m.iter() {
2843                assert_eq!(Some(*v), map.get(k).cloned());
2844            }
2845        }
2846
2847        #[test]
2848        fn remove(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2849            let mut map: OrdMap<i16, i16> =
2850                OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2851            for k in m.keys() {
2852                let l = map.len();
2853                assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2854                map = map.without(k);
2855                assert_eq!(None, map.get(k));
2856                assert_eq!(l - 1, map.len());
2857            }
2858        }
2859
2860        #[test]
2861        fn insert_mut(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2862            let mut mut_map = OrdMap::new();
2863            let mut map = OrdMap::new();
2864            for (k, v) in m.iter() {
2865                map = map.update(*k, *v);
2866                mut_map.insert(*k, *v);
2867            }
2868            assert_eq!(map, mut_map);
2869        }
2870
2871        #[test]
2872        fn remove_mut(ref orig in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2873            let mut map = orig.clone();
2874            for key in orig.keys() {
2875                let len = map.len();
2876                assert_eq!(orig.get(key), map.get(key));
2877                assert_eq!(orig.get(key).cloned(), map.remove(key));
2878                assert_eq!(None, map.get(key));
2879                assert_eq!(len - 1, map.len());
2880            }
2881        }
2882
2883        #[test]
2884        fn remove_alien(ref orig in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2885            let mut map: OrdMap<i16, i16> = OrdMap::from(orig.clone());
2886            for key in orig.keys() {
2887                let len = map.len();
2888                assert_eq!(orig.get(key), map.get(key));
2889                assert_eq!(orig.get(key).cloned(), map.remove(key));
2890                assert_eq!(None, map.get(key));
2891                assert_eq!(len - 1, map.len());
2892            }
2893        }
2894
2895        #[test]
2896        fn delete_and_reinsert(
2897            ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000),
2898            index_rand in usize::ANY
2899        ) {
2900            let index = *input.keys().nth(index_rand % input.len()).unwrap();
2901            let map1 = OrdMap::from_iter(input.clone());
2902            let (val, map2): (i16, _) = map1.extract(&index).unwrap();
2903            let map3 = map2.update(index, val);
2904            for key in map2.keys() {
2905                assert!(*key != index);
2906            }
2907            assert_eq!(map1.len(), map2.len() + 1);
2908            assert_eq!(map1, map3);
2909        }
2910
2911        #[test]
2912        fn exact_size_iterator(ref m in ord_map(i16::ANY, i16::ANY, 1..1000)) {
2913            let mut should_be = m.len();
2914            let mut it = m.iter();
2915            loop {
2916                assert_eq!(should_be, it.len());
2917                match it.next() {
2918                    None => break,
2919                    Some(_) => should_be -= 1,
2920                }
2921            }
2922            assert_eq!(0, it.len());
2923        }
2924
2925        #[test]
2926        fn diff_all_values(a in collection::vec((usize::ANY, usize::ANY), 1..1000), b in collection::vec((usize::ANY, usize::ANY), 1..1000)) {
2927            let a: OrdMap<usize, usize> = OrdMap::from(a);
2928            let b: OrdMap<usize, usize> = OrdMap::from(b);
2929
2930            let diff: Vec<_> = a.diff(&b).collect();
2931            let expected = expected_diff(&a, &b);
2932            assert_eq!(expected, diff);
2933        }
2934
2935        #[test]
2936        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)) {
2937            let a: OrdMap<usize, usize> = OrdMap::from(a);
2938            let mut b = a.clone();
2939            for (k, v) in ops {
2940                b.insert(k, v);
2941            }
2942
2943            let diff: Vec<_> = a.diff(&b).collect();
2944            let expected = expected_diff(&a, &b);
2945            assert_eq!(expected, diff);
2946        }
2947
2948        /// Like `diff_all_values_shared`, but with a key domain narrow
2949        /// enough that the ops routinely update, remove, and re-insert keys
2950        /// at shared-structure boundaries (issue #161); with `usize::ANY`
2951        /// keys, ops are pure inserts of fresh keys and never exercise
2952        /// those shapes.
2953        #[test]
2954        fn diff_clone_derived_narrow_keys(
2955            a in collection::vec((0usize..64, usize::ANY), 1..100),
2956            ops in collection::vec((0usize..64, ::proptest::option::of(usize::ANY)), 1..100),
2957        ) {
2958            let a: OrdMap<usize, usize> = OrdMap::from(a);
2959            let mut b = a.clone();
2960            for (k, op) in ops {
2961                match op {
2962                    Some(v) => {
2963                        b.insert(k, v);
2964                    }
2965                    None => {
2966                        b.remove(&k);
2967                    }
2968                }
2969            }
2970
2971            let diff: Vec<_> = a.diff(&b).collect();
2972            let expected = expected_diff(&a, &b);
2973            assert_eq!(expected, diff);
2974        }
2975
2976        #[test]
2977        fn union(ref map1 in ord_map(i16::ANY, i16::ANY, 0..100),
2978                 ref map2 in ord_map(i16::ANY, i16::ANY, 0..100)) {
2979            let union_map = map1.clone().union(map2.clone());
2980
2981            for k in map1.keys() {
2982                assert!(union_map.contains_key(k));
2983            }
2984
2985            for k in map2.keys() {
2986                assert!(union_map.contains_key(k));
2987            }
2988
2989            for (k, v) in union_map.iter() {
2990                assert_eq!(v, map1.get(k).or_else(|| map2.get(k)).unwrap());
2991            }
2992        }
2993    }
2994}