hashlink/
linked_hash_map.rs

1use core::{
2    alloc::Layout,
3    borrow::Borrow,
4    cmp::Ordering,
5    fmt,
6    hash::{BuildHasher, Hash, Hasher},
7    iter::FromIterator,
8    marker::PhantomData,
9    mem::{self, MaybeUninit},
10    ops::{Index, IndexMut},
11    ptr::{self, NonNull},
12};
13
14use alloc::boxed::Box;
15use hashbrown::hash_table::{self, HashTable};
16
17use crate::DefaultHashBuilder;
18
19pub enum TryReserveError {
20    CapacityOverflow,
21    AllocError { layout: Layout },
22}
23
24/// A version of `HashMap` that has a user controllable order for its entries.
25///
26/// It achieves this by keeping its entries in an internal linked list and using a `HashMap` to
27/// point at nodes in this linked list.
28///
29/// The order of entries defaults to "insertion order", but the user can also modify the order of
30/// existing entries by manually moving them to the front or back.
31///
32/// There are two kinds of methods that modify the order of the internal list:
33///
34/// * Methods that have names like `to_front` and `to_back` will unsurprisingly move an existing
35///   entry to the front or back
36/// * Methods that have the word `insert` will insert a new entry ot the back of the list, and if
37///   that method might replace an entry, that method will *also move that existing entry to the
38///   back*.
39pub struct LinkedHashMap<K, V, S = DefaultHashBuilder> {
40    table: HashTable<NonNull<Node<K, V>>>,
41    // We always need to keep our custom hash builder outside of the HashTable, because it doesn't
42    // know how to do any hashing itself.
43    hash_builder: S,
44    // Circular linked list of nodes.  If `values` is non-null, it will point to a "guard node"
45    // which will never have an initialized key or value, `values.prev` will contain the last key /
46    // value in the list, `values.next` will contain the first key / value in the list.
47    values: Option<NonNull<Node<K, V>>>,
48    // *Singly* linked list of free nodes.  The `prev` pointers in the free list should be assumed
49    // invalid.
50    free: Option<NonNull<Node<K, V>>>,
51}
52
53impl<K, V> LinkedHashMap<K, V> {
54    #[inline]
55    pub fn new() -> Self {
56        Self {
57            hash_builder: DefaultHashBuilder::default(),
58            table: HashTable::new(),
59            values: None,
60            free: None,
61        }
62    }
63
64    #[inline]
65    pub fn with_capacity(capacity: usize) -> Self {
66        Self {
67            hash_builder: DefaultHashBuilder::default(),
68            table: HashTable::with_capacity(capacity),
69            values: None,
70            free: None,
71        }
72    }
73}
74
75impl<K, V, S> LinkedHashMap<K, V, S> {
76    #[inline]
77    pub fn with_hasher(hash_builder: S) -> Self {
78        Self {
79            hash_builder,
80            table: HashTable::new(),
81            values: None,
82            free: None,
83        }
84    }
85
86    #[inline]
87    pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
88        Self {
89            hash_builder,
90            table: HashTable::with_capacity(capacity),
91            values: None,
92            free: None,
93        }
94    }
95
96    #[inline]
97    pub fn len(&self) -> usize {
98        self.table.len()
99    }
100
101    #[inline]
102    pub fn is_empty(&self) -> bool {
103        self.len() == 0
104    }
105
106    #[inline]
107    pub fn clear(&mut self) {
108        self.table.clear();
109        if let Some(mut values) = self.values {
110            unsafe {
111                drop_value_nodes(values);
112                values.as_mut().links.value = ValueLinks {
113                    prev: values,
114                    next: values,
115                };
116            }
117        }
118    }
119
120    #[inline]
121    pub fn iter(&self) -> Iter<K, V> {
122        let (head, tail) = if let Some(values) = self.values {
123            unsafe {
124                let ValueLinks { next, prev } = values.as_ref().links.value;
125                (next.as_ptr(), prev.as_ptr())
126            }
127        } else {
128            (ptr::null_mut(), ptr::null_mut())
129        };
130
131        Iter {
132            head,
133            tail,
134            remaining: self.len(),
135            marker: PhantomData,
136        }
137    }
138
139    #[inline]
140    pub fn iter_mut(&mut self) -> IterMut<K, V> {
141        let (head, tail) = if let Some(values) = self.values {
142            unsafe {
143                let ValueLinks { next, prev } = values.as_ref().links.value;
144                (Some(next), Some(prev))
145            }
146        } else {
147            (None, None)
148        };
149
150        IterMut {
151            head,
152            tail,
153            remaining: self.len(),
154            marker: PhantomData,
155        }
156    }
157
158    #[inline]
159    pub fn drain(&mut self) -> Drain<'_, K, V> {
160        unsafe {
161            let (head, tail) = if let Some(mut values) = self.values {
162                let ValueLinks { next, prev } = values.as_ref().links.value;
163                values.as_mut().links.value = ValueLinks {
164                    next: values,
165                    prev: values,
166                };
167                (Some(next), Some(prev))
168            } else {
169                (None, None)
170            };
171            let len = self.len();
172
173            self.table.clear();
174
175            Drain {
176                free: (&mut self.free).into(),
177                head,
178                tail,
179                remaining: len,
180                marker: PhantomData,
181            }
182        }
183    }
184
185    #[inline]
186    pub fn keys(&self) -> Keys<K, V> {
187        Keys { inner: self.iter() }
188    }
189
190    #[inline]
191    pub fn values(&self) -> Values<K, V> {
192        Values { inner: self.iter() }
193    }
194
195    #[inline]
196    pub fn values_mut(&mut self) -> ValuesMut<K, V> {
197        ValuesMut {
198            inner: self.iter_mut(),
199        }
200    }
201
202    #[inline]
203    pub fn front(&self) -> Option<(&K, &V)> {
204        if self.is_empty() {
205            return None;
206        }
207        unsafe {
208            let front = (*self.values.as_ptr()).links.value.next.as_ptr();
209            let (key, value) = (*front).entry_ref();
210            Some((key, value))
211        }
212    }
213
214    #[inline]
215    pub fn back(&self) -> Option<(&K, &V)> {
216        if self.is_empty() {
217            return None;
218        }
219        unsafe {
220            let back = &*(*self.values.as_ptr()).links.value.prev.as_ptr();
221            let (key, value) = (*back).entry_ref();
222            Some((key, value))
223        }
224    }
225
226    #[inline]
227    pub fn retain<F>(&mut self, mut f: F)
228    where
229        F: FnMut(&K, &mut V) -> bool,
230    {
231        let free = self.free;
232        let mut drop_filtered_values = DropFilteredValues {
233            free: &mut self.free,
234            cur_free: free,
235        };
236
237        self.table.retain(|&mut node| unsafe {
238            let (k, v) = (*node.as_ptr()).entry_mut();
239            if f(k, v) {
240                true
241            } else {
242                drop_filtered_values.drop_later(node);
243                false
244            }
245        });
246    }
247
248    #[inline]
249    pub fn hasher(&self) -> &S {
250        &self.hash_builder
251    }
252
253    #[inline]
254    pub fn capacity(&self) -> usize {
255        self.table.capacity()
256    }
257}
258
259impl<K, V, S> LinkedHashMap<K, V, S>
260where
261    K: Eq + Hash,
262    S: BuildHasher,
263{
264    #[inline]
265    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S> {
266        match self.raw_entry_mut().from_key(&key) {
267            RawEntryMut::Occupied(occupied) => Entry::Occupied(OccupiedEntry {
268                key,
269                raw_entry: occupied,
270            }),
271            RawEntryMut::Vacant(vacant) => Entry::Vacant(VacantEntry {
272                key,
273                raw_entry: vacant,
274            }),
275        }
276    }
277
278    #[inline]
279    pub fn get<Q>(&self, k: &Q) -> Option<&V>
280    where
281        K: Borrow<Q>,
282        Q: Hash + Eq + ?Sized,
283    {
284        self.raw_entry().from_key(k).map(|(_, v)| v)
285    }
286
287    #[inline]
288    pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
289    where
290        K: Borrow<Q>,
291        Q: Hash + Eq + ?Sized,
292    {
293        self.raw_entry().from_key(k)
294    }
295
296    #[inline]
297    pub fn contains_key<Q>(&self, k: &Q) -> bool
298    where
299        K: Borrow<Q>,
300        Q: Hash + Eq + ?Sized,
301    {
302        self.get(k).is_some()
303    }
304
305    #[inline]
306    pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
307    where
308        K: Borrow<Q>,
309        Q: Hash + Eq + ?Sized,
310    {
311        match self.raw_entry_mut().from_key(k) {
312            RawEntryMut::Occupied(occupied) => Some(occupied.into_mut()),
313            RawEntryMut::Vacant(_) => None,
314        }
315    }
316
317    /// Inserts the given key / value pair at the *back* of the internal linked list.
318    ///
319    /// Returns the previously set value, if one existed prior to this call.  After this call,
320    /// calling `LinkedHashMap::back` will return a reference to this key / value pair.
321    #[inline]
322    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
323        match self.raw_entry_mut().from_key(&k) {
324            RawEntryMut::Occupied(mut occupied) => {
325                occupied.to_back();
326                Some(occupied.replace_value(v))
327            }
328            RawEntryMut::Vacant(vacant) => {
329                vacant.insert(k, v);
330                None
331            }
332        }
333    }
334
335    /// If the given key is not in this map, inserts the key / value pair at the *back* of the
336    /// internal linked list and returns `None`, otherwise, replaces the existing value with the
337    /// given value *without* moving the entry in the internal linked list and returns the previous
338    /// value.
339    #[inline]
340    pub fn replace(&mut self, k: K, v: V) -> Option<V> {
341        match self.raw_entry_mut().from_key(&k) {
342            RawEntryMut::Occupied(mut occupied) => Some(occupied.replace_value(v)),
343            RawEntryMut::Vacant(vacant) => {
344                vacant.insert(k, v);
345                None
346            }
347        }
348    }
349
350    #[inline]
351    pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
352    where
353        K: Borrow<Q>,
354        Q: Hash + Eq + ?Sized,
355    {
356        match self.raw_entry_mut().from_key(k) {
357            RawEntryMut::Occupied(occupied) => Some(occupied.remove()),
358            RawEntryMut::Vacant(_) => None,
359        }
360    }
361
362    #[inline]
363    pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
364    where
365        K: Borrow<Q>,
366        Q: Hash + Eq + ?Sized,
367    {
368        match self.raw_entry_mut().from_key(k) {
369            RawEntryMut::Occupied(occupied) => Some(occupied.remove_entry()),
370            RawEntryMut::Vacant(_) => None,
371        }
372    }
373
374    #[inline]
375    pub fn pop_front(&mut self) -> Option<(K, V)> {
376        if self.is_empty() {
377            return None;
378        }
379        unsafe {
380            let front = (*self.values.as_ptr()).links.value.next;
381            let hash = hash_node(&self.hash_builder, front);
382            match self
383                .raw_entry_mut()
384                .from_hash(hash, |k| k.eq(front.as_ref().key_ref()))
385            {
386                RawEntryMut::Occupied(occupied) => Some(occupied.remove_entry()),
387                RawEntryMut::Vacant(_) => None,
388            }
389        }
390    }
391
392    #[inline]
393    pub fn pop_back(&mut self) -> Option<(K, V)> {
394        if self.is_empty() {
395            return None;
396        }
397        unsafe {
398            let back = (*self.values.as_ptr()).links.value.prev;
399            let hash = hash_node(&self.hash_builder, back);
400            match self
401                .raw_entry_mut()
402                .from_hash(hash, |k| k.eq(back.as_ref().key_ref()))
403            {
404                RawEntryMut::Occupied(occupied) => Some(occupied.remove_entry()),
405                RawEntryMut::Vacant(_) => None,
406            }
407        }
408    }
409
410    /// If an entry with this key exists, move it to the front of the list and return a reference to
411    /// the value.
412    #[inline]
413    pub fn to_front<Q>(&mut self, k: &Q) -> Option<&mut V>
414    where
415        K: Borrow<Q>,
416        Q: Hash + Eq + ?Sized,
417    {
418        match self.raw_entry_mut().from_key(k) {
419            RawEntryMut::Occupied(mut occupied) => {
420                occupied.to_front();
421                Some(occupied.into_mut())
422            }
423            RawEntryMut::Vacant(_) => None,
424        }
425    }
426
427    /// If an entry with this key exists, move it to the back of the list and return a reference to
428    /// the value.
429    #[inline]
430    pub fn to_back<Q>(&mut self, k: &Q) -> Option<&mut V>
431    where
432        K: Borrow<Q>,
433        Q: Hash + Eq + ?Sized,
434    {
435        match self.raw_entry_mut().from_key(k) {
436            RawEntryMut::Occupied(mut occupied) => {
437                occupied.to_back();
438                Some(occupied.into_mut())
439            }
440            RawEntryMut::Vacant(_) => None,
441        }
442    }
443
444    #[inline]
445    pub fn reserve(&mut self, additional: usize) {
446        let hash_builder = &self.hash_builder;
447        self.table
448            .reserve(additional, move |&n| unsafe { hash_node(hash_builder, n) });
449    }
450
451    #[inline]
452    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
453        let hash_builder = &self.hash_builder;
454        self.table
455            .try_reserve(additional, move |&n| unsafe { hash_node(hash_builder, n) })
456            .map_err(|e| match e {
457                hashbrown::TryReserveError::CapacityOverflow => TryReserveError::CapacityOverflow,
458                hashbrown::TryReserveError::AllocError { layout } => {
459                    TryReserveError::AllocError { layout }
460                }
461            })
462    }
463
464    #[inline]
465    pub fn shrink_to_fit(&mut self) {
466        let hash_builder = &self.hash_builder;
467        unsafe {
468            self.table
469                .shrink_to_fit(move |&n| hash_node(hash_builder, n));
470            drop_free_nodes(self.free.take());
471        }
472    }
473
474    pub fn retain_with_order<F>(&mut self, mut f: F)
475    where
476        F: FnMut(&K, &mut V) -> bool,
477    {
478        let free = self.free;
479        let mut drop_filtered_values = DropFilteredValues {
480            free: &mut self.free,
481            cur_free: free,
482        };
483
484        if let Some(values) = self.values {
485            unsafe {
486                let mut cur = values.as_ref().links.value.next;
487                while cur != values {
488                    let next = cur.as_ref().links.value.next;
489                    let filter = {
490                        let (k, v) = (*cur.as_ptr()).entry_mut();
491                        !f(k, v)
492                    };
493                    if filter {
494                        let k = (*cur.as_ptr()).key_ref();
495                        let hash = hash_key(&self.hash_builder, k);
496                        self.table
497                            .find_entry(hash, |o| (*o).as_ref().key_ref().eq(k))
498                            .unwrap()
499                            .remove();
500                        drop_filtered_values.drop_later(cur);
501                    }
502                    cur = next;
503                }
504            }
505        }
506    }
507
508    // Returns the `CursorMut` over the _guard_ node.
509    fn cursor_mut(&mut self) -> CursorMut<K, V, S> {
510        unsafe { ensure_guard_node(&mut self.values) };
511        CursorMut {
512            cur: self.values.as_ptr(),
513            hash_builder: &self.hash_builder,
514            free: &mut self.free,
515            values: &mut self.values,
516            table: &mut self.table,
517        }
518    }
519
520    /// Returns the `CursorMut` over the front node.
521    ///
522    /// Note: The `CursorMut` is pointing to the _guard_ node in an empty `LinkedHashMap` and
523    ///       will always return `None` as its current element, regardless of any move in any
524    ///       direction.
525    pub fn cursor_front_mut(&mut self) -> CursorMut<K, V, S> {
526        let mut c = self.cursor_mut();
527        c.move_next();
528        c
529    }
530
531    /// Returns the `CursorMut` over the back node.
532    ///
533    /// Note: The `CursorMut` is pointing to the _guard_ node in an empty `LinkedHashMap` and
534    ///       will always return `None` as its current element, regardless of any move in any
535    ///       direction.
536    pub fn cursor_back_mut(&mut self) -> CursorMut<K, V, S> {
537        let mut c = self.cursor_mut();
538        c.move_prev();
539        c
540    }
541}
542
543impl<K, V, S> LinkedHashMap<K, V, S>
544where
545    S: BuildHasher,
546{
547    #[inline]
548    pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
549        RawEntryBuilder { map: self }
550    }
551
552    #[inline]
553    pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
554        RawEntryBuilderMut { map: self }
555    }
556}
557
558impl<K, V, S> Default for LinkedHashMap<K, V, S>
559where
560    S: Default,
561{
562    #[inline]
563    fn default() -> Self {
564        Self::with_hasher(S::default())
565    }
566}
567
568impl<K: Hash + Eq, V, S: BuildHasher + Default> FromIterator<(K, V)> for LinkedHashMap<K, V, S> {
569    #[inline]
570    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
571        let iter = iter.into_iter();
572        let mut map = Self::with_capacity_and_hasher(iter.size_hint().0, S::default());
573        map.extend(iter);
574        map
575    }
576}
577
578impl<K, V, S> fmt::Debug for LinkedHashMap<K, V, S>
579where
580    K: fmt::Debug,
581    V: fmt::Debug,
582{
583    #[inline]
584    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
585        f.debug_map().entries(self).finish()
586    }
587}
588
589impl<K: Hash + Eq, V: PartialEq, S: BuildHasher> PartialEq for LinkedHashMap<K, V, S> {
590    #[inline]
591    fn eq(&self, other: &Self) -> bool {
592        self.len() == other.len() && self.iter().eq(other)
593    }
594}
595
596impl<K: Hash + Eq, V: Eq, S: BuildHasher> Eq for LinkedHashMap<K, V, S> {}
597
598impl<K: Hash + Eq + PartialOrd, V: PartialOrd, S: BuildHasher> PartialOrd
599    for LinkedHashMap<K, V, S>
600{
601    #[inline]
602    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
603        self.iter().partial_cmp(other)
604    }
605
606    #[inline]
607    fn lt(&self, other: &Self) -> bool {
608        self.iter().lt(other)
609    }
610
611    #[inline]
612    fn le(&self, other: &Self) -> bool {
613        self.iter().le(other)
614    }
615
616    #[inline]
617    fn ge(&self, other: &Self) -> bool {
618        self.iter().ge(other)
619    }
620
621    #[inline]
622    fn gt(&self, other: &Self) -> bool {
623        self.iter().gt(other)
624    }
625}
626
627impl<K: Hash + Eq + Ord, V: Ord, S: BuildHasher> Ord for LinkedHashMap<K, V, S> {
628    #[inline]
629    fn cmp(&self, other: &Self) -> Ordering {
630        self.iter().cmp(other)
631    }
632}
633
634impl<K: Hash + Eq, V: Hash, S: BuildHasher> Hash for LinkedHashMap<K, V, S> {
635    #[inline]
636    fn hash<H: Hasher>(&self, h: &mut H) {
637        for e in self.iter() {
638            e.hash(h);
639        }
640    }
641}
642
643impl<K, V, S> Drop for LinkedHashMap<K, V, S> {
644    #[inline]
645    fn drop(&mut self) {
646        unsafe {
647            if let Some(values) = self.values {
648                drop_value_nodes(values);
649                let _ = Box::from_raw(values.as_ptr());
650            }
651            drop_free_nodes(self.free);
652        }
653    }
654}
655
656unsafe impl<K: Send, V: Send, S: Send> Send for LinkedHashMap<K, V, S> {}
657unsafe impl<K: Sync, V: Sync, S: Sync> Sync for LinkedHashMap<K, V, S> {}
658
659impl<'a, K, V, S, Q> Index<&'a Q> for LinkedHashMap<K, V, S>
660where
661    K: Hash + Eq + Borrow<Q>,
662    S: BuildHasher,
663    Q: Eq + Hash + ?Sized,
664{
665    type Output = V;
666
667    #[inline]
668    fn index(&self, index: &'a Q) -> &V {
669        self.get(index).expect("no entry found for key")
670    }
671}
672
673impl<'a, K, V, S, Q> IndexMut<&'a Q> for LinkedHashMap<K, V, S>
674where
675    K: Hash + Eq + Borrow<Q>,
676    S: BuildHasher,
677    Q: Eq + Hash + ?Sized,
678{
679    #[inline]
680    fn index_mut(&mut self, index: &'a Q) -> &mut V {
681        self.get_mut(index).expect("no entry found for key")
682    }
683}
684
685impl<K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Clone> Clone for LinkedHashMap<K, V, S> {
686    #[inline]
687    fn clone(&self) -> Self {
688        let mut map = Self::with_hasher(self.hash_builder.clone());
689        map.extend(self.iter().map(|(k, v)| (k.clone(), v.clone())));
690        map
691    }
692}
693
694impl<K: Hash + Eq, V, S: BuildHasher> Extend<(K, V)> for LinkedHashMap<K, V, S> {
695    #[inline]
696    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
697        for (k, v) in iter {
698            self.insert(k, v);
699        }
700    }
701}
702
703impl<'a, K, V, S> Extend<(&'a K, &'a V)> for LinkedHashMap<K, V, S>
704where
705    K: 'a + Hash + Eq + Copy,
706    V: 'a + Copy,
707    S: BuildHasher,
708{
709    #[inline]
710    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
711        for (&k, &v) in iter {
712            self.insert(k, v);
713        }
714    }
715}
716
717pub enum Entry<'a, K, V, S> {
718    Occupied(OccupiedEntry<'a, K, V, S>),
719    Vacant(VacantEntry<'a, K, V, S>),
720}
721
722impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for Entry<'_, K, V, S> {
723    #[inline]
724    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
725        match *self {
726            Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
727            Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
728        }
729    }
730}
731
732impl<'a, K, V, S> Entry<'a, K, V, S> {
733    /// If this entry is vacant, inserts a new entry with the given value and returns a reference to
734    /// it.
735    ///
736    /// If this entry is occupied, this method *moves the occupied entry to the back of the internal
737    /// linked list* and returns a reference to the existing value.
738    #[inline]
739    pub fn or_insert(self, default: V) -> &'a mut V
740    where
741        K: Hash,
742        S: BuildHasher,
743    {
744        match self {
745            Entry::Occupied(mut entry) => {
746                entry.to_back();
747                entry.into_mut()
748            }
749            Entry::Vacant(entry) => entry.insert(default),
750        }
751    }
752
753    /// Similar to `Entry::or_insert`, but accepts a function to construct a new value if this entry
754    /// is vacant.
755    #[inline]
756    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
757    where
758        K: Hash,
759        S: BuildHasher,
760    {
761        match self {
762            Entry::Occupied(mut entry) => {
763                entry.to_back();
764                entry.into_mut()
765            }
766            Entry::Vacant(entry) => entry.insert(default()),
767        }
768    }
769
770    #[inline]
771    pub fn key(&self) -> &K {
772        match *self {
773            Entry::Occupied(ref entry) => entry.key(),
774            Entry::Vacant(ref entry) => entry.key(),
775        }
776    }
777
778    #[inline]
779    pub fn and_modify<F>(self, f: F) -> Self
780    where
781        F: FnOnce(&mut V),
782    {
783        match self {
784            Entry::Occupied(mut entry) => {
785                f(entry.get_mut());
786                Entry::Occupied(entry)
787            }
788            Entry::Vacant(entry) => Entry::Vacant(entry),
789        }
790    }
791}
792
793pub struct OccupiedEntry<'a, K, V, S> {
794    key: K,
795    raw_entry: RawOccupiedEntryMut<'a, K, V, S>,
796}
797
798impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for OccupiedEntry<'_, K, V, S> {
799    #[inline]
800    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801        f.debug_struct("OccupiedEntry")
802            .field("key", self.key())
803            .field("value", self.get())
804            .finish()
805    }
806}
807
808impl<'a, K, V, S> OccupiedEntry<'a, K, V, S> {
809    #[inline]
810    pub fn key(&self) -> &K {
811        self.raw_entry.key()
812    }
813
814    #[inline]
815    pub fn remove_entry(self) -> (K, V) {
816        self.raw_entry.remove_entry()
817    }
818
819    #[inline]
820    pub fn get(&self) -> &V {
821        self.raw_entry.get()
822    }
823
824    #[inline]
825    pub fn get_mut(&mut self) -> &mut V {
826        self.raw_entry.get_mut()
827    }
828
829    #[inline]
830    pub fn into_mut(self) -> &'a mut V {
831        self.raw_entry.into_mut()
832    }
833
834    #[inline]
835    pub fn to_back(&mut self) {
836        self.raw_entry.to_back()
837    }
838
839    #[inline]
840    pub fn to_front(&mut self) {
841        self.raw_entry.to_front()
842    }
843
844    /// Replaces this entry's value with the provided value.
845    ///
846    /// Similarly to `LinkedHashMap::insert`, this moves the existing entry to the back of the
847    /// internal linked list.
848    #[inline]
849    pub fn insert(&mut self, value: V) -> V {
850        self.raw_entry.to_back();
851        self.raw_entry.replace_value(value)
852    }
853
854    #[inline]
855    pub fn remove(self) -> V {
856        self.raw_entry.remove()
857    }
858
859    /// Similar to `OccupiedEntry::replace_entry`, but *does* move the entry to the back of the
860    /// internal linked list.
861    #[inline]
862    pub fn insert_entry(mut self, value: V) -> (K, V) {
863        self.raw_entry.to_back();
864        self.replace_entry(value)
865    }
866
867    /// Returns a `CursorMut` over the current entry.
868    #[inline]
869    pub fn cursor_mut(self) -> CursorMut<'a, K, V, S>
870    where
871        K: Eq + Hash,
872        S: BuildHasher,
873    {
874        self.raw_entry.cursor_mut()
875    }
876
877    /// Replaces the entry's key with the key provided to `LinkedHashMap::entry`, and replaces the
878    /// entry's value with the given `value` parameter.
879    ///
880    /// Does *not* move the entry to the back of the internal linked list.
881    pub fn replace_entry(mut self, value: V) -> (K, V) {
882        let old_key = mem::replace(self.raw_entry.key_mut(), self.key);
883        let old_value = mem::replace(self.raw_entry.get_mut(), value);
884        (old_key, old_value)
885    }
886
887    /// Replaces this entry's key with the key provided to `LinkedHashMap::entry`.
888    ///
889    /// Does *not* move the entry to the back of the internal linked list.
890    #[inline]
891    pub fn replace_key(mut self) -> K {
892        mem::replace(self.raw_entry.key_mut(), self.key)
893    }
894}
895
896pub struct VacantEntry<'a, K, V, S> {
897    key: K,
898    raw_entry: RawVacantEntryMut<'a, K, V, S>,
899}
900
901impl<K: fmt::Debug, V, S> fmt::Debug for VacantEntry<'_, K, V, S> {
902    #[inline]
903    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904        f.debug_tuple("VacantEntry").field(self.key()).finish()
905    }
906}
907
908impl<'a, K, V, S> VacantEntry<'a, K, V, S> {
909    #[inline]
910    pub fn key(&self) -> &K {
911        &self.key
912    }
913
914    #[inline]
915    pub fn into_key(self) -> K {
916        self.key
917    }
918
919    /// Insert's the key for this vacant entry paired with the given value as a new entry at the
920    /// *back* of the internal linked list.
921    #[inline]
922    pub fn insert(self, value: V) -> &'a mut V
923    where
924        K: Hash,
925        S: BuildHasher,
926    {
927        self.raw_entry.insert(self.key, value).1
928    }
929}
930
931pub struct RawEntryBuilder<'a, K, V, S> {
932    map: &'a LinkedHashMap<K, V, S>,
933}
934
935impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
936where
937    S: BuildHasher,
938{
939    #[inline]
940    pub fn from_key<Q>(self, k: &Q) -> Option<(&'a K, &'a V)>
941    where
942        K: Borrow<Q>,
943        Q: Hash + Eq + ?Sized,
944    {
945        let hash = hash_key(&self.map.hash_builder, k);
946        self.from_key_hashed_nocheck(hash, k)
947    }
948
949    #[inline]
950    pub fn from_key_hashed_nocheck<Q>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
951    where
952        K: Borrow<Q>,
953        Q: Hash + Eq + ?Sized,
954    {
955        self.from_hash(hash, move |o| k.eq(o.borrow()))
956    }
957
958    #[inline]
959    pub fn from_hash(
960        self,
961        hash: u64,
962        mut is_match: impl FnMut(&K) -> bool,
963    ) -> Option<(&'a K, &'a V)> {
964        unsafe {
965            let node = self
966                .map
967                .table
968                .find(hash, move |k| is_match((*k).as_ref().key_ref()))?;
969
970            let (key, value) = (*node.as_ptr()).entry_ref();
971            Some((key, value))
972        }
973    }
974}
975
976unsafe impl<K, V, S> Send for RawEntryBuilder<'_, K, V, S>
977where
978    K: Send,
979    V: Send,
980    S: Send,
981{
982}
983
984unsafe impl<K, V, S> Sync for RawEntryBuilder<'_, K, V, S>
985where
986    K: Sync,
987    V: Sync,
988    S: Sync,
989{
990}
991
992pub struct RawEntryBuilderMut<'a, K, V, S> {
993    map: &'a mut LinkedHashMap<K, V, S>,
994}
995
996impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
997where
998    S: BuildHasher,
999{
1000    #[inline]
1001    pub fn from_key<Q>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1002    where
1003        K: Borrow<Q>,
1004        Q: Hash + Eq + ?Sized,
1005    {
1006        let hash = hash_key(&self.map.hash_builder, k);
1007        self.from_key_hashed_nocheck(hash, k)
1008    }
1009
1010    #[inline]
1011    pub fn from_key_hashed_nocheck<Q>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1012    where
1013        K: Borrow<Q>,
1014        Q: Hash + Eq + ?Sized,
1015    {
1016        self.from_hash(hash, move |o| k.eq(o.borrow()))
1017    }
1018
1019    #[inline]
1020    pub fn from_hash(
1021        self,
1022        hash: u64,
1023        mut is_match: impl FnMut(&K) -> bool,
1024    ) -> RawEntryMut<'a, K, V, S> {
1025        let entry = self
1026            .map
1027            .table
1028            .find_entry(hash, move |k| is_match(unsafe { (*k).as_ref().key_ref() }));
1029
1030        match entry {
1031            Ok(occupied) => RawEntryMut::Occupied(RawOccupiedEntryMut {
1032                hash_builder: &self.map.hash_builder,
1033                free: &mut self.map.free,
1034                values: &mut self.map.values,
1035                entry: occupied,
1036            }),
1037            Err(absent) => RawEntryMut::Vacant(RawVacantEntryMut {
1038                hash_builder: &self.map.hash_builder,
1039                values: &mut self.map.values,
1040                free: &mut self.map.free,
1041                entry: absent,
1042            }),
1043        }
1044    }
1045}
1046
1047unsafe impl<K, V, S> Send for RawEntryBuilderMut<'_, K, V, S>
1048where
1049    K: Send,
1050    V: Send,
1051    S: Send,
1052{
1053}
1054
1055unsafe impl<K, V, S> Sync for RawEntryBuilderMut<'_, K, V, S>
1056where
1057    K: Sync,
1058    V: Sync,
1059    S: Sync,
1060{
1061}
1062
1063pub enum RawEntryMut<'a, K, V, S> {
1064    Occupied(RawOccupiedEntryMut<'a, K, V, S>),
1065    Vacant(RawVacantEntryMut<'a, K, V, S>),
1066}
1067
1068impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1069    /// Similarly to `Entry::or_insert`, if this entry is occupied, it will move the existing entry
1070    /// to the back of the internal linked list.
1071    #[inline]
1072    pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1073    where
1074        K: Hash,
1075        S: BuildHasher,
1076    {
1077        match self {
1078            RawEntryMut::Occupied(mut entry) => {
1079                entry.to_back();
1080                entry.into_key_value()
1081            }
1082            RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1083        }
1084    }
1085
1086    /// Similarly to `Entry::or_insert_with`, if this entry is occupied, it will move the existing
1087    /// entry to the back of the internal linked list.
1088    #[inline]
1089    pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1090    where
1091        F: FnOnce() -> (K, V),
1092        K: Hash,
1093        S: BuildHasher,
1094    {
1095        match self {
1096            RawEntryMut::Occupied(mut entry) => {
1097                entry.to_back();
1098                entry.into_key_value()
1099            }
1100            RawEntryMut::Vacant(entry) => {
1101                let (k, v) = default();
1102                entry.insert(k, v)
1103            }
1104        }
1105    }
1106
1107    #[inline]
1108    pub fn and_modify<F>(self, f: F) -> Self
1109    where
1110        F: FnOnce(&mut K, &mut V),
1111    {
1112        match self {
1113            RawEntryMut::Occupied(mut entry) => {
1114                {
1115                    let (k, v) = entry.get_key_value_mut();
1116                    f(k, v);
1117                }
1118                RawEntryMut::Occupied(entry)
1119            }
1120            RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1121        }
1122    }
1123}
1124
1125pub struct RawOccupiedEntryMut<'a, K, V, S> {
1126    hash_builder: &'a S,
1127    free: &'a mut Option<NonNull<Node<K, V>>>,
1128    values: &'a mut Option<NonNull<Node<K, V>>>,
1129    entry: hash_table::OccupiedEntry<'a, NonNull<Node<K, V>>>,
1130}
1131
1132impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
1133    #[inline]
1134    pub fn key(&self) -> &K {
1135        self.get_key_value().0
1136    }
1137
1138    #[inline]
1139    pub fn key_mut(&mut self) -> &mut K {
1140        self.get_key_value_mut().0
1141    }
1142
1143    #[inline]
1144    pub fn into_key(self) -> &'a mut K {
1145        self.into_key_value().0
1146    }
1147
1148    #[inline]
1149    pub fn get(&self) -> &V {
1150        self.get_key_value().1
1151    }
1152
1153    #[inline]
1154    pub fn get_mut(&mut self) -> &mut V {
1155        self.get_key_value_mut().1
1156    }
1157
1158    #[inline]
1159    pub fn into_mut(self) -> &'a mut V {
1160        self.into_key_value().1
1161    }
1162
1163    #[inline]
1164    pub fn get_key_value(&self) -> (&K, &V) {
1165        unsafe {
1166            let node = *self.entry.get();
1167            let (key, value) = (*node.as_ptr()).entry_ref();
1168            (key, value)
1169        }
1170    }
1171
1172    #[inline]
1173    pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1174        unsafe {
1175            let node = *self.entry.get_mut();
1176            let (key, value) = (*node.as_ptr()).entry_mut();
1177            (key, value)
1178        }
1179    }
1180
1181    #[inline]
1182    pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1183        unsafe {
1184            let node = *self.entry.into_mut();
1185            let (key, value) = (*node.as_ptr()).entry_mut();
1186            (key, value)
1187        }
1188    }
1189
1190    #[inline]
1191    pub fn to_back(&mut self) {
1192        unsafe {
1193            let node = *self.entry.get_mut();
1194            detach_node(node);
1195            attach_before(node, NonNull::new_unchecked(self.values.as_ptr()));
1196        }
1197    }
1198
1199    #[inline]
1200    pub fn to_front(&mut self) {
1201        unsafe {
1202            let node = *self.entry.get_mut();
1203            detach_node(node);
1204            attach_before(node, (*self.values.as_ptr()).links.value.next);
1205        }
1206    }
1207
1208    #[inline]
1209    pub fn replace_value(&mut self, value: V) -> V {
1210        unsafe {
1211            let mut node = *self.entry.get_mut();
1212            mem::replace(&mut node.as_mut().entry_mut().1, value)
1213        }
1214    }
1215
1216    #[inline]
1217    pub fn replace_key(&mut self, key: K) -> K {
1218        unsafe {
1219            let mut node = *self.entry.get_mut();
1220            mem::replace(&mut node.as_mut().entry_mut().0, key)
1221        }
1222    }
1223
1224    #[inline]
1225    pub fn remove(self) -> V {
1226        self.remove_entry().1
1227    }
1228
1229    #[inline]
1230    pub fn remove_entry(self) -> (K, V) {
1231        let node = self.entry.remove().0;
1232        unsafe { remove_node(self.free, node) }
1233    }
1234
1235    /// Returns a `CursorMut` over the current entry.
1236    #[inline]
1237    pub fn cursor_mut(self) -> CursorMut<'a, K, V, S>
1238    where
1239        K: Eq + Hash,
1240        S: BuildHasher,
1241    {
1242        CursorMut {
1243            cur: self.entry.get().as_ptr(),
1244            hash_builder: self.hash_builder,
1245            free: self.free,
1246            values: self.values,
1247            table: self.entry.into_table(),
1248        }
1249    }
1250}
1251
1252pub struct RawVacantEntryMut<'a, K, V, S> {
1253    hash_builder: &'a S,
1254    values: &'a mut Option<NonNull<Node<K, V>>>,
1255    free: &'a mut Option<NonNull<Node<K, V>>>,
1256    entry: hash_table::AbsentEntry<'a, NonNull<Node<K, V>>>,
1257}
1258
1259impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1260    #[inline]
1261    pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1262    where
1263        K: Hash,
1264        S: BuildHasher,
1265    {
1266        let hash = hash_key(self.hash_builder, &key);
1267        self.insert_hashed_nocheck(hash, key, value)
1268    }
1269
1270    #[inline]
1271    pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1272    where
1273        K: Hash,
1274        S: BuildHasher,
1275    {
1276        let hash_builder = self.hash_builder;
1277        self.insert_with_hasher(hash, key, value, |k| hash_key(hash_builder, k))
1278    }
1279
1280    #[inline]
1281    pub fn insert_with_hasher(
1282        self,
1283        hash: u64,
1284        key: K,
1285        value: V,
1286        hasher: impl Fn(&K) -> u64,
1287    ) -> (&'a mut K, &'a mut V)
1288    where
1289        S: BuildHasher,
1290    {
1291        unsafe {
1292            ensure_guard_node(self.values);
1293            let mut new_node = allocate_node(self.free);
1294            new_node.as_mut().put_entry((key, value));
1295            attach_before(new_node, NonNull::new_unchecked(self.values.as_ptr()));
1296
1297            let node = self
1298                .entry
1299                .into_table()
1300                .insert_unique(hash, new_node, move |k| hasher((*k).as_ref().key_ref()))
1301                .into_mut();
1302
1303            let (key, value) = (*node.as_ptr()).entry_mut();
1304            (key, value)
1305        }
1306    }
1307}
1308
1309impl<K, V, S> fmt::Debug for RawEntryBuilderMut<'_, K, V, S> {
1310    #[inline]
1311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1312        f.debug_struct("RawEntryBuilder").finish()
1313    }
1314}
1315
1316impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for RawEntryMut<'_, K, V, S> {
1317    #[inline]
1318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1319        match *self {
1320            RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1321            RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1322        }
1323    }
1324}
1325
1326impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for RawOccupiedEntryMut<'_, K, V, S> {
1327    #[inline]
1328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1329        f.debug_struct("RawOccupiedEntryMut")
1330            .field("key", self.key())
1331            .field("value", self.get())
1332            .finish()
1333    }
1334}
1335
1336impl<K, V, S> fmt::Debug for RawVacantEntryMut<'_, K, V, S> {
1337    #[inline]
1338    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1339        f.debug_struct("RawVacantEntryMut").finish()
1340    }
1341}
1342
1343impl<K, V, S> fmt::Debug for RawEntryBuilder<'_, K, V, S> {
1344    #[inline]
1345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1346        f.debug_struct("RawEntryBuilder").finish()
1347    }
1348}
1349
1350unsafe impl<K, V, S> Send for RawOccupiedEntryMut<'_, K, V, S>
1351where
1352    K: Send,
1353    V: Send,
1354    S: Send,
1355{
1356}
1357
1358unsafe impl<K, V, S> Sync for RawOccupiedEntryMut<'_, K, V, S>
1359where
1360    K: Sync,
1361    V: Sync,
1362    S: Sync,
1363{
1364}
1365
1366unsafe impl<K, V, S> Send for RawVacantEntryMut<'_, K, V, S>
1367where
1368    K: Send,
1369    V: Send,
1370    S: Send,
1371{
1372}
1373
1374unsafe impl<K, V, S> Sync for RawVacantEntryMut<'_, K, V, S>
1375where
1376    K: Sync,
1377    V: Sync,
1378    S: Sync,
1379{
1380}
1381
1382pub struct Iter<'a, K, V> {
1383    head: *const Node<K, V>,
1384    tail: *const Node<K, V>,
1385    remaining: usize,
1386    marker: PhantomData<(&'a K, &'a V)>,
1387}
1388
1389pub struct IterMut<'a, K, V> {
1390    head: Option<NonNull<Node<K, V>>>,
1391    tail: Option<NonNull<Node<K, V>>>,
1392    remaining: usize,
1393    marker: PhantomData<(&'a K, &'a mut V)>,
1394}
1395
1396pub struct IntoIter<K, V> {
1397    head: Option<NonNull<Node<K, V>>>,
1398    tail: Option<NonNull<Node<K, V>>>,
1399    remaining: usize,
1400    marker: PhantomData<(K, V)>,
1401}
1402
1403pub struct Drain<'a, K, V> {
1404    free: NonNull<Option<NonNull<Node<K, V>>>>,
1405    head: Option<NonNull<Node<K, V>>>,
1406    tail: Option<NonNull<Node<K, V>>>,
1407    remaining: usize,
1408    // We want `Drain` to be covariant
1409    marker: PhantomData<(K, V, &'a LinkedHashMap<K, V>)>,
1410}
1411
1412impl<K, V> IterMut<'_, K, V> {
1413    #[inline]
1414    pub(crate) fn iter(&self) -> Iter<'_, K, V> {
1415        Iter {
1416            head: self.head.as_ptr(),
1417            tail: self.tail.as_ptr(),
1418            remaining: self.remaining,
1419            marker: PhantomData,
1420        }
1421    }
1422}
1423
1424impl<K, V> IntoIter<K, V> {
1425    #[inline]
1426    pub(crate) fn iter(&self) -> Iter<'_, K, V> {
1427        Iter {
1428            head: self.head.as_ptr(),
1429            tail: self.tail.as_ptr(),
1430            remaining: self.remaining,
1431            marker: PhantomData,
1432        }
1433    }
1434}
1435
1436impl<K, V> Drain<'_, K, V> {
1437    #[inline]
1438    pub(crate) fn iter(&self) -> Iter<'_, K, V> {
1439        Iter {
1440            head: self.head.as_ptr(),
1441            tail: self.tail.as_ptr(),
1442            remaining: self.remaining,
1443            marker: PhantomData,
1444        }
1445    }
1446}
1447
1448unsafe impl<K, V> Send for Iter<'_, K, V>
1449where
1450    K: Send,
1451    V: Send,
1452{
1453}
1454
1455unsafe impl<K, V> Send for IterMut<'_, K, V>
1456where
1457    K: Send,
1458    V: Send,
1459{
1460}
1461
1462unsafe impl<K, V> Send for IntoIter<K, V>
1463where
1464    K: Send,
1465    V: Send,
1466{
1467}
1468
1469unsafe impl<K, V> Send for Drain<'_, K, V>
1470where
1471    K: Send,
1472    V: Send,
1473{
1474}
1475
1476unsafe impl<K, V> Sync for Iter<'_, K, V>
1477where
1478    K: Sync,
1479    V: Sync,
1480{
1481}
1482
1483unsafe impl<K, V> Sync for IterMut<'_, K, V>
1484where
1485    K: Sync,
1486    V: Sync,
1487{
1488}
1489
1490unsafe impl<K, V> Sync for IntoIter<K, V>
1491where
1492    K: Sync,
1493    V: Sync,
1494{
1495}
1496
1497unsafe impl<K, V> Sync for Drain<'_, K, V>
1498where
1499    K: Sync,
1500    V: Sync,
1501{
1502}
1503
1504impl<K, V> Clone for Iter<'_, K, V> {
1505    #[inline]
1506    fn clone(&self) -> Self {
1507        Iter { ..*self }
1508    }
1509}
1510
1511impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
1512    #[inline]
1513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514        f.debug_list().entries(self.clone()).finish()
1515    }
1516}
1517
1518impl<K, V> fmt::Debug for IterMut<'_, K, V>
1519where
1520    K: fmt::Debug,
1521    V: fmt::Debug,
1522{
1523    #[inline]
1524    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1525        f.debug_list().entries(self.iter()).finish()
1526    }
1527}
1528
1529impl<K, V> fmt::Debug for IntoIter<K, V>
1530where
1531    K: fmt::Debug,
1532    V: fmt::Debug,
1533{
1534    #[inline]
1535    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1536        f.debug_list().entries(self.iter()).finish()
1537    }
1538}
1539
1540impl<K, V> fmt::Debug for Drain<'_, K, V>
1541where
1542    K: fmt::Debug,
1543    V: fmt::Debug,
1544{
1545    #[inline]
1546    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547        f.debug_list().entries(self.iter()).finish()
1548    }
1549}
1550
1551impl<'a, K, V> Iterator for Iter<'a, K, V> {
1552    type Item = (&'a K, &'a V);
1553
1554    #[inline]
1555    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1556        if self.remaining == 0 {
1557            None
1558        } else {
1559            self.remaining -= 1;
1560            unsafe {
1561                let (key, value) = (*self.head).entry_ref();
1562                self.head = (*self.head).links.value.next.as_ptr();
1563                Some((key, value))
1564            }
1565        }
1566    }
1567
1568    #[inline]
1569    fn size_hint(&self) -> (usize, Option<usize>) {
1570        (self.remaining, Some(self.remaining))
1571    }
1572}
1573
1574impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1575    type Item = (&'a K, &'a mut V);
1576
1577    #[inline]
1578    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1579        if self.remaining == 0 {
1580            None
1581        } else {
1582            self.remaining -= 1;
1583            unsafe {
1584                let head = self.head.as_ptr();
1585                let (key, value) = (*head).entry_mut();
1586                self.head = Some((*head).links.value.next);
1587                Some((key, value))
1588            }
1589        }
1590    }
1591
1592    #[inline]
1593    fn size_hint(&self) -> (usize, Option<usize>) {
1594        (self.remaining, Some(self.remaining))
1595    }
1596}
1597
1598impl<K, V> Iterator for IntoIter<K, V> {
1599    type Item = (K, V);
1600
1601    #[inline]
1602    fn next(&mut self) -> Option<(K, V)> {
1603        if self.remaining == 0 {
1604            return None;
1605        }
1606        self.remaining -= 1;
1607        unsafe {
1608            let head = self.head.as_ptr();
1609            self.head = Some((*head).links.value.next);
1610            let mut e = Box::from_raw(head);
1611            Some(e.take_entry())
1612        }
1613    }
1614
1615    #[inline]
1616    fn size_hint(&self) -> (usize, Option<usize>) {
1617        (self.remaining, Some(self.remaining))
1618    }
1619}
1620
1621impl<K, V> Iterator for Drain<'_, K, V> {
1622    type Item = (K, V);
1623
1624    #[inline]
1625    fn next(&mut self) -> Option<(K, V)> {
1626        if self.remaining == 0 {
1627            return None;
1628        }
1629        self.remaining -= 1;
1630        unsafe {
1631            let mut head = NonNull::new_unchecked(self.head.as_ptr());
1632            self.head = Some(head.as_ref().links.value.next);
1633            let entry = head.as_mut().take_entry();
1634            push_free(self.free.as_mut(), head);
1635            Some(entry)
1636        }
1637    }
1638
1639    #[inline]
1640    fn size_hint(&self) -> (usize, Option<usize>) {
1641        (self.remaining, Some(self.remaining))
1642    }
1643}
1644
1645impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1646    #[inline]
1647    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1648        if self.remaining == 0 {
1649            None
1650        } else {
1651            self.remaining -= 1;
1652            unsafe {
1653                let tail = self.tail;
1654                self.tail = (*tail).links.value.prev.as_ptr();
1655                let (key, value) = (*tail).entry_ref();
1656                Some((key, value))
1657            }
1658        }
1659    }
1660}
1661
1662impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1663    #[inline]
1664    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1665        if self.remaining == 0 {
1666            None
1667        } else {
1668            self.remaining -= 1;
1669            unsafe {
1670                let tail = self.tail.as_ptr();
1671                self.tail = Some((*tail).links.value.prev);
1672                let (key, value) = (*tail).entry_mut();
1673                Some((key, value))
1674            }
1675        }
1676    }
1677}
1678
1679impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1680    #[inline]
1681    fn next_back(&mut self) -> Option<(K, V)> {
1682        if self.remaining == 0 {
1683            return None;
1684        }
1685        self.remaining -= 1;
1686        unsafe {
1687            let mut e = *Box::from_raw(self.tail.as_ptr());
1688            self.tail = Some(e.links.value.prev);
1689            Some(e.take_entry())
1690        }
1691    }
1692}
1693
1694impl<K, V> DoubleEndedIterator for Drain<'_, K, V> {
1695    #[inline]
1696    fn next_back(&mut self) -> Option<(K, V)> {
1697        if self.remaining == 0 {
1698            return None;
1699        }
1700        self.remaining -= 1;
1701        unsafe {
1702            let mut tail = NonNull::new_unchecked(self.tail.as_ptr());
1703            self.tail = Some(tail.as_ref().links.value.prev);
1704            let entry = tail.as_mut().take_entry();
1705            push_free(&mut *self.free.as_ptr(), tail);
1706            Some(entry)
1707        }
1708    }
1709}
1710
1711impl<K, V> ExactSizeIterator for Iter<'_, K, V> {}
1712
1713impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {}
1714
1715impl<K, V> ExactSizeIterator for IntoIter<K, V> {}
1716
1717impl<K, V> Drop for IntoIter<K, V> {
1718    #[inline]
1719    fn drop(&mut self) {
1720        for _ in 0..self.remaining {
1721            unsafe {
1722                let tail = self.tail.as_ptr();
1723                self.tail = Some((*tail).links.value.prev);
1724                (*tail).take_entry();
1725                let _ = Box::from_raw(tail);
1726            }
1727        }
1728    }
1729}
1730
1731impl<K, V> Drop for Drain<'_, K, V> {
1732    #[inline]
1733    fn drop(&mut self) {
1734        for _ in 0..self.remaining {
1735            unsafe {
1736                let mut tail = NonNull::new_unchecked(self.tail.as_ptr());
1737                self.tail = Some(tail.as_ref().links.value.prev);
1738                tail.as_mut().take_entry();
1739                push_free(&mut *self.free.as_ptr(), tail);
1740            }
1741        }
1742    }
1743}
1744
1745/// The `CursorMut` struct and its implementation provide the basic mutable Cursor API for Linked
1746/// lists as proposed in
1747/// [here](https://github.com/rust-lang/rfcs/blob/master/text/2570-linked-list-cursors.md), with
1748/// several exceptions:
1749///
1750/// - It behaves similarly to Rust's Iterators, returning `None` when the end of the list is
1751///   reached. A _guard_ node is positioned between the head and tail of the linked list to
1752///   facilitate this. If the cursor is over this guard node, `None` is returned, signaling the end
1753///   or start of the list. From this position, the cursor can move in either direction as the
1754///   linked list is circular, with the guard node connecting the two ends.
1755/// - The current implementation does not include an `index` method, as it does not track the index
1756///   of its elements. It provides access to each map entry as a tuple of `(&K, &mut V)`.
1757///
1758pub struct CursorMut<'a, K, V, S> {
1759    cur: *mut Node<K, V>,
1760    hash_builder: &'a S,
1761    free: &'a mut Option<NonNull<Node<K, V>>>,
1762    values: &'a mut Option<NonNull<Node<K, V>>>,
1763    table: &'a mut hashbrown::HashTable<NonNull<Node<K, V>>>,
1764}
1765
1766impl<K, V, S> CursorMut<'_, K, V, S> {
1767    /// Returns an `Option` of the current element in the list, provided it is not the
1768    /// _guard_ node, and `None` overwise.
1769    #[inline]
1770    pub fn current(&mut self) -> Option<(&K, &mut V)> {
1771        unsafe {
1772            let at = NonNull::new_unchecked(self.cur);
1773            self.peek(at)
1774        }
1775    }
1776
1777    /// Retrieves the next element in the list (moving towards the end).
1778    #[inline]
1779    pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
1780        unsafe {
1781            let at = (*self.cur).links.value.next;
1782            self.peek(at)
1783        }
1784    }
1785
1786    /// Retrieves the previous element in the list (moving towards the front).
1787    #[inline]
1788    pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
1789        unsafe {
1790            let at = (*self.cur).links.value.prev;
1791            self.peek(at)
1792        }
1793    }
1794
1795    // Retrieves the element without advancing current position to it.
1796    #[inline]
1797    fn peek(&mut self, at: NonNull<Node<K, V>>) -> Option<(&K, &mut V)> {
1798        if let Some(values) = self.values {
1799            unsafe {
1800                let node = at.as_ptr();
1801                if node == values.as_ptr() {
1802                    None
1803                } else {
1804                    let entry = (*node).entry_mut();
1805                    Some((&entry.0, &mut entry.1))
1806                }
1807            }
1808        } else {
1809            None
1810        }
1811    }
1812
1813    /// Updates the pointer to the current element to the next element in the
1814    /// list (that is, moving towards the end).
1815    #[inline]
1816    pub fn move_next(&mut self) {
1817        let at = unsafe { (*self.cur).links.value.next };
1818        self.muv(at);
1819    }
1820
1821    /// Updates the pointer to the current element to the previous element in the
1822    /// list (that is, moving towards the front).
1823    #[inline]
1824    pub fn move_prev(&mut self) {
1825        let at = unsafe { (*self.cur).links.value.prev };
1826        self.muv(at);
1827    }
1828
1829    // Updates the pointer to the current element to the one returned by the at closure function.
1830    #[inline]
1831    fn muv(&mut self, at: NonNull<Node<K, V>>) {
1832        self.cur = at.as_ptr();
1833    }
1834
1835    /// Inserts the provided key and value before the current element. It checks if an entry
1836    /// with the given key exists and, if so, replaces its value with the provided `key`
1837    /// parameter. The key is not updated; this matters for types that can be `==` without
1838    /// being identical.
1839    ///
1840    /// If the entry doesn't exist, it creates a new one. If a value has been updated, the
1841    /// function returns the *old* value wrapped with `Some`  and `None` otherwise.
1842    #[inline]
1843    pub fn insert_before(&mut self, key: K, value: V) -> Option<V>
1844    where
1845        K: Eq + Hash,
1846        S: BuildHasher,
1847    {
1848        let before = unsafe { NonNull::new_unchecked(self.cur) };
1849        self.insert(key, value, before)
1850    }
1851
1852    /// Inserts the provided key and value after the current element. It checks if an entry
1853    /// with the given key exists and, if so, replaces its value with the provided `key`
1854    /// parameter. The key is not updated; this matters for types that can be `==` without
1855    /// being identical.
1856    ///
1857    /// If the entry doesn't exist, it creates a new one. If a value has been updated, the
1858    /// function returns the *old* value wrapped with `Some`  and `None` otherwise.
1859    #[inline]
1860    pub fn insert_after(&mut self, key: K, value: V) -> Option<V>
1861    where
1862        K: Eq + Hash,
1863        S: BuildHasher,
1864    {
1865        let before = unsafe { (*self.cur).links.value.next };
1866        self.insert(key, value, before)
1867    }
1868
1869    // Inserts an element immediately before the given `before` node.
1870    #[inline]
1871    fn insert(&mut self, key: K, value: V, before: NonNull<Node<K, V>>) -> Option<V>
1872    where
1873        K: Eq + Hash,
1874        S: BuildHasher,
1875    {
1876        unsafe {
1877            let hash = hash_key(self.hash_builder, &key);
1878            let i_entry = self
1879                .table
1880                .find_entry(hash, |o| (*o).as_ref().key_ref().eq(&key));
1881
1882            match i_entry {
1883                Ok(occupied) => {
1884                    let mut node = *occupied.into_mut();
1885                    let pv = mem::replace(&mut node.as_mut().entry_mut().1, value);
1886                    if node != before {
1887                        detach_node(node);
1888                        attach_before(node, before);
1889                    }
1890                    Some(pv)
1891                }
1892                Err(_) => {
1893                    let mut new_node = allocate_node(self.free);
1894                    new_node.as_mut().put_entry((key, value));
1895                    attach_before(new_node, before);
1896                    let hash_builder = self.hash_builder;
1897                    self.table.insert_unique(hash, new_node, move |k| {
1898                        hash_key(hash_builder, (*k).as_ref().key_ref())
1899                    });
1900                    None
1901                }
1902            }
1903        }
1904    }
1905}
1906
1907pub struct Keys<'a, K, V> {
1908    inner: Iter<'a, K, V>,
1909}
1910
1911impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
1912    #[inline]
1913    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1914        f.debug_list().entries(self.clone()).finish()
1915    }
1916}
1917
1918impl<'a, K, V> Clone for Keys<'a, K, V> {
1919    #[inline]
1920    fn clone(&self) -> Keys<'a, K, V> {
1921        Keys {
1922            inner: self.inner.clone(),
1923        }
1924    }
1925}
1926
1927impl<'a, K, V> Iterator for Keys<'a, K, V> {
1928    type Item = &'a K;
1929
1930    #[inline]
1931    fn next(&mut self) -> Option<&'a K> {
1932        self.inner.next().map(|e| e.0)
1933    }
1934
1935    #[inline]
1936    fn size_hint(&self) -> (usize, Option<usize>) {
1937        self.inner.size_hint()
1938    }
1939}
1940
1941impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1942    #[inline]
1943    fn next_back(&mut self) -> Option<&'a K> {
1944        self.inner.next_back().map(|e| e.0)
1945    }
1946}
1947
1948impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1949    #[inline]
1950    fn len(&self) -> usize {
1951        self.inner.len()
1952    }
1953}
1954
1955pub struct Values<'a, K, V> {
1956    inner: Iter<'a, K, V>,
1957}
1958
1959impl<K, V> Clone for Values<'_, K, V> {
1960    #[inline]
1961    fn clone(&self) -> Self {
1962        Values {
1963            inner: self.inner.clone(),
1964        }
1965    }
1966}
1967
1968impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
1969    #[inline]
1970    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1971        f.debug_list().entries(self.clone()).finish()
1972    }
1973}
1974
1975impl<'a, K, V> Iterator for Values<'a, K, V> {
1976    type Item = &'a V;
1977
1978    #[inline]
1979    fn next(&mut self) -> Option<&'a V> {
1980        self.inner.next().map(|e| e.1)
1981    }
1982
1983    #[inline]
1984    fn size_hint(&self) -> (usize, Option<usize>) {
1985        self.inner.size_hint()
1986    }
1987}
1988
1989impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1990    #[inline]
1991    fn next_back(&mut self) -> Option<&'a V> {
1992        self.inner.next_back().map(|e| e.1)
1993    }
1994}
1995
1996impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1997    #[inline]
1998    fn len(&self) -> usize {
1999        self.inner.len()
2000    }
2001}
2002
2003pub struct ValuesMut<'a, K, V> {
2004    inner: IterMut<'a, K, V>,
2005}
2006
2007impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
2008where
2009    K: fmt::Debug,
2010    V: fmt::Debug,
2011{
2012    #[inline]
2013    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2014        f.debug_list().entries(self.inner.iter()).finish()
2015    }
2016}
2017
2018impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2019    type Item = &'a mut V;
2020
2021    #[inline]
2022    fn next(&mut self) -> Option<&'a mut V> {
2023        self.inner.next().map(|e| e.1)
2024    }
2025
2026    #[inline]
2027    fn size_hint(&self) -> (usize, Option<usize>) {
2028        self.inner.size_hint()
2029    }
2030}
2031
2032impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2033    #[inline]
2034    fn next_back(&mut self) -> Option<&'a mut V> {
2035        self.inner.next_back().map(|e| e.1)
2036    }
2037}
2038
2039impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2040    #[inline]
2041    fn len(&self) -> usize {
2042        self.inner.len()
2043    }
2044}
2045
2046impl<'a, K, V, S> IntoIterator for &'a LinkedHashMap<K, V, S> {
2047    type Item = (&'a K, &'a V);
2048    type IntoIter = Iter<'a, K, V>;
2049
2050    #[inline]
2051    fn into_iter(self) -> Iter<'a, K, V> {
2052        self.iter()
2053    }
2054}
2055
2056impl<'a, K, V, S> IntoIterator for &'a mut LinkedHashMap<K, V, S> {
2057    type Item = (&'a K, &'a mut V);
2058    type IntoIter = IterMut<'a, K, V>;
2059
2060    #[inline]
2061    fn into_iter(self) -> IterMut<'a, K, V> {
2062        self.iter_mut()
2063    }
2064}
2065
2066impl<K, V, S> IntoIterator for LinkedHashMap<K, V, S> {
2067    type Item = (K, V);
2068    type IntoIter = IntoIter<K, V>;
2069
2070    #[inline]
2071    fn into_iter(mut self) -> IntoIter<K, V> {
2072        unsafe {
2073            let (head, tail) = if let Some(values) = self.values {
2074                let ValueLinks {
2075                    next: head,
2076                    prev: tail,
2077                } = values.as_ref().links.value;
2078
2079                let _ = Box::from_raw(self.values.as_ptr());
2080                self.values = None;
2081
2082                (Some(head), Some(tail))
2083            } else {
2084                (None, None)
2085            };
2086            let len = self.len();
2087
2088            drop_free_nodes(self.free.take());
2089
2090            self.table.clear();
2091
2092            IntoIter {
2093                head,
2094                tail,
2095                remaining: len,
2096                marker: PhantomData,
2097            }
2098        }
2099    }
2100}
2101
2102struct ValueLinks<K, V> {
2103    next: NonNull<Node<K, V>>,
2104    prev: NonNull<Node<K, V>>,
2105}
2106
2107impl<K, V> Clone for ValueLinks<K, V> {
2108    #[inline]
2109    fn clone(&self) -> Self {
2110        *self
2111    }
2112}
2113
2114impl<K, V> Copy for ValueLinks<K, V> {}
2115
2116struct FreeLink<K, V> {
2117    next: Option<NonNull<Node<K, V>>>,
2118}
2119
2120impl<K, V> Clone for FreeLink<K, V> {
2121    #[inline]
2122    fn clone(&self) -> Self {
2123        *self
2124    }
2125}
2126
2127impl<K, V> Copy for FreeLink<K, V> {}
2128
2129union Links<K, V> {
2130    value: ValueLinks<K, V>,
2131    free: FreeLink<K, V>,
2132}
2133
2134struct Node<K, V> {
2135    entry: MaybeUninit<(K, V)>,
2136    links: Links<K, V>,
2137}
2138
2139impl<K, V> Node<K, V> {
2140    #[inline]
2141    unsafe fn put_entry(&mut self, entry: (K, V)) {
2142        self.entry.as_mut_ptr().write(entry)
2143    }
2144
2145    #[inline]
2146    unsafe fn entry_ref(&self) -> &(K, V) {
2147        &*self.entry.as_ptr()
2148    }
2149
2150    #[inline]
2151    unsafe fn key_ref(&self) -> &K {
2152        &(*self.entry.as_ptr()).0
2153    }
2154
2155    #[inline]
2156    unsafe fn entry_mut(&mut self) -> &mut (K, V) {
2157        &mut *self.entry.as_mut_ptr()
2158    }
2159
2160    #[inline]
2161    unsafe fn take_entry(&mut self) -> (K, V) {
2162        self.entry.as_ptr().read()
2163    }
2164}
2165
2166trait OptNonNullExt<T> {
2167    #[allow(clippy::wrong_self_convention)]
2168    fn as_ptr(self) -> *mut T;
2169}
2170
2171impl<T> OptNonNullExt<T> for Option<NonNull<T>> {
2172    #[inline]
2173    fn as_ptr(self) -> *mut T {
2174        match self {
2175            Some(ptr) => ptr.as_ptr(),
2176            None => ptr::null_mut(),
2177        }
2178    }
2179}
2180
2181// Allocate a circular list guard node if not present.
2182#[inline]
2183unsafe fn ensure_guard_node<K, V>(head: &mut Option<NonNull<Node<K, V>>>) {
2184    if head.is_none() {
2185        let mut p = NonNull::new_unchecked(Box::into_raw(Box::new(Node {
2186            entry: MaybeUninit::uninit(),
2187            links: Links {
2188                value: ValueLinks {
2189                    next: NonNull::dangling(),
2190                    prev: NonNull::dangling(),
2191                },
2192            },
2193        })));
2194        p.as_mut().links.value = ValueLinks { next: p, prev: p };
2195        *head = Some(p);
2196    }
2197}
2198
2199// Attach the `to_attach` node to the existing circular list *before* `node`.
2200#[inline]
2201unsafe fn attach_before<K, V>(mut to_attach: NonNull<Node<K, V>>, mut node: NonNull<Node<K, V>>) {
2202    to_attach.as_mut().links.value = ValueLinks {
2203        prev: node.as_ref().links.value.prev,
2204        next: node,
2205    };
2206    node.as_mut().links.value.prev = to_attach;
2207    (*to_attach.as_mut().links.value.prev.as_ptr())
2208        .links
2209        .value
2210        .next = to_attach;
2211}
2212
2213#[inline]
2214unsafe fn detach_node<K, V>(mut node: NonNull<Node<K, V>>) {
2215    node.as_mut().links.value.prev.as_mut().links.value.next = node.as_ref().links.value.next;
2216    node.as_mut().links.value.next.as_mut().links.value.prev = node.as_ref().links.value.prev;
2217}
2218
2219#[inline]
2220unsafe fn push_free<K, V>(
2221    free_list: &mut Option<NonNull<Node<K, V>>>,
2222    mut node: NonNull<Node<K, V>>,
2223) {
2224    node.as_mut().links.free.next = *free_list;
2225    *free_list = Some(node);
2226}
2227
2228#[inline]
2229unsafe fn pop_free<K, V>(
2230    free_list: &mut Option<NonNull<Node<K, V>>>,
2231) -> Option<NonNull<Node<K, V>>> {
2232    if let Some(free) = *free_list {
2233        *free_list = free.as_ref().links.free.next;
2234        Some(free)
2235    } else {
2236        None
2237    }
2238}
2239
2240#[inline]
2241unsafe fn allocate_node<K, V>(free_list: &mut Option<NonNull<Node<K, V>>>) -> NonNull<Node<K, V>> {
2242    if let Some(mut free) = pop_free(free_list) {
2243        free.as_mut().links.value = ValueLinks {
2244            next: NonNull::dangling(),
2245            prev: NonNull::dangling(),
2246        };
2247        free
2248    } else {
2249        NonNull::new_unchecked(Box::into_raw(Box::new(Node {
2250            entry: MaybeUninit::uninit(),
2251            links: Links {
2252                value: ValueLinks {
2253                    next: NonNull::dangling(),
2254                    prev: NonNull::dangling(),
2255                },
2256            },
2257        })))
2258    }
2259}
2260
2261// Given node is assumed to be the guard node and is *not* dropped.
2262#[inline]
2263unsafe fn drop_value_nodes<K, V>(guard: NonNull<Node<K, V>>) {
2264    let mut cur = guard.as_ref().links.value.prev;
2265    while cur != guard {
2266        let prev = cur.as_ref().links.value.prev;
2267        cur.as_mut().take_entry();
2268        let _ = Box::from_raw(cur.as_ptr());
2269        cur = prev;
2270    }
2271}
2272
2273// Drops all linked free nodes starting with the given node.  Free nodes are only non-circular
2274// singly linked, and should have uninitialized keys / values.
2275#[inline]
2276unsafe fn drop_free_nodes<K, V>(mut free: Option<NonNull<Node<K, V>>>) {
2277    while let Some(some_free) = free {
2278        let next_free = some_free.as_ref().links.free.next;
2279        let _ = Box::from_raw(some_free.as_ptr());
2280        free = next_free;
2281    }
2282}
2283
2284#[inline]
2285unsafe fn remove_node<K, V>(
2286    free_list: &mut Option<NonNull<Node<K, V>>>,
2287    mut node: NonNull<Node<K, V>>,
2288) -> (K, V) {
2289    detach_node(node);
2290    push_free(free_list, node);
2291    node.as_mut().take_entry()
2292}
2293
2294#[inline]
2295unsafe fn hash_node<S, K, V>(s: &S, node: NonNull<Node<K, V>>) -> u64
2296where
2297    S: BuildHasher,
2298    K: Hash,
2299{
2300    hash_key(s, node.as_ref().key_ref())
2301}
2302
2303#[inline]
2304fn hash_key<S, Q>(s: &S, k: &Q) -> u64
2305where
2306    S: BuildHasher,
2307    Q: Hash + ?Sized,
2308{
2309    let mut hasher = s.build_hasher();
2310    k.hash(&mut hasher);
2311    hasher.finish()
2312}
2313
2314// We do not drop the key and value when a value is filtered from the map during the call to
2315// `retain`.  We need to be very careful not to have a live `HashMap` entry pointing to
2316// either a dangling `Node` or a `Node` with dropped keys / values.  Since the key and value
2317// types may panic on drop, they may short-circuit the entry in the map actually being
2318// removed.  Instead, we push the removed nodes onto the free list eagerly, then try and
2319// drop the keys and values for any newly freed nodes *after* `HashMap::retain` has
2320// completely finished.
2321struct DropFilteredValues<'a, K, V> {
2322    free: &'a mut Option<NonNull<Node<K, V>>>,
2323    cur_free: Option<NonNull<Node<K, V>>>,
2324}
2325
2326impl<K, V> DropFilteredValues<'_, K, V> {
2327    #[inline]
2328    fn drop_later(&mut self, node: NonNull<Node<K, V>>) {
2329        unsafe {
2330            detach_node(node);
2331            push_free(&mut self.cur_free, node);
2332        }
2333    }
2334}
2335
2336impl<K, V> Drop for DropFilteredValues<'_, K, V> {
2337    fn drop(&mut self) {
2338        unsafe {
2339            let end_free = self.cur_free;
2340            while self.cur_free != *self.free {
2341                let cur_free = self.cur_free.as_ptr();
2342                (*cur_free).take_entry();
2343                self.cur_free = (*cur_free).links.free.next;
2344            }
2345            *self.free = end_free;
2346        }
2347    }
2348}