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