Skip to main content

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