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