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