hashslab/
map.rs

1//! A hash map with indexes
2use core::{
3    fmt,
4    hash::{BuildHasher, Hash},
5    mem,
6    ops::{Index, IndexMut},
7};
8
9#[cfg(feature = "std")]
10use std::hash::RandomState;
11
12use hashbrown::{hash_table, Equivalent, HashTable};
13use slab::Slab;
14
15use crate::{TryReserveError, ValueData};
16
17use super::KeyData;
18
19mod keys;
20pub use keys::{FullKeys, Indices, IntoKeys, Keys};
21
22mod values;
23pub use values::{IntoValues, Values, ValuesMut};
24
25mod iter;
26pub use iter::{IntoFullIter, IntoIter, Iter, IterFull, IterFullMut, IterMut};
27
28mod drain;
29pub use drain::{Drain, DrainFull};
30
31mod entry;
32pub use entry::{Entry, OccupiedEntry, VacantEntry};
33
34#[cfg(test)]
35mod tests;
36
37/// A hash map with indexes
38///
39/// The interface is closely compatible with the [`IndexMap`].
40///
41/// # Indices
42///
43/// [`HashSlabMap`] returns the index ([`usize`]) when storing the value. It
44/// is important to note that index may be reused. In other words, once a value
45/// associated with a given index is removed from a hashslab, that index may be
46/// returned from future calls to insert. For example, the method `.get_full` looks
47/// up the index for a key, and the method `.get_index` looks up the key-value pair
48/// by index.
49///
50/// # Examples
51///
52/// Standard [`HashMap`] usage:
53/// ```
54/// # use hashslab::HashSlabMap;
55/// // Type inference lets us omit an explicit type signature (which
56/// // would be `HashSlabMap<String, String>` in this example).
57/// let mut book_reviews = HashSlabMap::new();
58///
59/// // Review some books.
60/// book_reviews.insert(
61///     "Adventures of Huckleberry Finn".to_string(),
62///     "My favorite book.".to_string(),
63/// );
64/// book_reviews.insert(
65///     "Grimms' Fairy Tales".to_string(),
66///     "Masterpiece.".to_string(),
67/// );
68/// book_reviews.insert(
69///     "Pride and Prejudice".to_string(),
70///     "Very enjoyable.".to_string(),
71/// );
72/// book_reviews.insert(
73///     "The Adventures of Sherlock Holmes".to_string(),
74///     "Eye lyked it alot.".to_string(),
75/// );
76///
77/// // Check for a specific one.
78/// // When collections store owned values (String), they can still be
79/// // queried using references (&str).
80/// if !book_reviews.contains_key("Les Misérables") {
81///     println!("We've got {} reviews, but Les Misérables ain't one.",
82///              book_reviews.len());
83/// }
84///
85/// // oops, this review has a lot of spelling mistakes, let's delete it.
86/// book_reviews.remove("The Adventures of Sherlock Holmes");
87///
88/// // Look up the values associated with some keys.
89/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
90/// for &book in &to_find {
91///     match book_reviews.get(book) {
92///         Some(review) => println!("{}: {}", book, review),
93///         None => println!("{} is unreviewed.", book)
94///     }
95/// }
96///
97/// // Look up the value for a key (will panic if the key is not found).
98/// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
99///
100/// // Iterate over everything.
101/// for (book, review) in &book_reviews {
102///     println!("{}: \"{}\"", book, review);
103/// }
104/// ```
105///
106/// With indices:
107/// ```
108/// # use hashslab::HashSlabMap;
109/// // count the frequency of each letter in a sentence.
110/// let mut letters = HashSlabMap::new();
111/// for ch in "a short treatise on fungi".chars() {
112///     *letters.entry(ch).or_insert(0) += 1;
113/// }
114///
115/// assert_eq!(letters[&'s'], 2);
116/// assert_eq!(letters.get_index_of(&'a'), Some(0));
117/// assert_eq!(letters.get_index(1), Some((&' ', &4)));
118/// assert_eq!(letters.get(&'y'), None);
119/// ```
120///
121/// [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
122/// [`IndexMap`]: https://docs.rs/indexmap/latest/indexmap/map/struct.IndexMap.html
123/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
124/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
125/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
126/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
127/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
128/// [`default`]: #method.default
129/// [`with_hasher`]: #method.with_hasher
130/// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
131#[cfg(feature = "std")]
132pub struct HashSlabMap<K, V, S = RandomState> {
133    pub(crate) table: HashTable<KeyData<K>>,
134    pub(crate) slab: Slab<ValueData<V>>,
135    pub(crate) builder: S,
136}
137
138#[cfg(not(feature = "std"))]
139pub struct HashSlabMap<K, V, S> {
140    table: HashTable<KeyData<K>>,
141    slab: Slab<ValueData<V>>,
142    builder: S,
143}
144
145#[cfg(feature = "std")]
146#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
147impl<K, V> HashSlabMap<K, V> {
148    /// Creates an empty `HashSlabMap`.
149    ///
150    /// # Examples
151    ///
152    /// ```
153    /// # use hashslab::HashSlabMap;
154    /// let mut map: HashSlabMap<&str, i32> = HashSlabMap::new();
155    /// assert_eq!(map.len(), 0);
156    /// assert_eq!(map.capacity(), 0);
157    /// ```
158    #[inline]
159    pub fn new() -> Self {
160        Self::with_capacity(0)
161    }
162
163    /// Creates an empty `HashSlabMap` with the specified capacity.
164    ///
165    /// The hash map will be able to hold at least `capacity` elements without
166    /// reallocating. If `capacity` is 0, the hash map will not allocate.
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// # use hashslab::HashSlabMap;
172    /// let mut map: HashSlabMap<&str, i32> = HashSlabMap::with_capacity(10);
173    /// assert_eq!(map.len(), 0);
174    /// assert!(map.capacity() >= 10);
175    /// ```
176    #[inline]
177    pub fn with_capacity(n: usize) -> Self {
178        Self::with_capacity_and_hasher(n, Default::default())
179    }
180}
181
182impl<K, V, S> HashSlabMap<K, V, S> {
183    /// Creates an empty `HashSlabMap` with the specified capacity, using `hash_builder`
184    /// to hash the keys.
185    ///
186    /// The hash map will be able to hold at least `capacity` elements without
187    /// reallocating. If `capacity` is 0, the hash map will not allocate.
188    ///
189    /// # Examples
190    ///
191    /// ```
192    /// # use hashslab::HashSlabMap;
193    /// use std::hash::RandomState;
194    ///
195    /// let s = RandomState::new();
196    /// let mut map = HashSlabMap::with_capacity_and_hasher(10, s);
197    /// assert_eq!(map.len(), 0);
198    /// assert!(map.capacity() >= 10);
199    ///
200    /// map.insert(1, 2);
201    /// ```
202    #[inline]
203    pub fn with_capacity_and_hasher(n: usize, builder: S) -> Self {
204        Self {
205            table: HashTable::with_capacity(n),
206            slab: Slab::with_capacity(n),
207            builder,
208        }
209    }
210
211    /// Create a new map with `hash_builder`.
212    ///
213    /// # Examples
214    ///
215    /// ```
216    /// # use hashslab::HashSlabMap;
217    /// let s = std::hash::RandomState::new();
218    /// let mut map = HashSlabMap::with_hasher(s);
219    /// assert_eq!(map.len(), 0);
220    /// assert_eq!(map.capacity(), 0);
221    ///
222    /// map.insert(1, 2);
223    /// ```
224    pub const fn with_hasher(builder: S) -> Self {
225        Self {
226            table: HashTable::new(),
227            slab: Slab::new(),
228            builder,
229        }
230    }
231
232    /// Return the number of values the hashslab can store without reallocating.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// # use hashslab::HashSlabMap;
238    /// let map = HashSlabMap::<(), ()>::with_capacity(100);
239    /// assert!(map.capacity() >= 100);
240    /// ```
241    pub fn capacity(&self) -> usize {
242        self.table.capacity().min(self.slab.capacity())
243    }
244
245    /// Returns a reference to the map's [`BuildHasher`].
246    ///
247    /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// # use hashslab::HashSlabMap;
253    /// use std::hash::{RandomState, BuildHasherDefault};
254    /// use fnv::{FnvBuildHasher, FnvHasher};
255    ///
256    /// let map = HashSlabMap::<(), ()>::new();
257    /// let hasher: &RandomState = map.hasher();
258    ///
259    /// let s = FnvBuildHasher::default();
260    /// let mut map = HashSlabMap::with_hasher(s);
261    /// map.insert(1, 2);
262    /// let hasher: &BuildHasherDefault<FnvHasher> = map.hasher();
263    /// ```
264    pub fn hasher(&self) -> &S {
265        &self.builder
266    }
267
268    /// Return the number of key-value pairs in the map.
269    #[inline]
270    pub fn len(&self) -> usize {
271        debug_assert_eq!(
272            self.table.len(),
273            self.slab.len(),
274            "Number of entries in HashTable and Slab should be equal"
275        );
276        self.table.len()
277    }
278
279    /// Returns true if the map contains no elements.
280    #[inline]
281    pub fn is_empty(&self) -> bool {
282        self.len() == 0
283    }
284
285    /// An iterator over the index-key-value triples in arbitrary order.  
286    /// The iterator element type is `(usize, &'a K, &'a V)`.
287    ///
288    /// # Examples
289    ///
290    /// ```
291    /// # use hashslab::HashSlabMap;
292    ///
293    /// let mut map = HashSlabMap::new();
294    /// map.insert("a", 1);
295    /// map.insert("b", 2);
296    /// map.insert("c", 3);
297    /// assert_eq!(map.len(), 3);
298    /// let mut vec: Vec<(usize, &str, i32)> = Vec::new();
299    ///
300    /// for (idx, key, val) in map.iter_full() {
301    ///     println!("idx: {idx}, key: {key} val: {val}");
302    ///     vec.push((idx, *key, *val));
303    /// }
304    ///
305    /// // The `IterFull` iterator produces items in arbitrary order, so the
306    /// // items must be sorted to test them against a sorted array.
307    /// vec.sort_unstable();
308    /// assert_eq!(vec, [(0, "a", 1), (1, "b", 2), (2, "c", 3)]);
309    ///
310    /// assert_eq!(map.len(), 3);
311    /// ```
312    pub fn iter_full(&self) -> IterFull<'_, K, V> {
313        IterFull::new(self.table.iter(), &self.slab)
314    }
315
316    /// An iterator visiting all key-value pairs in arbitrary order.  
317    /// The iterator element type is `(&'a K, &'a V)`.
318    ///
319    /// # Examples
320    ///
321    /// ```
322    /// # use hashslab::HashSlabMap;
323    ///
324    /// let mut map = HashSlabMap::new();
325    /// map.insert("a", 1);
326    /// map.insert("b", 2);
327    /// map.insert("c", 3);
328    /// assert_eq!(map.len(), 3);
329    /// let mut vec: Vec<(&str, i32)> = Vec::new();
330    ///
331    /// for (key, val) in map.iter() {
332    ///     println!("key: {} val: {}", key, val);
333    ///     vec.push((*key, *val));
334    /// }
335    ///
336    /// // The `Iter` iterator produces items in arbitrary order, so the
337    /// // items must be sorted to test them against a sorted array.
338    /// vec.sort_unstable();
339    /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
340    ///
341    /// assert_eq!(map.len(), 3);
342    /// ```
343    pub fn iter(&self) -> Iter<'_, K, V> {
344        Iter::new(self.iter_full())
345    }
346
347    /// An iterator visiting all index-key-value triple in arbitrary order,
348    /// with mutable references to the values.  
349    /// The iterator element type is `(usize, &'a K, &'a mut V)`.
350    ///
351    /// # Examples
352    ///
353    /// ```
354    /// # use hashslab::HashSlabMap;
355    ///
356    /// let mut map = HashSlabMap::new();
357    /// map.insert("a", 1);
358    /// map.insert("b", 2);
359    /// map.insert("c", 3);
360    ///
361    /// assert_eq!(map.len(), 3);
362    /// 
363    /// let mut vec: Vec<(usize, &str, i32)> = Vec::new();
364    ///
365    /// for (idx, key, val) in map.iter_full_mut() {
366    ///     assert_eq!(idx + 1, *val as usize);
367    ///     // Update value
368    ///     *val *= 2;
369    ///     println!("idx: {idx}, key: {key} val: {val}");
370    ///     vec.push((idx, *key, *val));
371    /// }
372    ///
373    /// // The `IterFullMut` iterator produces items in arbitrary order, so the
374    /// // items must be sorted to test them against a sorted array.
375    /// vec.sort_unstable();
376    /// assert_eq!(vec, [(0, "a", 2), (1, "b", 4), (2, "c", 6)]);
377    ///
378    /// assert_eq!(map.len(), 3);
379    /// ```
380    pub fn iter_full_mut(&mut self) -> IterFullMut<'_, K, V> {
381        IterFullMut::new(self.table.iter(), &mut self.slab)
382    }
383
384    /// An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values.  
385    /// The iterator element type is `(&'a K, &'a mut V)`.
386    ///
387    /// # Examples
388    ///
389    /// ```
390    /// # use hashslab::HashSlabMap;
391    ///
392    /// let mut map = HashSlabMap::new();
393    /// map.insert("a", 1);
394    /// map.insert("b", 2);
395    /// map.insert("c", 3);
396    ///
397    /// // Update all values
398    /// for (_, val) in map.iter_mut() {
399    ///     *val *= 2;
400    /// }
401    ///
402    /// assert_eq!(map.len(), 3);
403    /// let mut vec: Vec<(&str, i32)> = Vec::new();
404    ///
405    /// for (key, val) in &map {
406    ///     println!("key: {} val: {}", key, val);
407    ///     vec.push((*key, *val));
408    /// }
409    ///
410    /// // The `Iter` iterator produces items in arbitrary order, so the
411    /// // items must be sorted to test them against a sorted array.
412    /// vec.sort_unstable();
413    /// assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);
414    ///
415    /// assert_eq!(map.len(), 3);
416    /// ```
417    pub fn iter_mut(&mut self) -> IterMut<'_, K, V>
418    where
419        K: Clone,
420    {
421        IterMut::new(self.iter_full_mut())
422    }
423
424    /// Creates a consuming iterator, that is, one that moves each index-key-value
425    /// pair out of the map in arbitrary order. The map cannot be used after
426    /// calling this.  
427    /// The iterator element type is `(usize, K, V)`.
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// # use hashslab::HashSlabMap;
433    ///
434    /// let map: HashSlabMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
435    ///
436    /// // Not possible with .iter_full()
437    /// let mut vec: Vec<(usize, &str, i32)> = map.into_full_iter().collect();
438    /// // The `IntoFullIter` iterator produces items in arbitrary order, so
439    /// // the items must be sorted to test them against a sorted array.
440    /// vec.sort_unstable();
441    /// assert_eq!(vec, [(0, "a", 1), (1, "b", 2), (2, "c", 3)]);
442    /// ```
443    pub fn into_full_iter(self) -> IntoFullIter<K, V> {
444        IntoFullIter::new(self.table.into_iter(), self.slab)
445    }
446
447    /// An iterator visiting index-keys pairs in arbitrary order.  
448    /// The iterator element type is `&'a K`.
449    ///
450    /// # Examples
451    ///
452    /// ```
453    /// # use hashslab::HashSlabMap;
454    ///
455    /// let mut map = HashSlabMap::new();
456    /// map.insert("a", 1);
457    /// map.insert("b", 2);
458    /// map.insert("c", 3);
459    /// assert_eq!(map.len(), 3);
460    /// let mut vec: Vec<(usize, &str)> = Vec::new();
461    ///
462    /// for (idx, key) in map.full_keys() {
463    ///     println!("idx: {idx}, key: {key}");
464    ///     vec.push((idx, *key));
465    /// }
466    ///
467    /// // The `Keys` iterator produces keys in arbitrary order, so the
468    /// // keys must be sorted to test them against a sorted array.
469    /// vec.sort_unstable();
470    /// assert_eq!(vec, [(0, "a"), (1, "b"), (2, "c")]);
471    ///
472    /// assert_eq!(map.len(), 3);
473    /// ```
474    pub fn full_keys(&self) -> FullKeys<'_, K> {
475        FullKeys::new(self.table.iter())
476    }
477
478    /// An iterator visiting all keys in arbitrary order.  
479    /// The iterator element type is `&'a K`.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// # use hashslab::HashSlabMap;
485    ///
486    /// let mut map = HashSlabMap::new();
487    /// map.insert("a", 1);
488    /// map.insert("b", 2);
489    /// map.insert("c", 3);
490    /// assert_eq!(map.len(), 3);
491    /// let mut vec: Vec<&str> = Vec::new();
492    ///
493    /// for key in map.keys() {
494    ///     println!("{}", key);
495    ///     vec.push(*key);
496    /// }
497    ///
498    /// // The `Keys` iterator produces keys in arbitrary order, so the
499    /// // keys must be sorted to test them against a sorted array.
500    /// vec.sort_unstable();
501    /// assert_eq!(vec, ["a", "b", "c"]);
502    ///
503    /// assert_eq!(map.len(), 3);
504    /// ```
505    pub fn keys(&self) -> Keys<'_, K> {
506        Keys::new(self.full_keys())
507    }
508
509    /// Creates a consuming iterator visiting all the keys in arbitrary order.
510    /// The map cannot be used after calling this.
511    /// The iterator element type is `K`.
512    ///
513    /// # Examples
514    ///
515    /// ```
516    /// # use hashslab::HashSlabMap;
517    ///
518    /// let mut map = HashSlabMap::new();
519    /// map.insert("a", 1);
520    /// map.insert("b", 2);
521    /// map.insert("c", 3);
522    ///
523    /// let mut vec: Vec<&str> = map.into_keys().collect();
524    ///
525    /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
526    /// // keys must be sorted to test them against a sorted array.
527    /// vec.sort_unstable();
528    /// assert_eq!(vec, ["a", "b", "c"]);
529    /// ```
530    pub fn into_keys(self) -> IntoKeys<K> {
531        IntoKeys::new(self.table.into_iter())
532    }
533
534    /// An iterator over indices in arbitrary order. The iterator element type is `usize`.
535    pub fn indices(&self) -> Indices<'_, K> {
536        Indices::new(self.table.iter())
537    }
538
539    /// An iterator visiting all values in arbitrary order. The iterator element type is `&'a V`.
540    ///
541    /// # Examples
542    ///
543    /// ```
544    /// # use hashslab::HashSlabMap;
545    /// let mut map = HashSlabMap::new();
546    /// map.insert("a", 1);
547    /// map.insert("b", 2);
548    /// map.insert("c", 3);
549    /// assert_eq!(map.len(), 3);
550    /// let mut vec: Vec<i32> = Vec::new();
551    ///
552    /// for val in map.values() {
553    ///     println!("{}", val);
554    ///     vec.push(*val);
555    /// }
556    ///
557    /// // The `Values` iterator produces values in arbitrary order, so the
558    /// // values must be sorted to test them against a sorted array.
559    /// vec.sort_unstable();
560    /// assert_eq!(vec, [1, 2, 3]);
561    ///
562    /// assert_eq!(map.len(), 3);
563    /// ```
564    pub fn values(&self) -> Values<'_, K, V> {
565        Values::new(self.iter_full())
566    }
567
568    /// An iterator visiting all values mutably in arbitrary order. The iterator element type is `&'a mut V`.
569    ///
570    /// # Examples
571    ///
572    /// ```
573    /// # use hashslab::HashSlabMap;
574    ///
575    /// let mut map = HashSlabMap::new();
576    ///
577    /// map.insert("a", 1);
578    /// map.insert("b", 2);
579    /// map.insert("c", 3);
580    ///
581    /// for val in map.values_mut() {
582    ///     *val = *val + 10;
583    /// }
584    ///
585    /// assert_eq!(map.len(), 3);
586    /// let mut vec: Vec<i32> = Vec::new();
587    ///
588    /// for val in map.values() {
589    ///     println!("{}", val);
590    ///     vec.push(*val);
591    /// }
592    ///
593    /// // The `Values` iterator produces values in arbitrary order, so the
594    /// // values must be sorted to test them against a sorted array.
595    /// vec.sort_unstable();
596    /// assert_eq!(vec, [11, 12, 13]);
597    ///
598    /// assert_eq!(map.len(), 3);
599    /// ```
600    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
601        ValuesMut::new(self.iter_full_mut())
602    }
603
604    /// Creates a consuming iterator visiting all the values in arbitrary order.
605    /// The map cannot be used after calling this.
606    /// The iterator element type is `V`.
607    ///
608    /// # Examples
609    ///
610    /// ```
611    /// use hashslab::HashSlabMap;
612    ///
613    /// let mut map = HashSlabMap::new();
614    /// map.insert("a", 1);
615    /// map.insert("b", 2);
616    /// map.insert("c", 3);
617    ///
618    /// let mut vec: Vec<i32> = map.into_values().collect();
619    ///
620    /// // The `IntoValues` iterator produces values in arbitrary order, so
621    /// // the values must be sorted to test them against a sorted array.
622    /// vec.sort_unstable();
623    /// assert_eq!(vec, [1, 2, 3]);
624    /// ```
625    pub fn into_values(self) -> IntoValues<K, V> {
626        IntoValues::new(self.into_iter())
627    }
628
629    /// Remove all entries in the map, while preserving its capacity.
630    pub fn clear(&mut self) {
631        self.table.clear();
632        self.slab.clear();
633    }
634
635    /// Clears the map, returning all index-key-value triples as an iterator. Keeps the allocated memory for reuse.
636    pub fn drain_full(&mut self) -> DrainFull<'_, K, V> {
637        DrainFull::new(self.table.drain(), &mut self.slab)
638    }
639
640    /// Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
641    pub fn drain(&mut self) -> Drain<'_, K, V> {
642        Drain::new(self.drain_full())
643    }
644
645    /// Retains only the elements specified by the predicate. Keeps the
646    /// allocated memory for reuse.
647    ///
648    /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
649    /// The elements are visited in unsorted (and unspecified) order.
650    ///
651    /// # Examples
652    ///
653    /// ```
654    /// # use hashslab::HashSlabMap;
655    /// let mut map: HashSlabMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
656    /// assert_eq!(map.len(), 8);
657    ///
658    /// map.retain(|&k, _| dbg!(k) % 2 == 0);
659    ///
660    /// // We can see, that the number of elements inside map is changed.
661    /// assert_eq!(map.len(), 4);
662    ///
663    /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
664    /// vec.sort_unstable();
665    /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
666    /// ```
667    pub fn retain<F>(&mut self, mut f: F)
668    where
669        F: FnMut(&K, &mut V) -> bool,
670    {
671        self.table.retain(|KeyData { key, index }| {
672            let value = &mut self.slab[*index].value;
673            if f(key, value) {
674                true
675            } else {
676                self.slab.remove(*index);
677                false
678            }
679        })
680    }
681
682    /// Get a key-value pair by index
683    ///
684    /// # Examples
685    ///
686    /// ```
687    /// # use hashslab::HashSlabMap;
688    /// let mut map = HashSlabMap::new();
689    /// map.insert(1, "a");
690    /// assert_eq!(map.get_index(0), Some((&1, &"a")));
691    /// assert_eq!(map.get_index(1), None);
692    /// ```
693    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
694        let ValueData { value, hash } = self.slab.get(index)?;
695        self.table
696            .find(*hash, |e| e.index == index)
697            .map(|KeyData { key, .. }| (key, value))
698    }
699
700    /// Get a value by index.
701    pub fn get_index_value(&self, index: usize) -> Option<&V> {
702        self.slab.get(index).map(|ValueData { value, .. }| value)
703    }
704
705    /// Returns the index of the next vacant entry.
706    ///
707    /// This function returns the index of the vacant entry which  will be used
708    ///
709    /// # Examples
710    ///
711    /// ```
712    /// # use hashslab::*;
713    /// let mut map = HashSlabMap::new();
714    /// assert_eq!(map.vacant_index(), 0);
715    ///
716    /// map.insert(0, ());
717    /// assert_eq!(map.vacant_index(), 1);
718    ///
719    /// map.insert(1, ());
720    /// map.remove(&0);
721    /// assert_eq!(map.vacant_index(), 0);
722    /// ```
723    pub fn vacant_index(&self) -> usize {
724        self.slab.vacant_key()
725    }
726}
727
728impl<K, V, S> HashSlabMap<K, V, S>
729where
730    K: Hash + Eq,
731    S: BuildHasher,
732{
733    /// Reserve capacity for `additional` more key-value pairs.
734    pub fn reserve(&mut self, additional: usize) {
735        self.table.reserve(additional, make_hasher(&self.builder));
736        self.slab.reserve(additional);
737    }
738
739    /// Try to reserve capacity for `additional` more key-value pairs.
740    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
741        self.table
742            .try_reserve(additional, make_hasher(&self.builder))?;
743        let capacity = self.slab.capacity();
744        if (capacity + additional) <= isize::MAX as usize {
745            self.slab.reserve(additional);
746            Ok(())
747        } else {
748            Err(TryReserveError::Slab {
749                capacity,
750                additional,
751            })
752        }
753    }
754
755    /// Shrink the capacity of the map as much as possible.
756    pub fn shrink_to_fit(&mut self) {
757        self.table.shrink_to_fit(make_hasher(&self.builder));
758        self.slab.shrink_to_fit();
759    }
760
761    /// Insert a key-value pair in the map.
762    ///
763    /// If an equivalent key already exists in the map: the key remains and
764    /// retains in its place in the order, its corresponding value is updated
765    /// with `value`, and the older value is returned inside `Some(_)`.
766    ///
767    /// If no equivalent key existed in the map: the new key-value pair is
768    /// inserted, last in order, and `None` is returned.
769    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
770        self.insert_full(key, value).1
771    }
772
773    /// Insert a key-value pair in the map, and get their index.
774    ///
775    /// If an equivalent key already exists in the map: the key remains and
776    /// retains in its place in the order, its corresponding value is updated
777    /// with `value`, and the older value is returned inside `(index, Some(_))`.
778    ///
779    /// If no equivalent key existed in the map: the new key-value pair is
780    /// inserted, last in order, and `(index, None)` is returned.
781    pub fn insert_full(&mut self, key: K, value: V) -> (usize, Option<V>) {
782        let hash = self.builder.hash_one(&key);
783        match self
784            .table
785            .entry(hash, |e| e.key == key, make_hasher(&self.builder))
786        {
787            hash_table::Entry::Occupied(entry) => {
788                let i = entry.get().index;
789                (i, Some(mem::replace(&mut self.slab[i].value, value)))
790            }
791            hash_table::Entry::Vacant(entry) => {
792                let index = self.slab.insert(ValueData::new(value, hash));
793                entry.insert(KeyData::new(key, index));
794                debug_assert_eq!(self.table.len(), self.slab.len());
795                (index, None)
796            }
797        }
798    }
799
800    /// Return item index, key and value
801    pub fn get_full<Q>(&self, key: &Q) -> Option<(usize, &K, &V)>
802    where
803        Q: Hash + Equivalent<K> + ?Sized,
804    {
805        self.get_key_index(key)
806            .map(|(key, index)| (index, key, &self.slab[index].value))
807    }
808
809    /// Return references to the key-value pair stored for `key`, if it is present, else `None`.
810    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
811    where
812        Q: Hash + Equivalent<K> + ?Sized,
813    {
814        self.get_full(key).map(|(_, key, data)| (key, data))
815    }
816
817    /// Returns a reference to the value corresponding to the key.
818    ///
819    /// The key may be any borrowed form of the map's key type, but
820    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
821    /// the key type.
822    ///
823    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
824    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
825    ///
826    /// # Examples
827    ///
828    /// ```
829    /// use hashslab::HashSlabMap;
830    ///
831    /// let mut map = HashSlabMap::new();
832    /// map.insert(1, "a");
833    /// assert_eq!(map.get(&1), Some(&"a"));
834    /// assert_eq!(map.get(&2), None);
835    /// ```
836    pub fn get<Q>(&self, key: &Q) -> Option<&V>
837    where
838        Q: Hash + Equivalent<K> + ?Sized,
839    {
840        self.get_full(key).map(|(_, _, data)| data)
841    }
842
843    /// Return item index, if it exists in the map
844    pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
845    where
846        Q: Hash + Equivalent<K> + ?Sized,
847    {
848        self.get_key_index(key).map(|(_, index)| index)
849    }
850
851    /// Returns the index-key-value triple corresponding to the supplied key, with a mutable reference to value.
852    pub fn get_full_mut<Q>(&mut self, key: &Q) -> Option<(usize, &K, &mut V)>
853    where
854        Q: ?Sized + Hash + Equivalent<K>,
855    {
856        if self.table.is_empty() {
857            None
858        } else {
859            let hash = self.builder.hash_one(key);
860            self.table
861                .find(hash, |e| key.equivalent(&e.key))
862                .map(|KeyData { index, key, .. }| (*index, key, &mut self.slab[*index].value))
863        }
864    }
865
866    /// Returns a mutable reference to the value corresponding to the key.
867    ///
868    /// The key may be any borrowed form of the map's key type, but
869    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
870    /// the key type.
871    ///
872    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
873    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
874    ///
875    /// # Examples
876    ///
877    /// ```
878    /// use hashslab::HashSlabMap;
879    ///
880    /// let mut map = HashSlabMap::new();
881    /// map.insert(1, "a");
882    /// if let Some(x) = map.get_mut(&1) {
883    ///     *x = "b";
884    /// }
885    /// assert_eq!(map[&1], "b");
886    ///
887    /// assert_eq!(map.get_mut(&2), None);
888    /// ```
889    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
890    where
891        Q: ?Sized + Hash + Equivalent<K>,
892    {
893        self.get_full_mut(key).map(|(_, _, value)| value)
894    }
895
896    /// Returns key reference and mutable reference to the value corresponding to the index.
897    ///
898    /// ```
899    /// use hashslab::HashSlabMap;
900    ///
901    /// let mut map = HashSlabMap::new();
902    /// map.insert(1, "a");
903    /// if let Some((k, v)) = map.get_index_mut(0) {
904    ///     *v = "b";
905    /// }
906    /// assert_eq!(map[&1], "b");
907    ///
908    /// assert_eq!(map.get_index_mut(1), None);
909    /// ```
910    pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
911        let ValueData { value, hash } = self.slab.get_mut(index)?;
912        self.table
913            .find(*hash, |e| e.index == index)
914            .map(|KeyData { key, .. }| (key, value))
915    }
916
917    /// Remove the key-value pair equivalent to `key` and return its value.
918    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
919    where
920        Q: ?Sized + Hash + Equivalent<K>,
921    {
922        self.remove_entry(key).map(|(_, v)| v)
923    }
924
925    /// Remove and return the key-value pair equivalent to `key`.
926    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
927    where
928        Q: ?Sized + Hash + Equivalent<K>,
929    {
930        self.remove_full(key).map(|(_, k, v)| (k, v))
931    }
932
933    /// Remove the key-value pair equivalent to key and return it and the index it had.
934    pub fn remove_full<Q>(&mut self, key: &Q) -> Option<(usize, K, V)>
935    where
936        Q: ?Sized + Hash + Equivalent<K>,
937    {
938        let hash = self.builder.hash_one(key);
939        self.table
940            .find_entry(hash, |e| key.equivalent(&e.key))
941            .ok()
942            .map(|entry| {
943                let (KeyData { key, index, .. }, _) = entry.remove();
944                let ValueData { value, .. } = self.slab.remove(index);
945                (index, key, value)
946            })
947    }
948
949    /// Remove the key-value pair by index
950    pub fn remove_index(&mut self, index: usize) -> Option<(K, V)> {
951        let ValueData { value, hash } = self.slab.try_remove(index)?;
952        self.table
953            .find_entry(hash, |e| e.index == index)
954            .ok()
955            .map(|entry| {
956                let (KeyData { key, .. }, _) = entry.remove();
957                (key, value)
958            })
959    }
960
961    /// Gets the given key's corresponding entry in the map for in-place manipulation.
962    ///
963    /// # Examples
964    ///
965    /// ```
966    /// # use hashslab::HashSlabMap;
967    /// let mut letters = HashSlabMap::new();
968    ///
969    /// for ch in "a short treatise on fungi".chars() {
970    ///     let counter = letters.entry(ch).or_insert(0);
971    ///     *counter += 1;
972    /// }
973    ///
974    /// assert_eq!(letters[&'s'], 2);
975    /// assert_eq!(letters[&'t'], 3);
976    /// assert_eq!(letters[&'u'], 1);
977    /// assert_eq!(letters.get(&'y'), None);
978    /// ```
979    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
980        // let key_entry = EntryBuilder::new(key, self.map.hasher()).key_entry(self.slab.vacant_key());
981        // match self.table.entry(key) {
982        //     hash_table::Entry::Occupied(occupied_entry) => {
983        //         Entry::Occupied(OccupiedEntry::new(occupied_entry, &mut self.slab))
984        //     }
985        //     hash_table::Entry::Vacant(vacant_entry) => {
986        //         Entry::Vacant(VacantEntry::new(vacant_entry, &mut self.slab))
987        //     }
988        // }
989        let hash = self.builder.hash_one(&key);
990        match self
991            .table
992            .entry(hash, |e| e.key == key, make_hasher(&self.builder))
993        {
994            hash_table::Entry::Occupied(occupied_entry) => {
995                Entry::Occupied(OccupiedEntry::new(occupied_entry, &mut self.slab))
996            }
997            hash_table::Entry::Vacant(vacant_entry) => {
998                Entry::Vacant(VacantEntry::new(vacant_entry, &mut self.slab, key, hash))
999            }
1000        }
1001    }
1002
1003    /// Returns `true` if the map contains a value for the specified key.
1004    ///
1005    /// # Examples
1006    ///
1007    /// ```
1008    /// # use hashslab::HashSlabMap;
1009    /// let mut map = HashSlabMap::new();
1010    /// map.insert(1, "a");
1011    /// assert_eq!(map.contains_key(&1), true);
1012    /// assert_eq!(map.contains_key(&2), false);
1013    /// ```
1014    pub fn contains_key<Q>(&self, key: &Q) -> bool
1015    where
1016        Q: Hash + Equivalent<K> + ?Sized,
1017    {
1018        let hash = self.builder.hash_one(key);
1019        self.table.find(hash, |e| key.equivalent(&e.key)).is_some()
1020    }
1021
1022    /// Return `true` if a value is associated with the given key.
1023    ///
1024    /// # Examples
1025    ///
1026    /// ```
1027    /// # use hashslab::HashSlabMap;
1028    /// let mut map = HashSlabMap::new();
1029    ///
1030    /// let idx = map.insert_full("hello", ()).0;
1031    /// assert!(map.contains_index(idx));
1032    ///
1033    /// map.remove_index(idx);
1034    ///
1035    /// assert!(!map.contains_index(idx));
1036    /// ```
1037    pub fn contains_index(&self, index: usize) -> bool {
1038        self.slab.contains(index)
1039    }
1040
1041    /// Moves all key-value pairs from `other` into `self`, leaving `other` empty.
1042    ///
1043    /// This is equivalent to calling [`insert`][Self::insert] for each
1044    /// key-value pair from `other` in order, which means that for keys that
1045    /// already exist in `self`, their value is updated in the current position.
1046    ///
1047    /// # Examples
1048    ///
1049    /// ```
1050    /// # use hashslab::HashSlabMap;
1051    /// // Note: Key (3) is present in both maps.
1052    /// let mut a = HashSlabMap::from([(3, "c"), (2, "b"), (1, "a")]);
1053    /// let mut b = HashSlabMap::from([(3, "d"), (4, "e"), (5, "f")]);
1054    /// let old_capacity = b.capacity();
1055    ///
1056    /// a.append(&mut b);
1057    ///
1058    /// assert_eq!(a.len(), 5);
1059    /// assert_eq!(b.len(), 0);
1060    /// assert_eq!(b.capacity(), old_capacity);
1061    ///
1062    /// let mut keys: Vec<_> = a.keys().cloned().collect();
1063    /// keys.sort();
1064    /// assert_eq!(keys, vec![1, 2, 3, 4, 5]);
1065    ///
1066    /// // "c" was overwritten.
1067    /// assert_eq!(a[&3], "d");
1068    /// ```
1069    pub fn append<S2>(&mut self, other: &mut HashSlabMap<K, V, S2>) {
1070        self.extend(other.drain());
1071    }
1072}
1073
1074// Private methods
1075impl<K, V, S> HashSlabMap<K, V, S> {
1076    fn get_key_index<Q>(&self, key: &Q) -> Option<(&K, usize)>
1077    where
1078        Q: Hash + Equivalent<K> + ?Sized,
1079        S: BuildHasher,
1080    {
1081        if self.table.is_empty() {
1082            None
1083        } else {
1084            let hash = self.builder.hash_one(key);
1085            self.table
1086                .find(hash, |e| key.equivalent(&e.key))
1087                .map(|KeyData { index, key, .. }| (key, *index))
1088        }
1089    }
1090}
1091
1092// https://github.com/rust-lang/rust/issues/26925
1093impl<K: Clone, V: Clone, S: Clone> Clone for HashSlabMap<K, V, S> {
1094    fn clone(&self) -> Self {
1095        Self {
1096            table: self.table.clone(),
1097            slab: self.slab.clone(),
1098            builder: self.builder.clone(),
1099        }
1100    }
1101}
1102
1103impl<K, V> fmt::Debug for HashSlabMap<K, V>
1104where
1105    K: fmt::Debug,
1106    V: fmt::Debug,
1107{
1108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109        f.debug_map()
1110            .entries(self.iter_full().map(|(i, k, v)| (i, (k, v))))
1111            .finish()
1112    }
1113}
1114
1115impl<K, V, S> Default for HashSlabMap<K, V, S>
1116where
1117    S: Default,
1118{
1119    fn default() -> Self {
1120        Self::with_capacity_and_hasher(0, S::default())
1121    }
1122}
1123
1124/// Access [`HashSlabMap`] values corresponding to a key.
1125///
1126/// # Examples
1127///
1128/// ```
1129/// use hashslab::HashSlabMap;
1130///
1131/// let mut map = HashSlabMap::new();
1132/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1133///     map.insert(word.to_lowercase(), word.to_uppercase());
1134/// }
1135/// assert_eq!(map["lorem"], "LOREM");
1136/// assert_eq!(map["ipsum"], "IPSUM");
1137/// ```
1138///
1139/// ```should_panic
1140/// use hashslab::HashSlabMap;
1141///
1142/// let mut map = HashSlabMap::new();
1143/// map.insert("foo", 1);
1144/// println!("{:?}", map["bar"]); // panics!
1145/// ```
1146impl<K, V, Q: ?Sized, S> Index<&Q> for HashSlabMap<K, V, S>
1147where
1148    K: Hash + Eq,
1149    Q: Hash + Equivalent<K>,
1150    S: BuildHasher,
1151{
1152    type Output = V;
1153
1154    /// Returns a reference to the value corresponding to the supplied `key`.
1155    ///
1156    /// ***Panics*** if `key` is not present in the map.
1157    fn index(&self, key: &Q) -> &V {
1158        self.get(key).expect("HashSlabMap: key not found")
1159    }
1160}
1161
1162/// Access [`HashSlabMap`] values at indexed positions.
1163///
1164/// # Examples
1165///
1166/// ```
1167/// use hashslab::HashSlabMap;
1168///
1169/// let mut map = HashSlabMap::new();
1170/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1171///     map.insert(word.to_lowercase(), word.to_uppercase());
1172/// }
1173/// assert_eq!(map[0], "LOREM");
1174/// assert_eq!(map[1], "IPSUM");
1175/// ```
1176///
1177/// ```should_panic
1178/// use hashslab::HashSlabMap;
1179///
1180/// let mut map = HashSlabMap::new();
1181/// map.insert("foo", 1);
1182/// println!("{:?}", map[10]); // panics!
1183/// ```
1184impl<K, V, S> Index<usize> for HashSlabMap<K, V, S>
1185where
1186    K: Hash + Eq,
1187    S: BuildHasher,
1188{
1189    type Output = V;
1190
1191    /// Returns a reference to the value at the supplied `index`.
1192    ///
1193    /// ***Panics*** if `index` is out of bounds.
1194    fn index(&self, index: usize) -> &V {
1195        self.get_index(index)
1196            .expect("HashSlabMap: index out of bounds")
1197            .1
1198    }
1199}
1200
1201/// Access [`HashSlabMap`] values corresponding to a key.
1202///
1203/// Mutable indexing allows changing / updating values of key-value
1204/// pairs that are already present.
1205///
1206/// You can **not** insert new pairs with index syntax, use `.insert()`.
1207///
1208/// # Examples
1209///
1210/// ```
1211/// use hashslab::HashSlabMap;
1212///
1213/// let mut map = HashSlabMap::new();
1214/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1215///     map.insert(word.to_lowercase(), word.to_string());
1216/// }
1217/// let lorem = &mut map["lorem"];
1218/// assert_eq!(lorem, "Lorem");
1219/// lorem.retain(char::is_lowercase);
1220/// assert_eq!(map["lorem"], "orem");
1221/// ```
1222///
1223/// ```should_panic
1224/// use hashslab::HashSlabMap;
1225///
1226/// let mut map = HashSlabMap::new();
1227/// map.insert("foo", 1);
1228/// map["bar"] = 1; // panics!
1229/// ```
1230impl<K, V, Q: ?Sized, S> IndexMut<&Q> for HashSlabMap<K, V, S>
1231where
1232    K: Hash + Eq,
1233    Q: Hash + Equivalent<K>,
1234    S: BuildHasher,
1235{
1236    /// Returns a mutable reference to the value corresponding to the supplied `key`.
1237    ///
1238    /// ***Panics*** if `key` is not present in the map.
1239    fn index_mut(&mut self, key: &Q) -> &mut V {
1240        self.get_mut(key).expect("HashSlabMap: key not found")
1241    }
1242}
1243
1244/// Access [`HashSlabMap`] values at indexed positions.
1245///
1246/// Mutable indexing allows changing / updating indexed values
1247/// that are already present.
1248///
1249/// You can **not** insert new values with index syntax -- use [`.insert()`][HashSlabMap::insert].
1250///
1251/// # Examples
1252///
1253/// ```
1254/// use hashslab::HashSlabMap;
1255///
1256/// let mut map = HashSlabMap::new();
1257/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1258///     map.insert(word.to_lowercase(), word.to_string());
1259/// }
1260/// let lorem = &mut map[0];
1261/// assert_eq!(lorem, "Lorem");
1262/// lorem.retain(char::is_lowercase);
1263/// assert_eq!(map["lorem"], "orem");
1264/// ```
1265///
1266/// ```should_panic
1267/// use hashslab::HashSlabMap;
1268///
1269/// let mut map = HashSlabMap::new();
1270/// map.insert("foo", 1);
1271/// map[10] = 1; // panics!
1272/// ```
1273impl<K, V, S> IndexMut<usize> for HashSlabMap<K, V, S>
1274where
1275    K: Hash + Eq,
1276    S: BuildHasher,
1277{
1278    /// Returns a mutable reference to the value at the supplied `index`.
1279    ///
1280    /// ***Panics*** if `index` is out of bounds.
1281    fn index_mut(&mut self, index: usize) -> &mut V {
1282        self.get_index_mut(index)
1283            .expect("HashSlabMap: index out of bounds")
1284            .1
1285    }
1286}
1287
1288impl<K, V, S> Extend<(K, V)> for HashSlabMap<K, V, S>
1289where
1290    K: Hash + Eq,
1291    S: BuildHasher,
1292{
1293    /// Extend the map with all key-value pairs in the iterable.
1294    ///
1295    /// This is equivalent to calling [`insert`][HashSlabMap::insert] for each of
1296    /// them in order, which means that for keys that already existed
1297    /// in the map, their value is updated but it keeps the existing order.
1298    ///
1299    /// New keys are inserted in the order they appear in the sequence. If
1300    /// equivalents of a key occur more than once, the last corresponding value
1301    /// prevails.
1302    ///
1303    /// # Examples
1304    ///
1305    /// ```
1306    /// use hashslab::HashSlabMap;
1307    ///
1308    /// let mut map = HashSlabMap::new();
1309    /// map.insert(1, 100);
1310    ///
1311    /// let some_iter = [(1, 1), (2, 2)].into_iter();
1312    /// map.extend(some_iter);
1313    /// // Replace values with existing keys with new values returned from the iterator.
1314    /// // So that the map.get(&1) doesn't return Some(&100).
1315    /// assert_eq!(map.get(&1), Some(&1));
1316    ///
1317    /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
1318    /// map.extend(some_vec);
1319    ///
1320    /// let some_arr = [(5, 5), (6, 6)];
1321    /// map.extend(some_arr);
1322    /// let old_map_len = map.len();
1323    ///
1324    /// // You can also extend from another HashSlabMap
1325    /// let mut new_map = HashSlabMap::new();
1326    /// new_map.extend(map);
1327    /// assert_eq!(new_map.len(), old_map_len);
1328    ///
1329    /// let mut vec: Vec<_> = new_map.into_iter().collect();
1330    /// // The `IntoIter` iterator produces items in arbitrary order, so the
1331    /// // items must be sorted to test them against a sorted array.
1332    /// vec.sort_unstable();
1333    /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
1334    /// ```
1335    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iterable: I) {
1336        // (Note: this is a copy of `std`/`hashbrown`'s reservation logic.)
1337        // Keys may be already present or show multiple times in the iterator.
1338        // Reserve the entire hint lower bound if the map is empty.
1339        // Otherwise reserve half the hint (rounded up), so the map
1340        // will only resize twice in the worst case.
1341        let iter = iterable.into_iter();
1342        let reserve = if self.is_empty() {
1343            iter.size_hint().0
1344        } else {
1345            (iter.size_hint().0 + 1) / 2
1346        };
1347        self.reserve(reserve);
1348        iter.for_each(move |(k, v)| {
1349            self.insert(k, v);
1350        });
1351    }
1352}
1353
1354impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashSlabMap<K, V, S>
1355where
1356    K: Hash + Eq + Copy,
1357    V: Copy,
1358    S: BuildHasher,
1359{
1360    /// Extend the map with all key-value pairs in the iterable.
1361    ///
1362    /// See the first extend method for more details.
1363    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iterable: I) {
1364        self.extend(iterable.into_iter().map(|(&key, &value)| (key, value)));
1365    }
1366}
1367
1368/// Inserts all new key-values from the iterator and replaces values with existing
1369/// keys with new values returned from the iterator.
1370impl<'a, K, V, S> Extend<&'a (K, V)> for HashSlabMap<K, V, S>
1371where
1372    K: Eq + Hash + Copy,
1373    V: Copy,
1374    S: BuildHasher,
1375{
1376    /// Inserts all new key-values from the iterator to existing `HashSlabMap<K, V, S, A>`.
1377    /// Replace values with existing keys with new values returned from the iterator.
1378    /// The keys and values must implement [`Copy`] trait.
1379    ///
1380    /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
1381    ///
1382    /// # Examples
1383    ///
1384    /// ```
1385    /// use hashslab::HashSlabMap;
1386    /// let mut map = HashSlabMap::new();
1387    /// map.insert(1, 100);
1388    ///
1389    /// let arr = [(1, 1), (2, 2)];
1390    /// let some_iter = arr.iter();
1391    /// map.extend(some_iter);
1392    /// // Replace values with existing keys with new values returned from the iterator.
1393    /// // So that the map.get(&1) doesn't return Some(&100).
1394    /// assert_eq!(map.get(&1), Some(&1));
1395    ///
1396    /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
1397    /// map.extend(&some_vec);
1398    ///
1399    /// let some_arr = [(5, 5), (6, 6)];
1400    /// map.extend(&some_arr);
1401    ///
1402    /// let mut vec: Vec<_> = map.into_iter().collect();
1403    /// // The `IntoIter` iterator produces items in arbitrary order, so the
1404    /// // items must be sorted to test them against a sorted array.
1405    /// vec.sort_unstable();
1406    /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
1407    /// ```
1408    fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) {
1409        self.extend(iter.into_iter().map(|&(key, value)| (key, value)));
1410    }
1411}
1412
1413impl<K, V, S> FromIterator<(K, V)> for HashSlabMap<K, V, S>
1414where
1415    K: Hash + Eq,
1416    S: BuildHasher + Default,
1417{
1418    /// Create an `HashSlabMap` from the sequence of key-value pairs in the
1419    /// iterable.
1420    ///
1421    /// `from_iter` uses the same logic as `extend`. See
1422    /// [`extend`][HashSlabMap::extend] for more details.
1423    fn from_iter<I: IntoIterator<Item = (K, V)>>(iterable: I) -> Self {
1424        let iter = iterable.into_iter();
1425        let (low, _) = iter.size_hint();
1426        let mut map = Self::with_capacity_and_hasher(low, S::default());
1427        map.extend(iter);
1428        map
1429    }
1430}
1431
1432impl<K, V, const N: usize> From<[(K, V); N]> for HashSlabMap<K, V, RandomState>
1433where
1434    K: Hash + Eq,
1435{
1436    /// # Examples
1437    ///
1438    /// ```
1439    /// use hashslab::HashSlabMap;
1440    ///
1441    /// let map1 = HashSlabMap::from([(1, 2), (3, 4)]);
1442    /// let map2: HashSlabMap<_, _> = [(1, 2), (3, 4)].into();
1443    /// assert_eq!(map1, map2);
1444    /// ```
1445    fn from(arr: [(K, V); N]) -> Self {
1446        Self::from_iter(arr)
1447    }
1448}
1449
1450impl<K, V1, S1, V2, S2> PartialEq<HashSlabMap<K, V2, S2>> for HashSlabMap<K, V1, S1>
1451where
1452    K: Hash + Eq,
1453    V1: PartialEq<V2>,
1454    S1: BuildHasher,
1455    S2: BuildHasher,
1456{
1457    fn eq(&self, other: &HashSlabMap<K, V2, S2>) -> bool {
1458        if self.len() != other.len() {
1459            return false;
1460        }
1461
1462        self.iter()
1463            .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1464    }
1465}
1466
1467impl<K, V, S> Eq for HashSlabMap<K, V, S>
1468where
1469    K: Eq + Hash,
1470    V: Eq,
1471    S: BuildHasher,
1472{
1473}
1474
1475#[inline]
1476pub(crate) fn make_hasher<K, S>(hash_builder: &S) -> impl Fn(&KeyData<K>) -> u64 + '_
1477where
1478    K: Hash,
1479    S: BuildHasher,
1480{
1481    move |val| hash_builder.hash_one(&val.key)
1482}