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
976pub struct RawEntryBuilderMut<'a, K, V, S> {
977    map: &'a mut LinkedHashMap<K, V, S>,
978}
979
980impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
981where
982    S: BuildHasher,
983{
984    #[inline]
985    pub fn from_key<Q>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
986    where
987        K: Borrow<Q>,
988        Q: Hash + Eq + ?Sized,
989    {
990        let hash = hash_key(&self.map.hash_builder, k);
991        self.from_key_hashed_nocheck(hash, k)
992    }
993
994    #[inline]
995    pub fn from_key_hashed_nocheck<Q>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
996    where
997        K: Borrow<Q>,
998        Q: Hash + Eq + ?Sized,
999    {
1000        self.from_hash(hash, move |o| k.eq(o.borrow()))
1001    }
1002
1003    #[inline]
1004    pub fn from_hash(
1005        self,
1006        hash: u64,
1007        mut is_match: impl FnMut(&K) -> bool,
1008    ) -> RawEntryMut<'a, K, V, S> {
1009        let entry = self
1010            .map
1011            .table
1012            .find_entry(hash, move |k| is_match(unsafe { (*k).as_ref().key_ref() }));
1013
1014        match entry {
1015            Ok(occupied) => RawEntryMut::Occupied(RawOccupiedEntryMut {
1016                hash_builder: &self.map.hash_builder,
1017                free: &mut self.map.free,
1018                values: &mut self.map.values,
1019                entry: occupied,
1020            }),
1021            Err(absent) => RawEntryMut::Vacant(RawVacantEntryMut {
1022                hash_builder: &self.map.hash_builder,
1023                values: &mut self.map.values,
1024                free: &mut self.map.free,
1025                entry: absent,
1026            }),
1027        }
1028    }
1029}
1030
1031pub enum RawEntryMut<'a, K, V, S> {
1032    Occupied(RawOccupiedEntryMut<'a, K, V, S>),
1033    Vacant(RawVacantEntryMut<'a, K, V, S>),
1034}
1035
1036impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1037    /// Similarly to `Entry::or_insert`, if this entry is occupied, it will move the existing entry
1038    /// to the back of the internal linked list.
1039    #[inline]
1040    pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1041    where
1042        K: Hash,
1043        S: BuildHasher,
1044    {
1045        match self {
1046            RawEntryMut::Occupied(mut entry) => {
1047                entry.to_back();
1048                entry.into_key_value()
1049            }
1050            RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1051        }
1052    }
1053
1054    /// Similarly to `Entry::or_insert_with`, if this entry is occupied, it will move the existing
1055    /// entry to the back of the internal linked list.
1056    #[inline]
1057    pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1058    where
1059        F: FnOnce() -> (K, V),
1060        K: Hash,
1061        S: BuildHasher,
1062    {
1063        match self {
1064            RawEntryMut::Occupied(mut entry) => {
1065                entry.to_back();
1066                entry.into_key_value()
1067            }
1068            RawEntryMut::Vacant(entry) => {
1069                let (k, v) = default();
1070                entry.insert(k, v)
1071            }
1072        }
1073    }
1074
1075    #[inline]
1076    pub fn and_modify<F>(self, f: F) -> Self
1077    where
1078        F: FnOnce(&mut K, &mut V),
1079    {
1080        match self {
1081            RawEntryMut::Occupied(mut entry) => {
1082                {
1083                    let (k, v) = entry.get_key_value_mut();
1084                    f(k, v);
1085                }
1086                RawEntryMut::Occupied(entry)
1087            }
1088            RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1089        }
1090    }
1091}
1092
1093pub struct RawOccupiedEntryMut<'a, K, V, S> {
1094    hash_builder: &'a S,
1095    free: &'a mut Option<NonNull<Node<K, V>>>,
1096    values: &'a mut Option<NonNull<Node<K, V>>>,
1097    entry: hash_table::OccupiedEntry<'a, NonNull<Node<K, V>>>,
1098}
1099
1100impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
1101    #[inline]
1102    pub fn key(&self) -> &K {
1103        self.get_key_value().0
1104    }
1105
1106    #[inline]
1107    pub fn key_mut(&mut self) -> &mut K {
1108        self.get_key_value_mut().0
1109    }
1110
1111    #[inline]
1112    pub fn into_key(self) -> &'a mut K {
1113        self.into_key_value().0
1114    }
1115
1116    #[inline]
1117    pub fn get(&self) -> &V {
1118        self.get_key_value().1
1119    }
1120
1121    #[inline]
1122    pub fn get_mut(&mut self) -> &mut V {
1123        self.get_key_value_mut().1
1124    }
1125
1126    #[inline]
1127    pub fn into_mut(self) -> &'a mut V {
1128        self.into_key_value().1
1129    }
1130
1131    #[inline]
1132    pub fn get_key_value(&self) -> (&K, &V) {
1133        unsafe {
1134            let node = *self.entry.get();
1135            let (key, value) = (*node.as_ptr()).entry_ref();
1136            (key, value)
1137        }
1138    }
1139
1140    #[inline]
1141    pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1142        unsafe {
1143            let node = *self.entry.get_mut();
1144            let (key, value) = (*node.as_ptr()).entry_mut();
1145            (key, value)
1146        }
1147    }
1148
1149    #[inline]
1150    pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1151        unsafe {
1152            let node = *self.entry.into_mut();
1153            let (key, value) = (*node.as_ptr()).entry_mut();
1154            (key, value)
1155        }
1156    }
1157
1158    #[inline]
1159    pub fn to_back(&mut self) {
1160        unsafe {
1161            let node = *self.entry.get_mut();
1162            detach_node(node);
1163            attach_before(node, NonNull::new_unchecked(self.values.as_ptr()));
1164        }
1165    }
1166
1167    #[inline]
1168    pub fn to_front(&mut self) {
1169        unsafe {
1170            let node = *self.entry.get_mut();
1171            detach_node(node);
1172            attach_before(node, (*self.values.as_ptr()).links.value.next);
1173        }
1174    }
1175
1176    #[inline]
1177    pub fn replace_value(&mut self, value: V) -> V {
1178        unsafe {
1179            let mut node = *self.entry.get_mut();
1180            mem::replace(&mut node.as_mut().entry_mut().1, value)
1181        }
1182    }
1183
1184    #[inline]
1185    pub fn replace_key(&mut self, key: K) -> K {
1186        unsafe {
1187            let mut node = *self.entry.get_mut();
1188            mem::replace(&mut node.as_mut().entry_mut().0, key)
1189        }
1190    }
1191
1192    #[inline]
1193    pub fn remove(self) -> V {
1194        self.remove_entry().1
1195    }
1196
1197    #[inline]
1198    pub fn remove_entry(self) -> (K, V) {
1199        let node = self.entry.remove().0;
1200        unsafe { remove_node(self.free, node) }
1201    }
1202
1203    /// Returns a `CursorMut` over the current entry.
1204    #[inline]
1205    pub fn cursor_mut(self) -> CursorMut<'a, K, V, S>
1206    where
1207        K: Eq + Hash,
1208        S: BuildHasher,
1209    {
1210        CursorMut {
1211            cur: self.entry.get().as_ptr(),
1212            hash_builder: self.hash_builder,
1213            free: self.free,
1214            values: self.values,
1215            table: self.entry.into_table(),
1216        }
1217    }
1218}
1219
1220pub struct RawVacantEntryMut<'a, K, V, S> {
1221    hash_builder: &'a S,
1222    values: &'a mut Option<NonNull<Node<K, V>>>,
1223    free: &'a mut Option<NonNull<Node<K, V>>>,
1224    entry: hash_table::AbsentEntry<'a, NonNull<Node<K, V>>>,
1225}
1226
1227impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1228    #[inline]
1229    pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1230    where
1231        K: Hash,
1232        S: BuildHasher,
1233    {
1234        let hash = hash_key(self.hash_builder, &key);
1235        self.insert_hashed_nocheck(hash, key, value)
1236    }
1237
1238    #[inline]
1239    pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1240    where
1241        K: Hash,
1242        S: BuildHasher,
1243    {
1244        let hash_builder = self.hash_builder;
1245        self.insert_with_hasher(hash, key, value, |k| hash_key(hash_builder, k))
1246    }
1247
1248    #[inline]
1249    pub fn insert_with_hasher(
1250        self,
1251        hash: u64,
1252        key: K,
1253        value: V,
1254        hasher: impl Fn(&K) -> u64,
1255    ) -> (&'a mut K, &'a mut V)
1256    where
1257        S: BuildHasher,
1258    {
1259        unsafe {
1260            ensure_guard_node(self.values);
1261            let mut new_node = allocate_node(self.free);
1262            new_node.as_mut().put_entry((key, value));
1263            attach_before(new_node, NonNull::new_unchecked(self.values.as_ptr()));
1264
1265            let node = self
1266                .entry
1267                .into_table()
1268                .insert_unique(hash, new_node, move |k| hasher((*k).as_ref().key_ref()))
1269                .into_mut();
1270
1271            let (key, value) = (*node.as_ptr()).entry_mut();
1272            (key, value)
1273        }
1274    }
1275}
1276
1277impl<K, V, S> fmt::Debug for RawEntryBuilderMut<'_, K, V, S> {
1278    #[inline]
1279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1280        f.debug_struct("RawEntryBuilder").finish()
1281    }
1282}
1283
1284impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for RawEntryMut<'_, K, V, S> {
1285    #[inline]
1286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1287        match *self {
1288            RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1289            RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1290        }
1291    }
1292}
1293
1294impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for RawOccupiedEntryMut<'_, K, V, S> {
1295    #[inline]
1296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1297        f.debug_struct("RawOccupiedEntryMut")
1298            .field("key", self.key())
1299            .field("value", self.get())
1300            .finish()
1301    }
1302}
1303
1304impl<K, V, S> fmt::Debug for RawVacantEntryMut<'_, K, V, S> {
1305    #[inline]
1306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1307        f.debug_struct("RawVacantEntryMut").finish()
1308    }
1309}
1310
1311impl<K, V, S> fmt::Debug for RawEntryBuilder<'_, K, V, S> {
1312    #[inline]
1313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1314        f.debug_struct("RawEntryBuilder").finish()
1315    }
1316}
1317
1318unsafe impl<K, V, S> Send for RawOccupiedEntryMut<'_, K, V, S>
1319where
1320    K: Send,
1321    V: Send,
1322    S: Send,
1323{
1324}
1325
1326unsafe impl<K, V, S> Sync for RawOccupiedEntryMut<'_, K, V, S>
1327where
1328    K: Sync,
1329    V: Sync,
1330    S: Sync,
1331{
1332}
1333
1334unsafe impl<K, V, S> Send for RawVacantEntryMut<'_, K, V, S>
1335where
1336    K: Send,
1337    V: Send,
1338    S: Send,
1339{
1340}
1341
1342unsafe impl<K, V, S> Sync for RawVacantEntryMut<'_, K, V, S>
1343where
1344    K: Sync,
1345    V: Sync,
1346    S: Sync,
1347{
1348}
1349
1350pub struct Iter<'a, K, V> {
1351    head: *const Node<K, V>,
1352    tail: *const Node<K, V>,
1353    remaining: usize,
1354    marker: PhantomData<(&'a K, &'a V)>,
1355}
1356
1357pub struct IterMut<'a, K, V> {
1358    head: Option<NonNull<Node<K, V>>>,
1359    tail: Option<NonNull<Node<K, V>>>,
1360    remaining: usize,
1361    marker: PhantomData<(&'a K, &'a mut V)>,
1362}
1363
1364pub struct IntoIter<K, V> {
1365    head: Option<NonNull<Node<K, V>>>,
1366    tail: Option<NonNull<Node<K, V>>>,
1367    remaining: usize,
1368    marker: PhantomData<(K, V)>,
1369}
1370
1371pub struct Drain<'a, K, V> {
1372    free: NonNull<Option<NonNull<Node<K, V>>>>,
1373    head: Option<NonNull<Node<K, V>>>,
1374    tail: Option<NonNull<Node<K, V>>>,
1375    remaining: usize,
1376    // We want `Drain` to be covariant
1377    marker: PhantomData<(K, V, &'a LinkedHashMap<K, V>)>,
1378}
1379
1380impl<K, V> IterMut<'_, K, V> {
1381    #[inline]
1382    pub(crate) fn iter(&self) -> Iter<'_, K, V> {
1383        Iter {
1384            head: self.head.as_ptr(),
1385            tail: self.tail.as_ptr(),
1386            remaining: self.remaining,
1387            marker: PhantomData,
1388        }
1389    }
1390}
1391
1392impl<K, V> IntoIter<K, V> {
1393    #[inline]
1394    pub(crate) fn iter(&self) -> Iter<'_, K, V> {
1395        Iter {
1396            head: self.head.as_ptr(),
1397            tail: self.tail.as_ptr(),
1398            remaining: self.remaining,
1399            marker: PhantomData,
1400        }
1401    }
1402}
1403
1404impl<K, V> Drain<'_, K, V> {
1405    #[inline]
1406    pub(crate) fn iter(&self) -> Iter<'_, K, V> {
1407        Iter {
1408            head: self.head.as_ptr(),
1409            tail: self.tail.as_ptr(),
1410            remaining: self.remaining,
1411            marker: PhantomData,
1412        }
1413    }
1414}
1415
1416unsafe impl<K, V> Send for Iter<'_, K, V>
1417where
1418    K: Sync,
1419    V: Sync,
1420{
1421}
1422
1423unsafe impl<K, V> Send for IterMut<'_, K, V>
1424where
1425    K: Send,
1426    V: Send,
1427{
1428}
1429
1430unsafe impl<K, V> Send for IntoIter<K, V>
1431where
1432    K: Send,
1433    V: Send,
1434{
1435}
1436
1437unsafe impl<K, V> Send for Drain<'_, K, V>
1438where
1439    K: Send,
1440    V: Send,
1441{
1442}
1443
1444unsafe impl<K, V> Sync for Iter<'_, K, V>
1445where
1446    K: Sync,
1447    V: Sync,
1448{
1449}
1450
1451unsafe impl<K, V> Sync for IterMut<'_, K, V>
1452where
1453    K: Sync,
1454    V: Sync,
1455{
1456}
1457
1458unsafe impl<K, V> Sync for IntoIter<K, V>
1459where
1460    K: Sync,
1461    V: Sync,
1462{
1463}
1464
1465unsafe impl<K, V> Sync for Drain<'_, K, V>
1466where
1467    K: Sync,
1468    V: Sync,
1469{
1470}
1471
1472impl<K, V> Clone for Iter<'_, K, V> {
1473    #[inline]
1474    fn clone(&self) -> Self {
1475        Iter { ..*self }
1476    }
1477}
1478
1479impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
1480    #[inline]
1481    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1482        f.debug_list().entries(self.clone()).finish()
1483    }
1484}
1485
1486impl<K, V> fmt::Debug for IterMut<'_, K, V>
1487where
1488    K: fmt::Debug,
1489    V: fmt::Debug,
1490{
1491    #[inline]
1492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1493        f.debug_list().entries(self.iter()).finish()
1494    }
1495}
1496
1497impl<K, V> fmt::Debug for IntoIter<K, V>
1498where
1499    K: fmt::Debug,
1500    V: fmt::Debug,
1501{
1502    #[inline]
1503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1504        f.debug_list().entries(self.iter()).finish()
1505    }
1506}
1507
1508impl<K, V> fmt::Debug for Drain<'_, K, V>
1509where
1510    K: fmt::Debug,
1511    V: fmt::Debug,
1512{
1513    #[inline]
1514    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1515        f.debug_list().entries(self.iter()).finish()
1516    }
1517}
1518
1519impl<'a, K, V> Iterator for Iter<'a, K, V> {
1520    type Item = (&'a K, &'a V);
1521
1522    #[inline]
1523    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1524        if self.remaining == 0 {
1525            None
1526        } else {
1527            self.remaining -= 1;
1528            unsafe {
1529                let (key, value) = (*self.head).entry_ref();
1530                self.head = (*self.head).links.value.next.as_ptr();
1531                Some((key, value))
1532            }
1533        }
1534    }
1535
1536    #[inline]
1537    fn size_hint(&self) -> (usize, Option<usize>) {
1538        (self.remaining, Some(self.remaining))
1539    }
1540}
1541
1542impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1543    type Item = (&'a K, &'a mut V);
1544
1545    #[inline]
1546    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1547        if self.remaining == 0 {
1548            None
1549        } else {
1550            self.remaining -= 1;
1551            unsafe {
1552                let head = self.head.as_ptr();
1553                let (key, value) = (*head).entry_mut();
1554                self.head = Some((*head).links.value.next);
1555                Some((key, value))
1556            }
1557        }
1558    }
1559
1560    #[inline]
1561    fn size_hint(&self) -> (usize, Option<usize>) {
1562        (self.remaining, Some(self.remaining))
1563    }
1564}
1565
1566impl<K, V> Iterator for IntoIter<K, V> {
1567    type Item = (K, V);
1568
1569    #[inline]
1570    fn next(&mut self) -> Option<(K, V)> {
1571        if self.remaining == 0 {
1572            return None;
1573        }
1574        self.remaining -= 1;
1575        unsafe {
1576            let head = self.head.as_ptr();
1577            self.head = Some((*head).links.value.next);
1578            let mut e = Box::from_raw(head);
1579            Some(e.take_entry())
1580        }
1581    }
1582
1583    #[inline]
1584    fn size_hint(&self) -> (usize, Option<usize>) {
1585        (self.remaining, Some(self.remaining))
1586    }
1587}
1588
1589impl<K, V> Iterator for Drain<'_, K, V> {
1590    type Item = (K, V);
1591
1592    #[inline]
1593    fn next(&mut self) -> Option<(K, V)> {
1594        if self.remaining == 0 {
1595            return None;
1596        }
1597        self.remaining -= 1;
1598        unsafe {
1599            let mut head = NonNull::new_unchecked(self.head.as_ptr());
1600            self.head = Some(head.as_ref().links.value.next);
1601            let entry = head.as_mut().take_entry();
1602            push_free(self.free.as_mut(), head);
1603            Some(entry)
1604        }
1605    }
1606
1607    #[inline]
1608    fn size_hint(&self) -> (usize, Option<usize>) {
1609        (self.remaining, Some(self.remaining))
1610    }
1611}
1612
1613impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1614    #[inline]
1615    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1616        if self.remaining == 0 {
1617            None
1618        } else {
1619            self.remaining -= 1;
1620            unsafe {
1621                let tail = self.tail;
1622                self.tail = (*tail).links.value.prev.as_ptr();
1623                let (key, value) = (*tail).entry_ref();
1624                Some((key, value))
1625            }
1626        }
1627    }
1628}
1629
1630impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1631    #[inline]
1632    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1633        if self.remaining == 0 {
1634            None
1635        } else {
1636            self.remaining -= 1;
1637            unsafe {
1638                let tail = self.tail.as_ptr();
1639                self.tail = Some((*tail).links.value.prev);
1640                let (key, value) = (*tail).entry_mut();
1641                Some((key, value))
1642            }
1643        }
1644    }
1645}
1646
1647impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1648    #[inline]
1649    fn next_back(&mut self) -> Option<(K, V)> {
1650        if self.remaining == 0 {
1651            return None;
1652        }
1653        self.remaining -= 1;
1654        unsafe {
1655            let mut e = *Box::from_raw(self.tail.as_ptr());
1656            self.tail = Some(e.links.value.prev);
1657            Some(e.take_entry())
1658        }
1659    }
1660}
1661
1662impl<K, V> DoubleEndedIterator for Drain<'_, K, V> {
1663    #[inline]
1664    fn next_back(&mut self) -> Option<(K, V)> {
1665        if self.remaining == 0 {
1666            return None;
1667        }
1668        self.remaining -= 1;
1669        unsafe {
1670            let mut tail = NonNull::new_unchecked(self.tail.as_ptr());
1671            self.tail = Some(tail.as_ref().links.value.prev);
1672            let entry = tail.as_mut().take_entry();
1673            push_free(&mut *self.free.as_ptr(), tail);
1674            Some(entry)
1675        }
1676    }
1677}
1678
1679impl<K, V> ExactSizeIterator for Iter<'_, K, V> {}
1680
1681impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {}
1682
1683impl<K, V> ExactSizeIterator for IntoIter<K, V> {}
1684
1685impl<K, V> Drop for IntoIter<K, V> {
1686    #[inline]
1687    fn drop(&mut self) {
1688        for _ in 0..self.remaining {
1689            unsafe {
1690                let tail = self.tail.as_ptr();
1691                self.tail = Some((*tail).links.value.prev);
1692                (*tail).take_entry();
1693                let _ = Box::from_raw(tail);
1694            }
1695        }
1696    }
1697}
1698
1699impl<K, V> Drop for Drain<'_, K, V> {
1700    #[inline]
1701    fn drop(&mut self) {
1702        for _ in 0..self.remaining {
1703            unsafe {
1704                let mut tail = NonNull::new_unchecked(self.tail.as_ptr());
1705                self.tail = Some(tail.as_ref().links.value.prev);
1706                tail.as_mut().take_entry();
1707                push_free(&mut *self.free.as_ptr(), tail);
1708            }
1709        }
1710    }
1711}
1712
1713/// The `CursorMut` struct and its implementation provide the basic mutable Cursor API for Linked
1714/// lists as proposed in
1715/// [here](https://github.com/rust-lang/rfcs/blob/master/text/2570-linked-list-cursors.md), with
1716/// several exceptions:
1717///
1718/// - It behaves similarly to Rust's Iterators, returning `None` when the end of the list is
1719///   reached. A _guard_ node is positioned between the head and tail of the linked list to
1720///   facilitate this. If the cursor is over this guard node, `None` is returned, signaling the end
1721///   or start of the list. From this position, the cursor can move in either direction as the
1722///   linked list is circular, with the guard node connecting the two ends.
1723/// - The current implementation does not include an `index` method, as it does not track the index
1724///   of its elements. It provides access to each map entry as a tuple of `(&K, &mut V)`.
1725///
1726pub struct CursorMut<'a, K, V, S> {
1727    cur: *mut Node<K, V>,
1728    hash_builder: &'a S,
1729    free: &'a mut Option<NonNull<Node<K, V>>>,
1730    values: &'a mut Option<NonNull<Node<K, V>>>,
1731    table: &'a mut hashbrown::HashTable<NonNull<Node<K, V>>>,
1732}
1733
1734impl<K, V, S> CursorMut<'_, K, V, S> {
1735    /// Returns an `Option` of the current element in the list, provided it is not the
1736    /// _guard_ node, and `None` overwise.
1737    #[inline]
1738    pub fn current(&mut self) -> Option<(&K, &mut V)> {
1739        unsafe {
1740            let at = NonNull::new_unchecked(self.cur);
1741            self.peek(at)
1742        }
1743    }
1744
1745    /// Retrieves the next element in the list (moving towards the end).
1746    #[inline]
1747    pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
1748        unsafe {
1749            let at = (*self.cur).links.value.next;
1750            self.peek(at)
1751        }
1752    }
1753
1754    /// Retrieves the previous element in the list (moving towards the front).
1755    #[inline]
1756    pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
1757        unsafe {
1758            let at = (*self.cur).links.value.prev;
1759            self.peek(at)
1760        }
1761    }
1762
1763    // Retrieves the element without advancing current position to it.
1764    #[inline]
1765    fn peek(&mut self, at: NonNull<Node<K, V>>) -> Option<(&K, &mut V)> {
1766        if let Some(values) = self.values {
1767            unsafe {
1768                let node = at.as_ptr();
1769                if node == values.as_ptr() {
1770                    None
1771                } else {
1772                    let entry = (*node).entry_mut();
1773                    Some((&entry.0, &mut entry.1))
1774                }
1775            }
1776        } else {
1777            None
1778        }
1779    }
1780
1781    /// Updates the pointer to the current element to the next element in the
1782    /// list (that is, moving towards the end).
1783    #[inline]
1784    pub fn move_next(&mut self) {
1785        let at = unsafe { (*self.cur).links.value.next };
1786        self.muv(at);
1787    }
1788
1789    /// Updates the pointer to the current element to the previous element in the
1790    /// list (that is, moving towards the front).
1791    #[inline]
1792    pub fn move_prev(&mut self) {
1793        let at = unsafe { (*self.cur).links.value.prev };
1794        self.muv(at);
1795    }
1796
1797    // Updates the pointer to the current element to the one returned by the at closure function.
1798    #[inline]
1799    fn muv(&mut self, at: NonNull<Node<K, V>>) {
1800        self.cur = at.as_ptr();
1801    }
1802
1803    /// Inserts the provided key and value before the current element. It checks if an entry
1804    /// with the given key exists and, if so, replaces its value with the provided `key`
1805    /// parameter. The key is not updated; this matters for types that can be `==` without
1806    /// being identical.
1807    ///
1808    /// If the entry doesn't exist, it creates a new one. If a value has been updated, the
1809    /// function returns the *old* value wrapped with `Some`  and `None` otherwise.
1810    #[inline]
1811    pub fn insert_before(&mut self, key: K, value: V) -> Option<V>
1812    where
1813        K: Eq + Hash,
1814        S: BuildHasher,
1815    {
1816        let before = unsafe { NonNull::new_unchecked(self.cur) };
1817        self.insert(key, value, before)
1818    }
1819
1820    /// Inserts the provided key and value after the current element. It checks if an entry
1821    /// with the given key exists and, if so, replaces its value with the provided `key`
1822    /// parameter. The key is not updated; this matters for types that can be `==` without
1823    /// being identical.
1824    ///
1825    /// If the entry doesn't exist, it creates a new one. If a value has been updated, the
1826    /// function returns the *old* value wrapped with `Some`  and `None` otherwise.
1827    #[inline]
1828    pub fn insert_after(&mut self, key: K, value: V) -> Option<V>
1829    where
1830        K: Eq + Hash,
1831        S: BuildHasher,
1832    {
1833        let before = unsafe { (*self.cur).links.value.next };
1834        self.insert(key, value, before)
1835    }
1836
1837    // Inserts an element immediately before the given `before` node.
1838    #[inline]
1839    fn insert(&mut self, key: K, value: V, before: NonNull<Node<K, V>>) -> Option<V>
1840    where
1841        K: Eq + Hash,
1842        S: BuildHasher,
1843    {
1844        unsafe {
1845            let hash = hash_key(self.hash_builder, &key);
1846            let i_entry = self
1847                .table
1848                .find_entry(hash, |o| (*o).as_ref().key_ref().eq(&key));
1849
1850            match i_entry {
1851                Ok(occupied) => {
1852                    let mut node = *occupied.into_mut();
1853                    let pv = mem::replace(&mut node.as_mut().entry_mut().1, value);
1854                    if node != before {
1855                        detach_node(node);
1856                        attach_before(node, before);
1857                    }
1858                    Some(pv)
1859                }
1860                Err(_) => {
1861                    let mut new_node = allocate_node(self.free);
1862                    new_node.as_mut().put_entry((key, value));
1863                    attach_before(new_node, before);
1864                    let hash_builder = self.hash_builder;
1865                    self.table.insert_unique(hash, new_node, move |k| {
1866                        hash_key(hash_builder, (*k).as_ref().key_ref())
1867                    });
1868                    None
1869                }
1870            }
1871        }
1872    }
1873}
1874
1875pub struct Keys<'a, K, V> {
1876    inner: Iter<'a, K, V>,
1877}
1878
1879impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
1880    #[inline]
1881    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1882        f.debug_list().entries(self.clone()).finish()
1883    }
1884}
1885
1886impl<'a, K, V> Clone for Keys<'a, K, V> {
1887    #[inline]
1888    fn clone(&self) -> Keys<'a, K, V> {
1889        Keys {
1890            inner: self.inner.clone(),
1891        }
1892    }
1893}
1894
1895impl<'a, K, V> Iterator for Keys<'a, K, V> {
1896    type Item = &'a K;
1897
1898    #[inline]
1899    fn next(&mut self) -> Option<&'a K> {
1900        self.inner.next().map(|e| e.0)
1901    }
1902
1903    #[inline]
1904    fn size_hint(&self) -> (usize, Option<usize>) {
1905        self.inner.size_hint()
1906    }
1907}
1908
1909impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1910    #[inline]
1911    fn next_back(&mut self) -> Option<&'a K> {
1912        self.inner.next_back().map(|e| e.0)
1913    }
1914}
1915
1916impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1917    #[inline]
1918    fn len(&self) -> usize {
1919        self.inner.len()
1920    }
1921}
1922
1923pub struct Values<'a, K, V> {
1924    inner: Iter<'a, K, V>,
1925}
1926
1927impl<K, V> Clone for Values<'_, K, V> {
1928    #[inline]
1929    fn clone(&self) -> Self {
1930        Values {
1931            inner: self.inner.clone(),
1932        }
1933    }
1934}
1935
1936impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
1937    #[inline]
1938    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1939        f.debug_list().entries(self.clone()).finish()
1940    }
1941}
1942
1943impl<'a, K, V> Iterator for Values<'a, K, V> {
1944    type Item = &'a V;
1945
1946    #[inline]
1947    fn next(&mut self) -> Option<&'a V> {
1948        self.inner.next().map(|e| e.1)
1949    }
1950
1951    #[inline]
1952    fn size_hint(&self) -> (usize, Option<usize>) {
1953        self.inner.size_hint()
1954    }
1955}
1956
1957impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1958    #[inline]
1959    fn next_back(&mut self) -> Option<&'a V> {
1960        self.inner.next_back().map(|e| e.1)
1961    }
1962}
1963
1964impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1965    #[inline]
1966    fn len(&self) -> usize {
1967        self.inner.len()
1968    }
1969}
1970
1971pub struct ValuesMut<'a, K, V> {
1972    inner: IterMut<'a, K, V>,
1973}
1974
1975impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
1976where
1977    K: fmt::Debug,
1978    V: fmt::Debug,
1979{
1980    #[inline]
1981    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1982        f.debug_list().entries(self.inner.iter()).finish()
1983    }
1984}
1985
1986impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1987    type Item = &'a mut V;
1988
1989    #[inline]
1990    fn next(&mut self) -> Option<&'a mut V> {
1991        self.inner.next().map(|e| e.1)
1992    }
1993
1994    #[inline]
1995    fn size_hint(&self) -> (usize, Option<usize>) {
1996        self.inner.size_hint()
1997    }
1998}
1999
2000impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2001    #[inline]
2002    fn next_back(&mut self) -> Option<&'a mut V> {
2003        self.inner.next_back().map(|e| e.1)
2004    }
2005}
2006
2007impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2008    #[inline]
2009    fn len(&self) -> usize {
2010        self.inner.len()
2011    }
2012}
2013
2014impl<'a, K, V, S> IntoIterator for &'a LinkedHashMap<K, V, S> {
2015    type Item = (&'a K, &'a V);
2016    type IntoIter = Iter<'a, K, V>;
2017
2018    #[inline]
2019    fn into_iter(self) -> Iter<'a, K, V> {
2020        self.iter()
2021    }
2022}
2023
2024impl<'a, K, V, S> IntoIterator for &'a mut LinkedHashMap<K, V, S> {
2025    type Item = (&'a K, &'a mut V);
2026    type IntoIter = IterMut<'a, K, V>;
2027
2028    #[inline]
2029    fn into_iter(self) -> IterMut<'a, K, V> {
2030        self.iter_mut()
2031    }
2032}
2033
2034impl<K, V, S> IntoIterator for LinkedHashMap<K, V, S> {
2035    type Item = (K, V);
2036    type IntoIter = IntoIter<K, V>;
2037
2038    #[inline]
2039    fn into_iter(mut self) -> IntoIter<K, V> {
2040        unsafe {
2041            let (head, tail) = if let Some(values) = self.values {
2042                let ValueLinks {
2043                    next: head,
2044                    prev: tail,
2045                } = values.as_ref().links.value;
2046
2047                let _ = Box::from_raw(self.values.as_ptr());
2048                self.values = None;
2049
2050                (Some(head), Some(tail))
2051            } else {
2052                (None, None)
2053            };
2054            let len = self.len();
2055
2056            drop_free_nodes(self.free.take());
2057
2058            self.table.clear();
2059
2060            IntoIter {
2061                head,
2062                tail,
2063                remaining: len,
2064                marker: PhantomData,
2065            }
2066        }
2067    }
2068}
2069
2070struct ValueLinks<K, V> {
2071    next: NonNull<Node<K, V>>,
2072    prev: NonNull<Node<K, V>>,
2073}
2074
2075impl<K, V> Clone for ValueLinks<K, V> {
2076    #[inline]
2077    fn clone(&self) -> Self {
2078        *self
2079    }
2080}
2081
2082impl<K, V> Copy for ValueLinks<K, V> {}
2083
2084struct FreeLink<K, V> {
2085    next: Option<NonNull<Node<K, V>>>,
2086}
2087
2088impl<K, V> Clone for FreeLink<K, V> {
2089    #[inline]
2090    fn clone(&self) -> Self {
2091        *self
2092    }
2093}
2094
2095impl<K, V> Copy for FreeLink<K, V> {}
2096
2097union Links<K, V> {
2098    value: ValueLinks<K, V>,
2099    free: FreeLink<K, V>,
2100}
2101
2102struct Node<K, V> {
2103    entry: MaybeUninit<(K, V)>,
2104    links: Links<K, V>,
2105}
2106
2107impl<K, V> Node<K, V> {
2108    #[inline]
2109    unsafe fn put_entry(&mut self, entry: (K, V)) {
2110        self.entry.as_mut_ptr().write(entry)
2111    }
2112
2113    #[inline]
2114    unsafe fn entry_ref(&self) -> &(K, V) {
2115        &*self.entry.as_ptr()
2116    }
2117
2118    #[inline]
2119    unsafe fn key_ref(&self) -> &K {
2120        &(*self.entry.as_ptr()).0
2121    }
2122
2123    #[inline]
2124    unsafe fn entry_mut(&mut self) -> &mut (K, V) {
2125        &mut *self.entry.as_mut_ptr()
2126    }
2127
2128    #[inline]
2129    unsafe fn take_entry(&mut self) -> (K, V) {
2130        self.entry.as_ptr().read()
2131    }
2132}
2133
2134trait OptNonNullExt<T> {
2135    #[allow(clippy::wrong_self_convention)]
2136    fn as_ptr(self) -> *mut T;
2137}
2138
2139impl<T> OptNonNullExt<T> for Option<NonNull<T>> {
2140    #[inline]
2141    fn as_ptr(self) -> *mut T {
2142        match self {
2143            Some(ptr) => ptr.as_ptr(),
2144            None => ptr::null_mut(),
2145        }
2146    }
2147}
2148
2149// Allocate a circular list guard node if not present.
2150#[inline]
2151unsafe fn ensure_guard_node<K, V>(head: &mut Option<NonNull<Node<K, V>>>) {
2152    if head.is_none() {
2153        let mut p = NonNull::new_unchecked(Box::into_raw(Box::new(Node {
2154            entry: MaybeUninit::uninit(),
2155            links: Links {
2156                value: ValueLinks {
2157                    next: NonNull::dangling(),
2158                    prev: NonNull::dangling(),
2159                },
2160            },
2161        })));
2162        p.as_mut().links.value = ValueLinks { next: p, prev: p };
2163        *head = Some(p);
2164    }
2165}
2166
2167// Attach the `to_attach` node to the existing circular list *before* `node`.
2168#[inline]
2169unsafe fn attach_before<K, V>(mut to_attach: NonNull<Node<K, V>>, mut node: NonNull<Node<K, V>>) {
2170    to_attach.as_mut().links.value = ValueLinks {
2171        prev: node.as_ref().links.value.prev,
2172        next: node,
2173    };
2174    node.as_mut().links.value.prev = to_attach;
2175    (*to_attach.as_mut().links.value.prev.as_ptr())
2176        .links
2177        .value
2178        .next = to_attach;
2179}
2180
2181#[inline]
2182unsafe fn detach_node<K, V>(mut node: NonNull<Node<K, V>>) {
2183    node.as_mut().links.value.prev.as_mut().links.value.next = node.as_ref().links.value.next;
2184    node.as_mut().links.value.next.as_mut().links.value.prev = node.as_ref().links.value.prev;
2185}
2186
2187#[inline]
2188unsafe fn push_free<K, V>(
2189    free_list: &mut Option<NonNull<Node<K, V>>>,
2190    mut node: NonNull<Node<K, V>>,
2191) {
2192    node.as_mut().links.free.next = *free_list;
2193    *free_list = Some(node);
2194}
2195
2196#[inline]
2197unsafe fn pop_free<K, V>(
2198    free_list: &mut Option<NonNull<Node<K, V>>>,
2199) -> Option<NonNull<Node<K, V>>> {
2200    if let Some(free) = *free_list {
2201        *free_list = free.as_ref().links.free.next;
2202        Some(free)
2203    } else {
2204        None
2205    }
2206}
2207
2208#[inline]
2209unsafe fn allocate_node<K, V>(free_list: &mut Option<NonNull<Node<K, V>>>) -> NonNull<Node<K, V>> {
2210    if let Some(mut free) = pop_free(free_list) {
2211        free.as_mut().links.value = ValueLinks {
2212            next: NonNull::dangling(),
2213            prev: NonNull::dangling(),
2214        };
2215        free
2216    } else {
2217        NonNull::new_unchecked(Box::into_raw(Box::new(Node {
2218            entry: MaybeUninit::uninit(),
2219            links: Links {
2220                value: ValueLinks {
2221                    next: NonNull::dangling(),
2222                    prev: NonNull::dangling(),
2223                },
2224            },
2225        })))
2226    }
2227}
2228
2229// Given node is assumed to be the guard node and is *not* dropped.
2230#[inline]
2231unsafe fn drop_value_nodes<K, V>(guard: NonNull<Node<K, V>>) {
2232    let mut cur = guard.as_ref().links.value.prev;
2233    while cur != guard {
2234        let prev = cur.as_ref().links.value.prev;
2235        cur.as_mut().take_entry();
2236        let _ = Box::from_raw(cur.as_ptr());
2237        cur = prev;
2238    }
2239}
2240
2241// Drops all linked free nodes starting with the given node.  Free nodes are only non-circular
2242// singly linked, and should have uninitialized keys / values.
2243#[inline]
2244unsafe fn drop_free_nodes<K, V>(mut free: Option<NonNull<Node<K, V>>>) {
2245    while let Some(some_free) = free {
2246        let next_free = some_free.as_ref().links.free.next;
2247        let _ = Box::from_raw(some_free.as_ptr());
2248        free = next_free;
2249    }
2250}
2251
2252#[inline]
2253unsafe fn remove_node<K, V>(
2254    free_list: &mut Option<NonNull<Node<K, V>>>,
2255    mut node: NonNull<Node<K, V>>,
2256) -> (K, V) {
2257    detach_node(node);
2258    push_free(free_list, node);
2259    node.as_mut().take_entry()
2260}
2261
2262#[inline]
2263unsafe fn hash_node<S, K, V>(s: &S, node: NonNull<Node<K, V>>) -> u64
2264where
2265    S: BuildHasher,
2266    K: Hash,
2267{
2268    hash_key(s, node.as_ref().key_ref())
2269}
2270
2271#[inline]
2272fn hash_key<S, Q>(s: &S, k: &Q) -> u64
2273where
2274    S: BuildHasher,
2275    Q: Hash + ?Sized,
2276{
2277    let mut hasher = s.build_hasher();
2278    k.hash(&mut hasher);
2279    hasher.finish()
2280}
2281
2282// We do not drop the key and value when a value is filtered from the map during the call to
2283// `retain`.  We need to be very careful not to have a live `HashMap` entry pointing to
2284// either a dangling `Node` or a `Node` with dropped keys / values.  Since the key and value
2285// types may panic on drop, they may short-circuit the entry in the map actually being
2286// removed.  Instead, we push the removed nodes onto the free list eagerly, then try and
2287// drop the keys and values for any newly freed nodes *after* `HashMap::retain` has
2288// completely finished.
2289struct DropFilteredValues<'a, K, V> {
2290    free: &'a mut Option<NonNull<Node<K, V>>>,
2291    cur_free: Option<NonNull<Node<K, V>>>,
2292}
2293
2294impl<K, V> DropFilteredValues<'_, K, V> {
2295    #[inline]
2296    fn drop_later(&mut self, node: NonNull<Node<K, V>>) {
2297        unsafe {
2298            detach_node(node);
2299            push_free(&mut self.cur_free, node);
2300        }
2301    }
2302}
2303
2304impl<K, V> Drop for DropFilteredValues<'_, K, V> {
2305    fn drop(&mut self) {
2306        unsafe {
2307            let end_free = self.cur_free;
2308            while self.cur_free != *self.free {
2309                let cur_free = self.cur_free.as_ptr();
2310                (*cur_free).take_entry();
2311                self.cur_free = (*cur_free).links.free.next;
2312            }
2313            *self.free = end_free;
2314        }
2315    }
2316}