Skip to main content

tether_map/linked_hash_map/
mod.rs

1//! Linked hash map implementation.
2//!
3//! This module provides the core [`LinkedHashMap`] type and related
4//! functionality. The linked hash map maintains relative order while providing
5//! O(1) access, insertion, and removal operations.
6//!
7//! # Examples
8//!
9//! ```
10//! use tether_map::linked_hash_map::LinkedHashMap;
11//!
12//! let mut map = LinkedHashMap::new();
13//! map.insert("first", 1);
14//! map.insert("second", 2);
15//!
16//! // Iteration preserves insertion order
17//! let entries: Vec<_> = map.iter().collect();
18//! assert_eq!(entries, [(&"first", &1), (&"second", &2)]);
19//! ```
20
21pub(crate) mod cursor;
22pub(crate) mod entry;
23pub(crate) mod iter;
24
25use alloc::vec::Vec;
26use core::borrow::Borrow;
27use core::clone::Clone;
28use core::cmp::Eq;
29use core::fmt::Debug;
30use core::hash::BuildHasher;
31use core::hash::Hash;
32use core::ops::Index;
33use core::ops::IndexMut;
34use core::panic;
35
36use hashbrown::Equivalent;
37use hashbrown::HashTable;
38use hashbrown::hash_table;
39
40use crate::Ptr;
41use crate::RandomState;
42use crate::arena::ActiveSlotRef;
43use crate::arena::Arena;
44use crate::arena::ArenaContainer;
45use crate::arena::FreedSlot;
46pub use crate::linked_hash_map::cursor::CursorMut;
47pub use crate::linked_hash_map::entry::Entry;
48pub use crate::linked_hash_map::entry::OccupiedEntry;
49pub use crate::linked_hash_map::entry::VacantEntry;
50pub use crate::linked_hash_map::iter::IntoIter;
51pub use crate::linked_hash_map::iter::Iter;
52pub use crate::linked_hash_map::iter::IterMut;
53pub use crate::linked_hash_map::iter::ValuesMut;
54
55pub(crate) struct HeadTail<K, T> {
56    head: ActiveSlotRef<K, T>,
57    tail: ActiveSlotRef<K, T>,
58}
59
60impl<K, T> Debug for HeadTail<K, T> {
61    fn fmt(
62        &self,
63        f: &mut core::fmt::Formatter<'_>,
64    ) -> core::fmt::Result {
65        f.debug_struct("HeadTail")
66            .field("head", &self.head)
67            .field("tail", &self.tail)
68            .finish()
69    }
70}
71
72impl<K, T> PartialEq for HeadTail<K, T> {
73    fn eq(
74        &self,
75        other: &Self,
76    ) -> bool {
77        self.head == other.head && self.tail == other.tail
78    }
79}
80
81impl<K, T> Eq for HeadTail<K, T> {}
82
83/// A hash map that maintains relative order using a doubly-linked list.
84///
85/// This data structure combines the O(1) lookup performance of a hash table
86/// with the ability to iterate over entries in relative order. It supports
87/// arbitrary key-value pairs where keys implement `Hash + Eq`.
88///
89/// The generic parameters are:
90/// - `K`: Key type, must implement `Hash + Eq`
91/// - `T`: Value type
92/// - `S`: Hash builder type, defaults to the standard hasher
93///
94/// # Examples
95///
96/// ```
97/// use tether_map::linked_hash_map::LinkedHashMap;
98///
99/// let mut map = LinkedHashMap::new();
100/// map.insert("apple", 5);
101/// map.insert("banana", 3);
102/// map.insert("cherry", 8);
103///
104/// // Iterate in insertion order
105/// for (key, value) in map.iter() {
106///     println!("{}: {}", key, value);
107/// }
108/// // Prints: apple: 5, banana: 3, cherry: 8
109/// ```
110pub struct LinkedHashMap<K, T, S = RandomState> {
111    nodes: ArenaContainer<K, T>,
112    head_tail: Option<HeadTail<K, T>>,
113    table: HashTable<ActiveSlotRef<K, T>>,
114    hasher: S,
115}
116
117impl<K: Hash + Eq + Clone, T: Clone, S: BuildHasher + Clone> Clone for LinkedHashMap<K, T, S> {
118    fn clone(&self) -> Self {
119        let mut new_map = LinkedHashMap::with_capacity_and_hasher(self.len(), self.hasher.clone());
120        let mut cursor = new_map.head_cursor_mut();
121        for (key, value) in self.iter() {
122            cursor.insert_after_move_to(key.clone(), value.clone());
123        }
124        new_map
125    }
126}
127
128/// Represents an entry that was removed from the linked hash map.
129///
130/// Contains the key-value pair along with the pointers to the previous
131/// and next entries in the linked list, allowing for potential reinsertion
132/// at the same position.
133///
134/// # Examples
135///
136/// ```
137/// use tether_map::LinkedHashMap;
138///
139/// let mut map = LinkedHashMap::new();
140/// map.insert("key", 42);
141/// let ptr = map.get_ptr(&"key").unwrap();
142///
143/// let removed = map.remove_ptr(ptr).unwrap();
144/// assert_eq!(removed.key, "key");
145/// assert_eq!(removed.value, 42);
146/// ```
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct RemovedEntry<K, T> {
149    /// The key of the removed entry
150    pub key: K,
151    /// The value of the removed entry
152    pub value: T,
153    /// Pointer to the previous entry in the linked list
154    pub prev: Option<Ptr>,
155    /// Pointer to the next entry in the linked list
156    pub next: Option<Ptr>,
157}
158
159impl<K: core::fmt::Debug, T: core::fmt::Debug, S> core::fmt::Debug for LinkedHashMap<K, T, S> {
160    fn fmt(
161        &self,
162        f: &mut core::fmt::Formatter<'_>,
163    ) -> core::fmt::Result {
164        #[derive(Debug)]
165        #[allow(dead_code)]
166        struct Entry<'a, K, V> {
167            key: &'a K,
168            value: &'a V,
169            previous: &'a K,
170            next: &'a K,
171        }
172
173        let mut prevnext = Vec::with_capacity(self.len());
174        let mut entries = Vec::with_capacity(self.len());
175
176        for ptr in self.table.iter() {
177            let next = ptr.next(&self.nodes);
178            let prev = ptr.prev(&self.nodes);
179            prevnext.push((prev, next));
180        }
181
182        for (ptr, (prev, next)) in self.table.iter().zip(prevnext.iter()) {
183            let data = ptr.data(&self.nodes);
184            let prev_key = &prev.data(&self.nodes).key;
185            let next_key = &next.data(&self.nodes).key;
186
187            entries.push(Entry {
188                key: &data.key,
189                value: &data.value,
190                previous: prev_key,
191                next: next_key,
192            });
193        }
194
195        f.debug_struct("LinkedHashMap")
196            .field("len", &self.len())
197            .field("head", &self.head_tail.as_ref().map(|ht| &ht.head))
198            .field("tail", &self.head_tail.as_ref().map(|ht| &ht.tail))
199            .field("entries", &entries)
200            .finish()?;
201
202        Ok(())
203    }
204}
205
206impl<K, T, S: BuildHasher + Default> Default for LinkedHashMap<K, T, S> {
207    #[inline]
208    fn default() -> Self {
209        LinkedHashMap::with_capacity_and_hasher(0, S::default())
210    }
211}
212
213impl<K, T> LinkedHashMap<K, T> {
214    /// Creates a new linked hash map with the specified capacity.
215    ///
216    /// The map will be able to hold at least `capacity` elements without
217    /// reallocating. If `capacity` is 0, the map will not allocate.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// use tether_map::LinkedHashMap;
223    ///
224    /// let mut map: LinkedHashMap<&str, i32> = LinkedHashMap::with_capacity(10);
225    /// assert_eq!(map.len(), 0);
226    /// ```
227    #[inline]
228    pub fn with_capacity(capacity: usize) -> Self {
229        Self::with_capacity_and_hasher(capacity, RandomState::default())
230    }
231
232    /// Creates a new, empty linked hash map.
233    ///
234    /// The map is initially created with a capacity of 0, so it will not
235    /// allocate until the first element is inserted.
236    ///
237    /// # Examples
238    ///
239    /// ```
240    /// use tether_map::LinkedHashMap;
241    ///
242    /// let mut map: LinkedHashMap<&str, i32> = LinkedHashMap::new();
243    /// assert!(map.is_empty());
244    /// map.insert("key", 42);
245    /// assert!(!map.is_empty());
246    /// ```
247    #[inline]
248    pub fn new() -> Self {
249        Self::with_capacity(0)
250    }
251}
252
253impl<K, T, S> LinkedHashMap<K, T, S> {
254    /// Creates a new linked hash map with the specified capacity and hasher.
255    ///
256    /// The map will use the given hasher to hash keys and will be able to
257    /// hold at least `capacity` elements without reallocating.
258    ///
259    /// # Examples
260    ///
261    /// ```
262    /// # use hashbrown::DefaultHashBuilder as RandomState;
263    /// use tether_map::linked_hash_map::LinkedHashMap;
264    ///
265    /// let hasher = RandomState::default();
266    /// let mut map: LinkedHashMap<&str, i32, _> = LinkedHashMap::with_capacity_and_hasher(10, hasher);
267    /// map.insert("key", 42);
268    /// ```
269    #[inline]
270    pub fn with_capacity_and_hasher(
271        capacity: usize,
272        hasher: S,
273    ) -> Self {
274        LinkedHashMap {
275            head_tail: None,
276            nodes: Arena::with_capacity(capacity),
277            table: HashTable::with_capacity(capacity),
278            hasher,
279        }
280    }
281
282    /// Moves the entry at `moved` to be immediately after the entry at `after`
283    /// in the linked list.
284    ///
285    /// If `moved` is already immediately after `after`, returns `None` and no
286    /// change is made. Both pointers must refer to valid entries in the
287    /// map.
288    ///
289    /// # Arguments
290    ///
291    /// * `moved` - The pointer to the entry to move
292    /// * `after` - The pointer to the entry after which `moved` will be placed
293    ///
294    /// # Returns
295    ///
296    /// * `Some(())` if the move was successful
297    /// * `None` if the move was unnecessary (already in correct position) or if
298    ///   either pointer is invalid
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use tether_map::LinkedHashMap;
304    ///
305    /// let mut map = LinkedHashMap::new();
306    /// let (ptr1, _) = map.insert_tail_full("a", 1);
307    /// let (ptr2, _) = map.insert_tail_full("b", 2);
308    /// let (ptr3, _) = map.insert_tail_full("c", 3);
309    ///
310    /// // Move "c" to be after "a"
311    /// map.move_after(ptr3, ptr1);
312    ///
313    /// // Order is now: a, c, b
314    /// let entries: Vec<_> = map.iter().collect();
315    /// assert_eq!(entries, [(&"a", &1), (&"c", &3), (&"b", &2)]);
316    /// ```
317    #[inline]
318    pub fn move_after(
319        &mut self,
320        moved: Ptr,
321        after: Ptr,
322    ) -> Option<()> {
323        if moved == after {
324            return None;
325        }
326
327        let moved = self.nodes.map_ptr(moved)?;
328        let after = self.nodes.map_ptr(after)?;
329
330        self.move_after_internal(moved, after)
331    }
332
333    #[inline]
334    fn move_after_internal(
335        &mut self,
336        mut moved: ActiveSlotRef<K, T>,
337        mut after: ActiveSlotRef<K, T>,
338    ) -> Option<()> {
339        debug_assert_ne!(moved, after);
340
341        if let Some(head_tail) = self.head_tail.as_mut()
342            && head_tail.tail == after
343            && head_tail.head == moved
344        {
345            head_tail.tail = moved;
346            head_tail.head = moved.next(&self.nodes);
347            return Some(());
348        }
349
350        if after.next(&self.nodes) == moved {
351            return None;
352        }
353
354        let mut needs_next = moved.prev(&self.nodes);
355        let mut needs_prev = moved.next(&self.nodes);
356        let mut also_needs_prev = after.next(&self.nodes);
357
358        *moved.next_mut(&mut self.nodes) = also_needs_prev;
359        *moved.prev_mut(&mut self.nodes) = after;
360        *after.next_mut(&mut self.nodes) = moved;
361
362        if also_needs_prev != after {
363            *also_needs_prev.prev_mut(&mut self.nodes) = moved;
364        }
365
366        if needs_next != moved {
367            *needs_next.next_mut(&mut self.nodes) = needs_prev;
368        }
369
370        if needs_prev != moved {
371            *needs_prev.prev_mut(&mut self.nodes) = needs_next;
372        }
373
374        if let Some(head_tail) = self.head_tail.as_mut() {
375            if head_tail.head == moved {
376                head_tail.head = needs_prev;
377            }
378            if head_tail.tail == moved {
379                head_tail.tail = needs_next;
380            }
381            if head_tail.tail == after {
382                head_tail.tail = moved;
383            }
384        }
385
386        Some(())
387    }
388
389    /// Moves the entry at `moved` to be immediately before the entry at
390    /// `before` in the linked list.
391    ///
392    /// If `moved` is already immediately before `before`, returns `None` and no
393    /// change is made. Both pointers must refer to valid entries in the
394    /// map.
395    ///
396    /// # Arguments
397    ///
398    /// * `moved` - The pointer to the entry to move
399    /// * `before` - The pointer to the entry before which `moved` will be
400    ///   placed
401    ///
402    /// # Returns
403    ///
404    /// * `Some(())` if the move was successful
405    /// * `None` if the move was unnecessary (already in correct position) or if
406    ///   either pointer is invalid
407    ///
408    /// # Examples
409    ///
410    /// ```
411    /// use tether_map::LinkedHashMap;
412    ///
413    /// let mut map = LinkedHashMap::new();
414    /// let (ptr1, _) = map.insert_tail_full("a", 1);
415    /// let (ptr2, _) = map.insert_tail_full("b", 2);
416    /// let (ptr3, _) = map.insert_tail_full("c", 3);
417    ///
418    /// // Move "a" to be before "c"
419    /// map.move_before(ptr1, ptr3);
420    ///
421    /// // Order is now: b, a, c
422    /// let entries: Vec<_> = map.iter().collect();
423    /// assert_eq!(entries, [(&"b", &2), (&"a", &1), (&"c", &3)]);
424    /// ```
425    #[inline]
426    pub fn move_before(
427        &mut self,
428        moved: Ptr,
429        before: Ptr,
430    ) -> Option<()> {
431        if moved == before {
432            return None;
433        }
434
435        let moved = self.nodes.map_ptr(moved)?;
436        let before = self.nodes.map_ptr(before)?;
437
438        self.move_before_internal(moved, before)
439    }
440
441    #[inline]
442    fn move_before_internal(
443        &mut self,
444        mut moved: ActiveSlotRef<K, T>,
445        mut before: ActiveSlotRef<K, T>,
446    ) -> Option<()> {
447        debug_assert_ne!(moved, before);
448
449        if let Some(head_tail) = self.head_tail.as_mut()
450            && head_tail.head == before
451            && head_tail.tail == moved
452        {
453            head_tail.head = moved;
454            head_tail.tail = moved.prev(&self.nodes);
455            return Some(());
456        }
457
458        if before.prev(&self.nodes) == moved {
459            return None;
460        }
461
462        let mut needs_next = moved.prev(&self.nodes);
463        let mut needs_prev = moved.next(&self.nodes);
464        let mut also_needs_next = before.prev(&self.nodes);
465
466        *moved.next_mut(&mut self.nodes) = before;
467        *moved.prev_mut(&mut self.nodes) = also_needs_next;
468        *before.prev_mut(&mut self.nodes) = moved;
469
470        if also_needs_next != before {
471            *also_needs_next.next_mut(&mut self.nodes) = moved;
472        }
473
474        if needs_next != moved {
475            *needs_next.next_mut(&mut self.nodes) = needs_prev;
476        }
477
478        if needs_prev != moved {
479            *needs_prev.prev_mut(&mut self.nodes) = needs_next;
480        }
481
482        if let Some(head_tail) = self.head_tail.as_mut() {
483            if head_tail.head == moved {
484                head_tail.head = needs_prev;
485            }
486            if head_tail.tail == moved {
487                head_tail.tail = needs_next;
488            }
489            if head_tail.head == before {
490                head_tail.head = moved;
491            }
492        }
493
494        Some(())
495    }
496
497    /// Links an entry as the new head of the linked list.
498    ///
499    /// The entry at `ptr` must already exist in the map but not be part of the
500    /// linked list.
501    ///
502    /// This is a low-level method intended for advanced use cases with entries
503    /// that have been inserted in an unlinked state. Using this with already
504    /// linked entries may screw up the list, causing issues during iteration or
505    /// other operations. It will not cause undefined behavior, but it may lead
506    /// to logical errors.
507    ///
508    /// # Arguments
509    ///
510    /// * `ptr` - The pointer to the entry to link as the new head
511    ///
512    /// # Returns
513    ///
514    /// * `Some(())` if the linking was successful
515    /// * `None` if the pointer is invalid
516    #[inline]
517    pub fn link_as_head(
518        &mut self,
519        ptr: Ptr,
520    ) -> Option<()> {
521        let node = self.nodes.map_ptr(ptr)?;
522        self.link_node_internal(
523            node,
524            self.head_tail.as_ref().map(|ht| ht.tail),
525            self.head_tail.as_ref().map(|ht| ht.head),
526            true,
527        )
528    }
529
530    /// Links an entry as the new tail of the linked list.
531    ///
532    /// The entry at `ptr` must already exist in the map but not be part of the
533    /// linked list.
534    ///
535    /// This is a low-level method intended for advanced use cases with entries
536    /// that have been inserted in an unlinked state. Using this with already
537    /// linked entries may screw up the list, causing issues during iteration or
538    /// other operations. It will not cause undefined behavior, but it may lead
539    /// to logical errors.
540    ///
541    /// # Arguments
542    ///
543    /// * `ptr` - The pointer to the entry to link as the new tail
544    ///
545    /// # Returns
546    ///
547    /// * `Some(())` if the linking was successful
548    /// * `None` if the pointer is invalid
549    #[inline]
550    pub fn link_as_tail(
551        &mut self,
552        ptr: Ptr,
553    ) -> Option<()> {
554        let node = self.nodes.map_ptr(ptr)?;
555        self.link_node_internal(
556            node,
557            self.head_tail.as_ref().map(|ht| ht.tail),
558            self.head_tail.as_ref().map(|ht| ht.head),
559            false,
560        )
561    }
562
563    /// Links an entry into the doubly-linked list at a specific position after
564    /// another entry.
565    ///
566    /// This is a low-level method intended for advanced use cases with entries
567    /// that have been inserted in an unlinked state. Using this with already
568    /// linked entries may screw up the list, causing issues during iteration or
569    /// other operations. It will not cause undefined behavior, but it may lead
570    /// to logical errors.
571    #[inline]
572    pub fn link_after(
573        &mut self,
574        ptr: Ptr,
575        prev: Ptr,
576    ) -> Option<()> {
577        let node = self.nodes.map_ptr(ptr)?;
578        let prev = self.nodes.map_ptr(prev);
579        self.link_node_internal(node, prev, None, false)
580    }
581
582    /// Links an entry into the doubly-linked list at a specific position before
583    /// another entry.
584    ///
585    /// This is a low-level method intended for advanced use cases with entries
586    /// that have been inserted in an unlinked state. Using this with already
587    /// linked entries may screw up the list, causing issues during iteration or
588    /// other operations. It will not cause undefined behavior, but it may lead
589    /// to logical errors.
590    #[inline]
591    pub fn link_before(
592        &mut self,
593        ptr: Ptr,
594        next: Ptr,
595    ) -> Option<()> {
596        let node = self.nodes.map_ptr(ptr)?;
597        let next = self.nodes.map_ptr(next);
598        self.link_node_internal(node, None, next, true)
599    }
600
601    /// # Safety
602    ///
603    /// `node` must be occupied (i.e. part of this map's arena). If prev and
604    /// next are non-null, they must also be occupied.
605    #[inline]
606    fn link_node_internal(
607        &mut self,
608        mut node: ActiveSlotRef<K, T>,
609        prev: Option<ActiveSlotRef<K, T>>,
610        next: Option<ActiveSlotRef<K, T>>,
611        as_head: bool,
612    ) -> Option<()> {
613        if let Some(head_tail) = self.head_tail.as_mut() {
614            if prev.is_none() && next.is_none() {
615                return None;
616            }
617
618            let mut prev = if let Some(prev) = prev {
619                prev
620            } else {
621                next.unwrap().prev(&self.nodes)
622            };
623
624            let mut next = if let Some(next) = next {
625                next
626            } else {
627                prev.next(&self.nodes)
628            };
629
630            *prev.next_mut(&mut self.nodes) = node;
631            *next.prev_mut(&mut self.nodes) = node;
632            *node.prev_mut(&mut self.nodes) = prev;
633            *node.next_mut(&mut self.nodes) = next;
634
635            if !as_head && head_tail.tail == prev {
636                head_tail.tail = node;
637            } else if as_head && head_tail.head == next {
638                head_tail.head = node;
639            }
640
641            Some(())
642        } else {
643            self.head_tail = Some(HeadTail {
644                head: node,
645                tail: node,
646            });
647            Some(())
648        }
649    }
650
651    /// Moves an entry to the tail (end) of the linked list.
652    ///
653    /// This is equivalent to calling `move_after(moved, tail_ptr())`.
654    ///
655    /// # Arguments
656    ///
657    /// * `moved` - The pointer to the entry to move to the tail
658    ///
659    /// # Returns
660    ///
661    /// * `Some(())` if the move was successful
662    /// * `None` if the entry is already at the tail or if the pointer is
663    ///   invalid
664    ///
665    /// # Examples
666    ///
667    /// ```
668    /// use tether_map::LinkedHashMap;
669    ///
670    /// let mut map = LinkedHashMap::new();
671    /// let (ptr1, _) = map.insert_tail_full("a", 1);
672    /// let (ptr2, _) = map.insert_tail_full("b", 2);
673    /// let (ptr3, _) = map.insert_tail_full("c", 3);
674    ///
675    /// // Move "a" to the tail
676    /// map.move_to_tail(ptr1);
677    ///
678    /// // Order is now: b, c, a
679    /// let entries: Vec<_> = map.iter().collect();
680    /// assert_eq!(entries, [(&"b", &2), (&"c", &3), (&"a", &1)]);
681    /// ```
682    #[inline]
683    pub fn move_to_tail(
684        &mut self,
685        moved: Ptr,
686    ) -> Option<()> {
687        self.move_after(moved, self.tail_ptr()?)
688    }
689
690    /// Moves an entry to the head (beginning) of the linked list.
691    ///
692    /// This is equivalent to calling `move_before(moved, head_ptr())`.
693    ///
694    /// # Arguments
695    ///
696    /// * `moved` - The pointer to the entry to move to the head
697    ///
698    /// # Returns
699    ///
700    /// * `Some(())` if the move was successful
701    /// * `None` if the entry is already at the head or if the pointer is
702    ///   invalid
703    ///
704    /// # Examples
705    ///
706    /// ```
707    /// use tether_map::LinkedHashMap;
708    ///
709    /// let mut map = LinkedHashMap::new();
710    /// let (ptr1, _) = map.insert_tail_full("a", 1);
711    /// let (ptr2, _) = map.insert_tail_full("b", 2);
712    /// let (ptr3, _) = map.insert_tail_full("c", 3);
713    ///
714    /// // Move "c" to the head
715    /// map.move_to_head(ptr3);
716    ///
717    /// // Order is now: c, a, b
718    /// let entries: Vec<_> = map.iter().collect();
719    /// assert_eq!(entries, [(&"c", &3), (&"a", &1), (&"b", &2)]);
720    /// ```
721    #[inline]
722    pub fn move_to_head(
723        &mut self,
724        moved: Ptr,
725    ) -> Option<()> {
726        self.move_before(moved, self.head_ptr()?)
727    }
728
729    /// Creates a mutable cursor positioned at the entry with the given pointer.
730    ///
731    /// A cursor provides a way to navigate and modify the linked list structure
732    /// while maintaining efficient access to specific entries.
733    ///
734    /// # Arguments
735    ///
736    /// * `ptr` - The pointer to the entry where the cursor should be positioned
737    ///
738    /// # Returns
739    ///
740    /// A `CursorMut` positioned at the specified entry. If the pointer is
741    /// invalid, the cursor will be positioned at a null entry.
742    ///
743    /// # Examples
744    ///
745    /// ```
746    /// use tether_map::LinkedHashMap;
747    ///
748    /// let mut map = LinkedHashMap::new();
749    /// let (ptr, _) = map.insert_tail_full("a", 1);
750    ///
751    /// let mut cursor = map.ptr_cursor_mut(ptr);
752    /// if let Some((key, value)) = cursor.current_mut() {
753    ///     *value = 42;
754    /// }
755    /// ```
756    #[inline]
757    pub fn ptr_cursor_mut(
758        &'_ mut self,
759        ptr: Ptr,
760    ) -> CursorMut<'_, K, T, S> {
761        let ptr = self.nodes.map_ptr(ptr);
762        CursorMut { ptr, map: self }
763    }
764
765    /// Returns the pointer to the next entry in the linked list.
766    ///
767    /// # Arguments
768    ///
769    /// * `ptr` - The pointer to the current entry
770    ///
771    /// # Returns
772    ///
773    /// * `Some(next_ptr)` if there is a next entry
774    /// * `None` if the pointer is invalid
775    ///
776    /// # Examples
777    ///
778    /// ```
779    /// use tether_map::LinkedHashMap;
780    ///
781    /// let mut map = LinkedHashMap::new();
782    /// let (ptr1, _) = map.insert_tail_full("a", 1);
783    /// let (ptr2, _) = map.insert_tail_full("b", 2);
784    ///
785    /// // Get the next entry after "a"
786    /// let next = map.next_ptr(ptr1).unwrap();
787    /// assert_eq!(map.ptr_get(next), Some(&2));
788    /// ```
789    #[inline]
790    pub fn next_ptr(
791        &self,
792        ptr: Ptr,
793    ) -> Option<Ptr> {
794        let ptr = self.nodes.map_ptr(ptr)?;
795        Some(ptr.next(&self.nodes).this(&self.nodes))
796    }
797
798    /// Returns the pointer to the previous entry in the linked list.
799    ///
800    /// # Arguments
801    ///
802    /// * `ptr` - The pointer to the current entry
803    ///
804    /// # Returns
805    ///
806    /// * `Some(prev_ptr)` if there is a previous entry
807    /// * `None` if the pointer is invalid
808    ///
809    /// # Examples
810    ///
811    /// ```
812    /// use tether_map::LinkedHashMap;
813    ///
814    /// let mut map = LinkedHashMap::new();
815    /// let (ptr1, _) = map.insert_tail_full("a", 1);
816    /// let (ptr2, _) = map.insert_tail_full("b", 2);
817    ///
818    /// // Get the previous entry before "b"
819    /// let prev = map.prev_ptr(ptr2).unwrap();
820    /// assert_eq!(map.ptr_get(prev), Some(&1));
821    /// ```
822    #[inline]
823    pub fn prev_ptr(
824        &self,
825        ptr: Ptr,
826    ) -> Option<Ptr> {
827        let ptr = self.nodes.map_ptr(ptr)?;
828        Some(ptr.prev(&self.nodes).this(&self.nodes))
829    }
830
831    /// Creates a mutable cursor positioned at the head (first entry) of the
832    /// linked list.
833    ///
834    /// # Returns
835    ///
836    /// A `CursorMut` positioned at the head entry. If the map is empty,
837    /// the cursor will be positioned at a null entry.
838    ///
839    /// # Examples
840    ///
841    /// ```
842    /// use tether_map::LinkedHashMap;
843    ///
844    /// let mut map = LinkedHashMap::new();
845    /// map.insert_tail("a", 1);
846    /// map.insert_tail("b", 2);
847    ///
848    /// let mut cursor = map.head_cursor_mut();
849    /// if let Some((key, value)) = cursor.current_mut() {
850    ///     assert_eq!(key, &"a");
851    ///     *value = 42;
852    /// }
853    /// ```
854    #[inline]
855    pub fn head_cursor_mut(&'_ mut self) -> CursorMut<'_, K, T, S> {
856        CursorMut {
857            ptr: self.head_tail.as_ref().map(|ht| ht.head),
858            map: self,
859        }
860    }
861
862    /// Creates a mutable cursor positioned at the tail (last entry) of the
863    /// linked list.
864    ///
865    /// # Returns
866    ///
867    /// A `CursorMut` positioned at the tail entry. If the map is empty,
868    /// the cursor will be positioned at a null entry.
869    ///
870    /// # Examples
871    ///
872    /// ```
873    /// use tether_map::LinkedHashMap;
874    ///
875    /// let mut map = LinkedHashMap::new();
876    /// map.insert_tail("a", 1);
877    /// map.insert_tail("b", 2);
878    ///
879    /// let mut cursor = map.tail_cursor_mut();
880    /// if let Some((key, value)) = cursor.current_mut() {
881    ///     assert_eq!(key, &"b");
882    ///     *value = 42;
883    /// }
884    /// ```
885    #[inline]
886    pub fn tail_cursor_mut(&'_ mut self) -> CursorMut<'_, K, T, S> {
887        CursorMut {
888            ptr: self.head_tail.as_ref().map(|ht| ht.tail),
889            map: self,
890        }
891    }
892
893    /// Returns the pointer to the head (first entry) of the linked list.
894    #[inline]
895    pub fn head_ptr(&self) -> Option<Ptr> {
896        self.head_tail.as_ref().map(|ht| ht.head.this(&self.nodes))
897    }
898
899    /// Returns the pointer to the tail (last entry) of the linked list.
900    #[inline]
901    pub fn tail_ptr(&self) -> Option<Ptr> {
902        self.head_tail.as_ref().map(|ht| ht.tail.this(&self.nodes))
903    }
904
905    /// Returns a reference to the value associated with the given pointer.
906    #[inline]
907    pub fn ptr_get(
908        &self,
909        ptr: Ptr,
910    ) -> Option<&T> {
911        self.nodes.map_ptr(ptr).map(|p| &p.data(&self.nodes).value)
912    }
913
914    /// Returns a reference to the key-value pair associated with the given
915    /// pointer.
916    #[inline]
917    pub fn ptr_get_entry(
918        &self,
919        ptr: Ptr,
920    ) -> Option<(&K, &T)> {
921        self.nodes.map_ptr(ptr).map(|p| {
922            let data = p.data(&self.nodes);
923            (&data.key, &data.value)
924        })
925    }
926
927    /// Returns a mutable reference to the key-value pair associated with the
928    /// given pointer.
929    #[inline]
930    pub fn ptr_get_entry_mut(
931        &mut self,
932        ptr: Ptr,
933    ) -> Option<(&K, &mut T)> {
934        self.nodes.map_ptr(ptr).map(|mut p| {
935            let data = p.data_mut(&mut self.nodes);
936            (&data.key, &mut data.value)
937        })
938    }
939
940    /// Returns a mutable reference to the value associated with the given
941    /// pointer.
942    #[inline]
943    pub fn ptr_get_mut(
944        &mut self,
945        ptr: Ptr,
946    ) -> Option<&mut T> {
947        self.nodes
948            .map_ptr(ptr)
949            .map(|mut p| &mut p.data_mut(&mut self.nodes).value)
950    }
951
952    /// Returns a reference to the key associated with the given pointer.
953    #[inline]
954    pub fn ptr_get_key(
955        &self,
956        ptr: Ptr,
957    ) -> Option<&K> {
958        self.nodes.map_ptr(ptr).map(|p| &p.data(&self.nodes).key)
959    }
960
961    /// Returns the number of elements in the map.
962    ///
963    /// # Examples
964    ///
965    /// ```
966    /// use tether_map::LinkedHashMap;
967    ///
968    /// let mut a = LinkedHashMap::new();
969    /// assert_eq!(a.len(), 0);
970    /// a.insert(1, "a");
971    /// assert_eq!(a.len(), 1);
972    /// ```
973    #[inline]
974    pub fn len(&self) -> usize {
975        self.table.len()
976    }
977
978    /// Returns `true` if the map contains no elements.
979    ///
980    /// # Examples
981    ///
982    /// ```
983    /// use tether_map::LinkedHashMap;
984    ///
985    /// let mut a = LinkedHashMap::new();
986    /// assert!(a.is_empty());
987    /// a.insert(1, "a");
988    /// assert!(!a.is_empty());
989    /// ```
990    #[inline]
991    pub fn is_empty(&self) -> bool {
992        self.len() == 0
993    }
994
995    /// Clears the map, removing all key-value pairs.
996    ///
997    /// Keeps the allocated memory for reuse.
998    ///
999    /// # Examples
1000    ///
1001    /// ```
1002    /// use tether_map::LinkedHashMap;
1003    ///
1004    /// let mut a = LinkedHashMap::new();
1005    /// a.insert(1, "a");
1006    /// a.clear();
1007    /// assert!(a.is_empty());
1008    /// ```
1009    pub fn clear(&mut self) {
1010        for node in self.table.drain() {
1011            // SAFETY: We do not touch nodes after freeing them, so this is safe.
1012            unsafe {
1013                self.nodes.free_and_unlink(node);
1014            }
1015        }
1016        self.head_tail = None;
1017    }
1018
1019    /// Returns an iterator over the key-value pairs of the map, in relative
1020    /// order.
1021    ///
1022    /// The iterator element type is `(&'a K, &'a V)`.
1023    ///
1024    /// # Examples
1025    ///
1026    /// ```
1027    /// use tether_map::LinkedHashMap;
1028    ///
1029    /// let mut map = LinkedHashMap::new();
1030    /// map.insert("a", 1);
1031    /// map.insert("b", 2);
1032    /// map.insert("c", 3);
1033    ///
1034    /// for (key, val) in map.iter() {
1035    ///     println!("key: {} val: {}", key, val);
1036    /// }
1037    /// ```
1038    #[inline]
1039    pub fn iter<'s>(&'s self) -> Iter<'s, K, T> {
1040        Iter {
1041            forward_ptr: self.head_tail.as_ref().map(|ht| ht.head),
1042            reverse_ptr: self.head_tail.as_ref().map(|ht| ht.tail),
1043            nodes: &self.nodes,
1044        }
1045    }
1046
1047    /// Checks if the map contains an entry for the given pointer.
1048    ///
1049    /// # Arguments
1050    ///
1051    /// * `ptr` - The pointer to check for existence in the map
1052    ///
1053    /// # Returns
1054    ///
1055    /// * `true` if the map contains an entry for the pointer
1056    /// * `false` otherwise
1057    ///
1058    /// # Examples
1059    ///
1060    /// ```
1061    /// use tether_map::LinkedHashMap;
1062    ///
1063    /// let mut map = LinkedHashMap::new();
1064    /// let (ptr, _) = map.insert_tail_full("a", 1);
1065    /// assert!(map.contains_ptr(ptr));
1066    /// map.remove_ptr(ptr);
1067    /// assert!(!map.contains_ptr(ptr));
1068    /// ```
1069    #[inline]
1070    pub fn contains_ptr(
1071        &self,
1072        ptr: Ptr,
1073    ) -> bool {
1074        self.nodes.is_occupied(ptr)
1075    }
1076
1077    /// Returns an iterator over the keys of the map in their relative order.
1078    ///
1079    /// The keys are returned in the order they were inserted into the map,
1080    /// which is maintained by the underlying doubly-linked list.
1081    ///
1082    /// # Returns
1083    ///
1084    /// An iterator that yields `&K` values in relative order.
1085    ///
1086    /// # Examples
1087    ///
1088    /// ```
1089    /// use tether_map::LinkedHashMap;
1090    ///
1091    /// let mut map = LinkedHashMap::new();
1092    /// map.insert("a", 1);
1093    /// map.insert("b", 2);
1094    /// map.insert("c", 3);
1095    ///
1096    /// let keys: Vec<_> = map.keys().collect();
1097    /// assert_eq!(keys, [&"a", &"b", &"c"]);
1098    /// ```
1099    #[inline]
1100    pub fn keys(&self) -> impl Iterator<Item = &K> {
1101        self.iter().map(|(k, _)| k)
1102    }
1103
1104    /// Returns an iterator over the values of the map in their relative order.
1105    ///
1106    /// The values are returned in the order their corresponding keys were
1107    /// inserted into the map, which is maintained by the underlying
1108    /// doubly-linked list.
1109    ///
1110    /// # Returns
1111    ///
1112    /// An iterator that yields `&T` values in relative order.
1113    ///
1114    /// # Examples
1115    ///
1116    /// ```
1117    /// use tether_map::LinkedHashMap;
1118    ///
1119    /// let mut map = LinkedHashMap::new();
1120    /// map.insert("a", 1);
1121    /// map.insert("b", 2);
1122    /// map.insert("c", 3);
1123    ///
1124    /// let values: Vec<_> = map.values().collect();
1125    /// assert_eq!(values, [&1, &2, &3]);
1126    /// ```
1127    #[inline]
1128    pub fn values(&self) -> impl Iterator<Item = &T> {
1129        self.iter().map(|(_, v)| v)
1130    }
1131
1132    /// Returns a mutable iterator over the values of the map in their relative
1133    /// order.
1134    ///
1135    /// The values are returned in the order their corresponding keys were
1136    /// inserted into the map, which is maintained by the underlying
1137    /// doubly-linked list. This method allows for in-place mutation of the
1138    /// values.
1139    ///
1140    /// # Returns
1141    ///
1142    /// A mutable iterator that yields `&mut T` values in relative order.
1143    ///
1144    /// # Examples
1145    ///
1146    /// ```
1147    /// use tether_map::LinkedHashMap;
1148    ///
1149    /// let mut map = LinkedHashMap::new();
1150    /// map.insert("a", 1);
1151    /// map.insert("b", 2);
1152    /// map.insert("c", 3);
1153    ///
1154    /// for value in map.values_mut() {
1155    ///     *value *= 2;
1156    /// }
1157    ///
1158    /// let values: Vec<_> = map.values().collect();
1159    /// assert_eq!(values, [&2, &4, &6]);
1160    /// ```
1161    #[inline]
1162    pub fn values_mut<'s>(&'s mut self) -> ValuesMut<'s, K, T> {
1163        ValuesMut {
1164            iter: self.iter_mut(),
1165        }
1166    }
1167
1168    /// Returns a mutable iterator over the key-value pairs of the map in their
1169    /// relative order.
1170    ///
1171    /// The key-value pairs are returned in the order they were inserted into
1172    /// the map, which is maintained by the underlying doubly-linked list.
1173    /// This method allows for in-place mutation of the values while keeping
1174    /// the keys immutable.
1175    ///
1176    /// # Returns
1177    ///
1178    /// A mutable iterator that yields `(&K, &mut T)` pairs in relative order.
1179    ///
1180    /// # Examples
1181    ///
1182    /// ```
1183    /// use tether_map::LinkedHashMap;
1184    ///
1185    /// let mut map = LinkedHashMap::new();
1186    /// map.insert("a", 1);
1187    /// map.insert("b", 2);
1188    /// map.insert("c", 3);
1189    ///
1190    /// for (key, value) in map.iter_mut() {
1191    ///     if key == &"b" {
1192    ///         *value *= 10;
1193    ///     }
1194    /// }
1195    ///
1196    /// assert_eq!(map.get(&"b"), Some(&20));
1197    /// ```
1198    #[inline]
1199    pub fn iter_mut<'s>(&'s mut self) -> IterMut<'s, K, T> {
1200        IterMut {
1201            forward_ptr: self.head_tail.as_ref().map(|ht| ht.head),
1202            reverse_ptr: self.head_tail.as_ref().map(|ht| ht.tail),
1203            _nodes: core::marker::PhantomData,
1204        }
1205    }
1206}
1207
1208impl<K, T, S> PartialEq for LinkedHashMap<K, T, S>
1209where
1210    K: Hash + Eq,
1211    T: PartialEq,
1212    S: BuildHasher,
1213{
1214    fn eq(
1215        &self,
1216        other: &Self,
1217    ) -> bool {
1218        if self.len() != other.len() {
1219            return false;
1220        }
1221
1222        self.iter()
1223            .all(|(key, value)| other.get(key).is_some_and(|v| *value == *v))
1224    }
1225}
1226
1227impl<K, T, S> Eq for LinkedHashMap<K, T, S>
1228where
1229    K: Hash + Eq,
1230    T: Eq,
1231    S: BuildHasher,
1232{
1233}
1234
1235impl<K, T, S> FromIterator<(K, T)> for LinkedHashMap<K, T, S>
1236where
1237    K: Hash + Eq,
1238    S: BuildHasher + Default,
1239{
1240    fn from_iter<I: IntoIterator<Item = (K, T)>>(iter: I) -> Self {
1241        let mut map = Self::default();
1242        map.extend(iter);
1243        map
1244    }
1245}
1246
1247impl<K, T, S> Extend<(K, T)> for LinkedHashMap<K, T, S>
1248where
1249    K: Hash + Eq,
1250    S: BuildHasher,
1251{
1252    fn extend<I: IntoIterator<Item = (K, T)>>(
1253        &mut self,
1254        iter: I,
1255    ) {
1256        for (key, value) in iter {
1257            self.insert(key, value);
1258        }
1259    }
1260}
1261
1262impl<'a, K, T, S> Extend<(&'a K, &'a T)> for LinkedHashMap<K, T, S>
1263where
1264    K: Hash + Eq + Clone,
1265    T: Clone,
1266    S: BuildHasher,
1267{
1268    fn extend<I: IntoIterator<Item = (&'a K, &'a T)>>(
1269        &mut self,
1270        iter: I,
1271    ) {
1272        for (key, value) in iter {
1273            self.insert(key.clone(), value.clone());
1274        }
1275    }
1276}
1277
1278impl<K, T, S> IntoIterator for LinkedHashMap<K, T, S> {
1279    type IntoIter = IntoIter<K, T>;
1280    type Item = (K, T);
1281
1282    #[inline]
1283    fn into_iter(self) -> Self::IntoIter {
1284        IntoIter {
1285            nodes: self.nodes,
1286            forward_ptr: self.head_tail.as_ref().map(|ht| ht.head),
1287            reverse_ptr: self.head_tail.as_ref().map(|ht| ht.tail),
1288        }
1289    }
1290}
1291
1292impl<K: Hash + Eq, T, S: BuildHasher> LinkedHashMap<K, T, S> {
1293    /// Shrinks the capacity of the map as much as possible.
1294    ///
1295    /// This will drop down the number of buckets in the underlying hash table
1296    /// as much as possible while maintaining the current number of elements.
1297    ///
1298    /// It does not affect the capacity of the arena used for storing entries,
1299    /// as it's not possible to safely shrink that without risking invalidating
1300    /// existing pointers.
1301    pub fn shrink_to_fit(&mut self) {
1302        self.table
1303            .shrink_to_fit(|k| self.hasher.hash_one(&k.data(&self.nodes).key));
1304    }
1305
1306    /// Removes the entry at the tail (end) of the linked list.
1307    ///
1308    /// This is equivalent to calling `remove_ptr(tail_ptr())`, but is more
1309    /// performant.
1310    #[inline]
1311    pub fn remove_tail(&mut self) -> Option<(Ptr, RemovedEntry<K, T>)> {
1312        let ptr = self.head_tail.as_ref().map(|ht| ht.tail)?;
1313
1314        Some(self.remove_ptr_internal(ptr))
1315    }
1316
1317    /// Removes the entry at the head (beginning) of the linked list.
1318    ///
1319    /// This is equivalent to calling `remove_ptr(head_ptr())`, but is more
1320    /// performant.
1321    #[inline]
1322    pub fn remove_head(&mut self) -> Option<(Ptr, RemovedEntry<K, T>)> {
1323        let ptr = self.head_tail.as_ref().map(|ht| ht.head)?;
1324        Some(self.remove_ptr_internal(ptr))
1325    }
1326
1327    /// Removes the entry at the given pointer from the map.
1328    ///
1329    /// If the pointer is invalid or does not correspond to an occupied entry,
1330    /// returns `None`. Otherwise, removes the entry and returns a
1331    /// `RemovedEntry` containing the key, value, and neighboring pointers.
1332    #[inline]
1333    pub fn remove_ptr(
1334        &mut self,
1335        ptr: Ptr,
1336    ) -> Option<RemovedEntry<K, T>> {
1337        let ptr = self.nodes.map_ptr(ptr)?;
1338
1339        Some(self.remove_ptr_internal(ptr).1)
1340    }
1341
1342    fn remove_ptr_internal(
1343        &mut self,
1344        ptr: ActiveSlotRef<K, T>,
1345    ) -> (Ptr, RemovedEntry<K, T>) {
1346        let hash = self.hasher.hash_one(&ptr.data(&self.nodes).key);
1347
1348        match self.table.find_entry(hash, move |k| *k == ptr) {
1349            Ok(occupied) => {
1350                occupied.remove();
1351            }
1352            Err(_) => {
1353                #[cold]
1354                #[inline(never)]
1355                fn die() -> ! {
1356                    panic!("Pointer not found in table");
1357                }
1358                die()
1359            }
1360        };
1361
1362        // SAFETY: We have removed the pointer from our table, and we do not dereference
1363        // it after this point.
1364        let FreedSlot {
1365            data,
1366            prev_next,
1367            this,
1368        } = unsafe { self.nodes.free_and_unlink(ptr) };
1369
1370        if let Some((prev, next)) = prev_next {
1371            if let Some(head_tail) = self.head_tail.as_mut() {
1372                if head_tail.head == ptr {
1373                    head_tail.head = next;
1374                }
1375                if head_tail.tail == ptr {
1376                    head_tail.tail = prev;
1377                }
1378            }
1379        } else if self
1380            .head_tail
1381            .as_ref()
1382            .is_some_and(|ht| ht.head == ptr || ht.tail == ptr)
1383        {
1384            self.head_tail = None;
1385        }
1386
1387        (
1388            this,
1389            RemovedEntry {
1390                key: data.key,
1391                value: data.value,
1392                prev: prev_next.map(|(p, _)| p.this(&self.nodes)),
1393                next: prev_next.map(|(_, n)| n.this(&self.nodes)),
1394            },
1395        )
1396    }
1397
1398    /// Retains only the entries specified by the predicate.
1399    ///
1400    /// In other words, removes all entries for which `f(&key, &mut value)`
1401    /// returns `false`. The entries are visited in relative order, and the
1402    /// predicate is allowed to modify the values.
1403    ///
1404    /// # Arguments
1405    ///
1406    /// * `f` - A closure that returns `true` for entries that should be kept.
1407    ///   It receives references to the key and a mutable reference to the
1408    ///   value.
1409    ///
1410    /// # Examples
1411    ///
1412    /// ```
1413    /// use tether_map::LinkedHashMap;
1414    ///
1415    /// let mut map = LinkedHashMap::new();
1416    /// map.insert("a", 1);
1417    /// map.insert("b", 2);
1418    /// map.insert("c", 3);
1419    /// map.insert("d", 4);
1420    ///
1421    /// // Keep only entries with even values, and double them
1422    /// map.retain(|_key, value| {
1423    ///     if *value % 2 == 0 {
1424    ///         *value *= 2;
1425    ///         true
1426    ///     } else {
1427    ///         false
1428    ///     }
1429    /// });
1430    ///
1431    /// // Only "b" and "d" remain, with values doubled
1432    /// assert_eq!(map.len(), 2);
1433    /// assert_eq!(map.get(&"b"), Some(&4));
1434    /// assert_eq!(map.get(&"d"), Some(&8));
1435    /// ```
1436    pub fn retain<F>(
1437        &mut self,
1438        mut f: F,
1439    ) where
1440        F: FnMut(&K, &mut T) -> bool,
1441    {
1442        let Some(mut ptr) = self.head_tail.as_ref().map(|ht| ht.head) else {
1443            return;
1444        };
1445
1446        let mut seen = 0;
1447        let len = self.len();
1448        while seen < len {
1449            seen += 1;
1450            let next = ptr.next(&self.nodes);
1451            let node = ptr.data_mut(&mut self.nodes);
1452
1453            if !f(&node.key, &mut node.value) {
1454                self.remove_ptr_internal(ptr);
1455            }
1456            ptr = next;
1457        }
1458    }
1459
1460    /// Inserts a key-value pair into the map.
1461    ///
1462    /// If the map did not have this key present, `None` is returned and the
1463    /// entry is inserted at the tail (most recently inserted position).
1464    ///
1465    /// If the map did have this key present, the value is updated and the old
1466    /// value is returned. The entry is **not** moved in the linked list.
1467    ///
1468    /// # Examples
1469    ///
1470    /// ```
1471    /// use tether_map::LinkedHashMap;
1472    ///
1473    /// let mut map = LinkedHashMap::new();
1474    /// assert_eq!(map.insert(37, "a"), None);
1475    /// assert_eq!(map.is_empty(), false);
1476    ///
1477    /// map.insert(37, "b");
1478    /// assert_eq!(map.insert(37, "c"), Some("b"));
1479    /// assert_eq!(map.get(&37), Some(&"c"));
1480    /// ```
1481    #[inline]
1482    pub fn insert(
1483        &mut self,
1484        key: K,
1485        value: T,
1486    ) -> Option<T> {
1487        let entry = self.entry(key);
1488        match entry {
1489            Entry::Occupied(occupied_entry) => {
1490                let old = occupied_entry.insert_no_move(value);
1491                Some(old)
1492            }
1493            Entry::Vacant(vacant_entry) => {
1494                vacant_entry.insert_tail(value);
1495                None
1496            }
1497        }
1498    }
1499
1500    /// Inserts a key-value pair and returns the pointer and any previous value.
1501    ///
1502    /// This method provides the same functionality as `insert` but returns
1503    /// additional information: the pointer to the inserted/updated entry
1504    /// and any previous value that was replaced. The insertion position
1505    /// depends on whether the key already exists:
1506    ///
1507    /// - If the key is new, the entry is inserted at the tail
1508    /// - If the key exists, the value is updated in-place without moving the
1509    ///   entry
1510    ///
1511    /// # Arguments
1512    ///
1513    /// * `key` - The key to insert or update
1514    /// * `value` - The value to insert
1515    ///
1516    /// # Returns
1517    ///
1518    /// A tuple containing:
1519    /// - `Ptr` - The pointer to the inserted or updated entry
1520    /// - `Option<T>` - `Some(old_value)` if the key existed, `None` if it was
1521    ///   newly inserted
1522    ///
1523    /// # Examples
1524    ///
1525    /// ```
1526    /// use tether_map::LinkedHashMap;
1527    ///
1528    /// let mut map = LinkedHashMap::new();
1529    ///
1530    /// // Insert new entry
1531    /// let (ptr1, old) = map.insert_full("key1", 10);
1532    /// assert_eq!(old, None); // No previous value
1533    ///
1534    /// // Update existing entry
1535    /// let (ptr2, old) = map.insert_full("key1", 20);
1536    /// assert_eq!(old, Some(10)); // Previous value returned
1537    /// assert_eq!(ptr1, ptr2); // Same pointer since key existed
1538    ///
1539    /// // Use the pointer for direct access
1540    /// assert_eq!(map.ptr_get(ptr1), Some(&20));
1541    /// ```
1542    #[inline]
1543    pub fn insert_full(
1544        &mut self,
1545        key: K,
1546        value: T,
1547    ) -> (Ptr, Option<T>) {
1548        let entry = self.entry(key);
1549        match entry {
1550            Entry::Occupied(occupied_entry) => {
1551                let ptr = occupied_entry.ptr();
1552                let old = occupied_entry.insert_no_move(value);
1553                (ptr, Some(old))
1554            }
1555            Entry::Vacant(vacant_entry) => {
1556                let (ptr, _) = vacant_entry.insert_tail(value);
1557                (ptr, None)
1558            }
1559        }
1560    }
1561
1562    /// Inserts a key-value pair at the tail of the linked list.
1563    ///
1564    /// If the key already exists, updates the value and moves the entry
1565    /// to the tail position, returning the old value.
1566    ///
1567    /// # Examples
1568    ///
1569    /// ```
1570    /// use tether_map::LinkedHashMap;
1571    ///
1572    /// let mut map = LinkedHashMap::new();
1573    /// map.insert_tail("first", 1);
1574    /// map.insert_tail("second", 2);
1575    ///
1576    /// let keys: Vec<_> = map.keys().cloned().collect();
1577    /// assert_eq!(keys, ["first", "second"]);
1578    /// ```
1579    #[inline]
1580    pub fn insert_tail(
1581        &mut self,
1582        key: K,
1583        value: T,
1584    ) -> Option<T> {
1585        let entry = self.entry(key);
1586        match entry {
1587            Entry::Occupied(occupied_entry) => {
1588                let ptr = occupied_entry.ptr();
1589                let old = occupied_entry.insert_no_move(value);
1590                self.move_to_tail(ptr);
1591                Some(old)
1592            }
1593            Entry::Vacant(vacant_entry) => {
1594                vacant_entry.insert_tail(value);
1595                None
1596            }
1597        }
1598    }
1599
1600    /// Inserts a key-value pair at the tail and returns the pointer and any
1601    /// previous value.
1602    ///
1603    /// This method is similar to `insert_full` but with explicit tail
1604    /// positioning behavior:
1605    ///
1606    /// - If the key is new, the entry is inserted at the tail
1607    /// - If the key exists, the value is updated AND the entry is moved to the
1608    ///   tail
1609    ///
1610    /// This is useful when you want to ensure that updated entries are moved to
1611    /// the most recent position, implementing LRU (Least Recently Used)
1612    /// cache behavior.
1613    ///
1614    /// # Arguments
1615    ///
1616    /// * `key` - The key to insert or update
1617    /// * `value` - The value to insert
1618    ///
1619    /// # Returns
1620    ///
1621    /// A tuple containing:
1622    /// - `Ptr` - The pointer to the inserted or updated entry
1623    /// - `Option<T>` - `Some(old_value)` if the key existed, `None` if it was
1624    ///   newly inserted
1625    ///
1626    /// # Examples
1627    ///
1628    /// ```
1629    /// use tether_map::LinkedHashMap;
1630    ///
1631    /// let mut map = LinkedHashMap::new();
1632    /// map.insert("a", 1);
1633    /// map.insert("b", 2);
1634    /// map.insert("c", 3);
1635    ///
1636    /// // Update existing entry - it moves to tail
1637    /// let (ptr, old) = map.insert_tail_full("a", 10);
1638    /// assert_eq!(old, Some(1));
1639    ///
1640    /// // Order is now: b, c, a (with updated value)
1641    /// let entries: Vec<_> = map.iter().collect();
1642    /// assert_eq!(entries, [(&"b", &2), (&"c", &3), (&"a", &10)]);
1643    /// ```
1644    #[inline]
1645    pub fn insert_tail_full(
1646        &mut self,
1647        key: K,
1648        value: T,
1649    ) -> (Ptr, Option<T>) {
1650        let entry = self.entry(key);
1651        match entry {
1652            Entry::Occupied(occupied_entry) => {
1653                let ptr = occupied_entry.ptr();
1654                let old = occupied_entry.insert_no_move(value);
1655                self.move_to_tail(ptr);
1656                (ptr, Some(old))
1657            }
1658            Entry::Vacant(vacant_entry) => {
1659                let (ptr, _) = vacant_entry.insert_tail(value);
1660                (ptr, None)
1661            }
1662        }
1663    }
1664
1665    /// Inserts a key-value pair at the head of the linked list.
1666    ///
1667    /// If the key already exists, updates the value and moves the entry
1668    /// to the head position, returning the old value.
1669    ///
1670    /// # Examples
1671    ///
1672    /// ```
1673    /// use tether_map::LinkedHashMap;
1674    ///
1675    /// let mut map = LinkedHashMap::new();
1676    /// map.insert_head("first", 1);
1677    /// map.insert_head("second", 2);
1678    ///
1679    /// let keys: Vec<_> = map.keys().cloned().collect();
1680    /// assert_eq!(keys, ["second", "first"]); // second is now first
1681    /// ```
1682    #[inline]
1683    pub fn insert_head(
1684        &mut self,
1685        key: K,
1686        value: T,
1687    ) -> Option<T> {
1688        let entry = self.entry(key);
1689        match entry {
1690            Entry::Occupied(occupied_entry) => {
1691                let ptr = occupied_entry.ptr();
1692                let old = occupied_entry.insert_no_move(value);
1693                self.move_to_head(ptr);
1694                Some(old)
1695            }
1696            Entry::Vacant(vacant_entry) => {
1697                vacant_entry.insert_head(value);
1698                None
1699            }
1700        }
1701    }
1702
1703    /// Inserts a key-value pair at the head and returns the pointer and any
1704    /// previous value.
1705    ///
1706    /// This method is similar to `insert_full` but with explicit head
1707    /// positioning behavior:
1708    ///
1709    /// - If the key is new, the entry is inserted at the head
1710    /// - If the key exists, the value is updated AND the entry is moved to the
1711    ///   head
1712    ///
1713    /// This is useful when you want to ensure that updated entries are moved to
1714    /// the most recent position at the beginning of the list, implementing
1715    /// MRU (Most Recently Used) behavior or priority queuing where recent
1716    /// updates should be processed first.
1717    ///
1718    /// # Arguments
1719    ///
1720    /// * `key` - The key to insert or update
1721    /// * `value` - The value to insert
1722    ///
1723    /// # Returns
1724    ///
1725    /// A tuple containing:
1726    /// - `Ptr` - The pointer to the inserted or updated entry
1727    /// - `Option<T>` - `Some(old_value)` if the key existed, `None` if it was
1728    ///   newly inserted
1729    ///
1730    /// # Examples
1731    ///
1732    /// ```
1733    /// use tether_map::LinkedHashMap;
1734    ///
1735    /// let mut map = LinkedHashMap::new();
1736    /// map.insert("a", 1);
1737    /// map.insert("b", 2);
1738    /// map.insert("c", 3);
1739    ///
1740    /// // Update existing entry - it moves to head
1741    /// let (ptr, old) = map.insert_head_full("b", 20);
1742    /// assert_eq!(old, Some(2));
1743    ///
1744    /// // Order is now: b (with updated value), a, c
1745    /// let entries: Vec<_> = map.iter().collect();
1746    /// assert_eq!(entries, [(&"b", &20), (&"a", &1), (&"c", &3)]);
1747    /// ```
1748    #[inline]
1749    pub fn insert_head_full(
1750        &mut self,
1751        key: K,
1752        value: T,
1753    ) -> (Ptr, Option<T>) {
1754        let entry = self.entry(key);
1755        match entry {
1756            Entry::Occupied(occupied_entry) => {
1757                let ptr = occupied_entry.ptr();
1758                let old = occupied_entry.insert_no_move(value);
1759                self.move_to_head(ptr);
1760                (ptr, Some(old))
1761            }
1762            Entry::Vacant(vacant_entry) => {
1763                let (ptr, _) = vacant_entry.insert_head(value);
1764                (ptr, None)
1765            }
1766        }
1767    }
1768
1769    /// Creates a mutable cursor positioned at the entry with the given key.
1770    ///
1771    /// This method performs a hash table lookup to find the entry with the
1772    /// specified key, then returns a cursor positioned at that entry.
1773    ///
1774    /// # Arguments
1775    ///
1776    /// * `key` - The key to search for
1777    ///
1778    /// # Returns
1779    ///
1780    /// A `CursorMut` positioned at the entry with the given key. If the key is
1781    /// not found, the cursor will be positioned at a null entry.
1782    ///
1783    /// # Examples
1784    ///
1785    /// ```
1786    /// use tether_map::LinkedHashMap;
1787    ///
1788    /// let mut map = LinkedHashMap::new();
1789    /// map.insert_tail("a", 1);
1790    /// map.insert_tail("b", 2);
1791    ///
1792    /// let mut cursor = map.key_cursor_mut(&"a");
1793    /// if let Some((key, value)) = cursor.current_mut() {
1794    ///     assert_eq!(key, &"a");
1795    ///     *value = 42;
1796    /// }
1797    /// ```
1798    #[inline]
1799    pub fn key_cursor_mut<Q>(
1800        &'_ mut self,
1801        key: &Q,
1802    ) -> CursorMut<'_, K, T, S>
1803    where
1804        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
1805    {
1806        let hash = self.hasher.hash_one(key);
1807        let ptr = self
1808            .table
1809            .find(hash, |k| k.data(&self.nodes).key.equivalent(key))
1810            .copied();
1811        CursorMut { ptr, map: self }
1812    }
1813
1814    /// Gets the given key's corresponding entry in the map for in-place
1815    /// manipulation.
1816    ///
1817    /// This method provides an efficient way to insert, update, or
1818    /// conditionally modify entries without performing multiple lookups.
1819    /// The entry API is particularly useful for complex operations that
1820    /// depend on whether a key exists.
1821    ///
1822    /// # Arguments
1823    ///
1824    /// * `key` - The key to get the entry for
1825    ///
1826    /// # Returns
1827    ///
1828    /// An `Entry` enum which can be either:
1829    /// - `Entry::Occupied` if the key exists, providing access to the existing
1830    ///   value
1831    /// - `Entry::Vacant` if the key doesn't exist, allowing insertion of a new
1832    ///   value
1833    ///
1834    /// # Examples
1835    ///
1836    /// ```
1837    /// use tether_map::Entry;
1838    /// use tether_map::LinkedHashMap;
1839    ///
1840    /// let mut map = LinkedHashMap::new();
1841    ///
1842    /// // Insert a value if key doesn't exist
1843    /// match map.entry("key") {
1844    ///     Entry::Vacant(entry) => {
1845    ///         entry.insert_tail(42);
1846    ///     }
1847    ///     Entry::Occupied(_) => {
1848    ///         // Key already exists
1849    ///     }
1850    /// }
1851    ///
1852    /// // Update existing value or insert default
1853    /// let value = match map.entry("counter") {
1854    ///     Entry::Occupied(mut entry) => {
1855    ///         *entry.get_mut() += 1;
1856    ///         *entry.get()
1857    ///     }
1858    ///     Entry::Vacant(entry) => *entry.insert_tail(1).1,
1859    /// };
1860    /// ```
1861    #[inline]
1862    pub fn entry(
1863        &'_ mut self,
1864        key: K,
1865    ) -> Entry<'_, K, T> {
1866        let hash = self.hasher.hash_one(&key);
1867        match self.table.entry(
1868            hash,
1869            |k| k.data(&self.nodes).key == key,
1870            |e| self.hasher.hash_one(&e.data(&self.nodes).key),
1871        ) {
1872            hash_table::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry {
1873                arena: &mut self.nodes,
1874                head_tail: &mut self.head_tail,
1875                entry,
1876            }),
1877            hash_table::Entry::Vacant(entry) => Entry::Vacant(VacantEntry {
1878                entry,
1879                key,
1880                nodes: &mut self.nodes,
1881                head_tail: &mut self.head_tail,
1882            }),
1883        }
1884    }
1885
1886    /// Removes a key from the map, returning the value at the key if the key
1887    /// was previously in the map.
1888    ///
1889    /// # Examples
1890    ///
1891    /// ```
1892    /// use tether_map::LinkedHashMap;
1893    ///
1894    /// let mut map = LinkedHashMap::new();
1895    /// map.insert(1, "a");
1896    /// assert_eq!(map.remove(&1), Some("a"));
1897    /// assert_eq!(map.remove(&1), None);
1898    /// ```
1899    #[inline]
1900    pub fn remove<Q>(
1901        &mut self,
1902        key: &Q,
1903    ) -> Option<T>
1904    where
1905        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
1906    {
1907        self.remove_entry(key).map(|(_, v)| v)
1908    }
1909
1910    /// Removes a key from the map, returning the stored key and value if the
1911    /// key was previously in the map.
1912    ///
1913    /// # Examples
1914    ///
1915    /// ```
1916    /// use tether_map::LinkedHashMap;
1917    ///
1918    /// let mut map = LinkedHashMap::new();
1919    /// map.insert(1, "a");
1920    /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1921    /// assert_eq!(map.remove(&1), None);
1922    /// ```
1923    #[inline]
1924    pub fn remove_entry<Q>(
1925        &mut self,
1926        key: &Q,
1927    ) -> Option<(K, T)>
1928    where
1929        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
1930    {
1931        let (_, removed) = self.remove_full(key)?;
1932        Some((removed.key, removed.value))
1933    }
1934
1935    /// Removes a key from the map, returning the pointer to the removed entry
1936    /// and the stored key, value, and neighboring pointers if the key was  
1937    /// previously in the map.
1938    ///
1939    /// # Arguments
1940    ///
1941    /// * `key` - The key to remove from the map
1942    ///
1943    /// # Returns
1944    ///
1945    /// * `Some((Ptr, RemovedEntry<K, T>))` if the key was found and removed,
1946    ///   where `Ptr` is the pointer to the removed entry and `RemovedEntry<K
1947    /// , T>` contains the key, value, and neighboring pointers
1948    /// * `None` if the key was not found in the map
1949    ///
1950    /// # Examples
1951    ///
1952    /// ```
1953    /// use tether_map::LinkedHashMap;
1954    ///
1955    /// let mut map = LinkedHashMap::new();
1956    /// let (ptr, _) = map.insert_tail_full("a", 1);
1957    ///
1958    /// // Remove by key
1959    /// let result = map.remove_full(&"a");
1960    /// assert!(result.is_some());
1961    /// let (removed_ptr, removed_entry) = result.unwrap();
1962    /// assert_eq!(removed_ptr, ptr);
1963    /// assert_eq!(removed_entry.key, "a");
1964    /// assert_eq!(removed_entry.value, 1);
1965    /// assert_eq!(removed_entry.prev, None);
1966    /// assert_eq!(removed_entry.next, None);
1967    /// // Removing a non-existent key returns None
1968    /// assert_eq!(map.remove_full(&"b"), None);
1969    /// ```
1970    #[inline]
1971    pub fn remove_full<Q>(
1972        &mut self,
1973        key: &Q,
1974    ) -> Option<(Ptr, RemovedEntry<K, T>)>
1975    where
1976        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
1977    {
1978        if self.is_empty() {
1979            return None;
1980        }
1981
1982        let hash = self.hasher.hash_one(key);
1983        match self
1984            .table
1985            .find_entry(hash, |k| k.data(&self.nodes).key.equivalent(key))
1986        {
1987            Ok(occupied) => {
1988                let ptr = occupied.remove().0;
1989
1990                // SAFETY: We just removed ptr from our table, and we do not dereference
1991                // it after this point.
1992                let FreedSlot {
1993                    data,
1994                    this,
1995                    prev_next,
1996                } = unsafe { self.nodes.free_and_unlink(ptr) };
1997
1998                if let Some((prev, next)) = prev_next {
1999                    if let Some(head_tail) = self.head_tail.as_mut() {
2000                        if head_tail.head == ptr {
2001                            head_tail.head = next;
2002                        }
2003                        if head_tail.tail == ptr {
2004                            head_tail.tail = prev;
2005                        }
2006                    }
2007                } else if self
2008                    .head_tail
2009                    .as_ref()
2010                    .is_some_and(|ht| ht.head == ptr || ht.tail == ptr)
2011                {
2012                    self.head_tail = None;
2013                }
2014
2015                Some((
2016                    this,
2017                    RemovedEntry {
2018                        key: data.key,
2019                        value: data.value,
2020                        prev: prev_next.map(|(p, _)| p.this(&self.nodes)),
2021                        next: prev_next.map(|(_, n)| n.this(&self.nodes)),
2022                    },
2023                ))
2024            }
2025            Err(_) => None,
2026        }
2027    }
2028
2029    /// Returns the pointer to the entry with the given key.
2030    ///
2031    /// This method performs a hash table lookup to find the entry with the
2032    /// specified key and returns its pointer. The pointer can then be used
2033    /// for direct access operations or cursor positioning without
2034    /// additional key lookups.
2035    ///
2036    /// # Arguments
2037    ///
2038    /// * `key` - The key to search for
2039    ///
2040    /// # Returns
2041    ///
2042    /// * `Some(ptr)` if the key exists in the map
2043    /// * `None` if the key is not found
2044    ///
2045    /// # Examples
2046    ///
2047    /// ```
2048    /// use tether_map::LinkedHashMap;
2049    ///
2050    /// let mut map = LinkedHashMap::new();
2051    /// let (inserted_ptr, _) = map.insert_tail_full("key", 42);
2052    ///
2053    /// // Get pointer for the key
2054    /// let found_ptr = map.get_ptr(&"key").unwrap();
2055    /// assert_eq!(inserted_ptr, found_ptr);
2056    ///
2057    /// // Use the pointer for direct access
2058    /// assert_eq!(map.ptr_get(found_ptr), Some(&42));
2059    ///
2060    /// // Non-existent key returns None
2061    /// assert_eq!(map.get_ptr(&"missing"), None);
2062    /// ```
2063    #[inline]
2064    pub fn get_ptr<Q>(
2065        &self,
2066        key: &Q,
2067    ) -> Option<Ptr>
2068    where
2069        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
2070    {
2071        let hash = self.hasher.hash_one(key);
2072        self.table
2073            .find(hash, |k| k.data(&self.nodes).key.equivalent(key))
2074            .map(|ptr| ptr.this(&self.nodes))
2075    }
2076
2077    /// Returns a reference to the value corresponding to the key.
2078    ///
2079    /// The key may be any borrowed form of the map's key type, but
2080    /// `Hash` and `Eq` on the borrowed form must match those for the key type.
2081    ///
2082    /// # Examples
2083    ///
2084    /// ```
2085    /// use tether_map::LinkedHashMap;
2086    ///
2087    /// let mut map = LinkedHashMap::new();
2088    /// map.insert(1, "a");
2089    /// assert_eq!(map.get(&1), Some(&"a"));
2090    /// assert_eq!(map.get(&2), None);
2091    /// ```
2092    #[inline]
2093    pub fn get<Q>(
2094        &self,
2095        key: &Q,
2096    ) -> Option<&T>
2097    where
2098        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
2099    {
2100        self.table
2101            .find(self.hasher.hash_one(key), |k| {
2102                k.data(&self.nodes).key.equivalent(key)
2103            })
2104            .map(|ptr| &ptr.data(&self.nodes).value)
2105    }
2106
2107    /// Returns a mutable reference to the value corresponding to the key.
2108    ///
2109    /// The key may be any borrowed form of the map's key type, but
2110    /// `Hash` and `Eq` on the borrowed form must match those for the key type.
2111    ///
2112    /// # Examples
2113    ///
2114    /// ```
2115    /// use tether_map::LinkedHashMap;
2116    ///
2117    /// let mut map = LinkedHashMap::new();
2118    /// map.insert(1, "a");
2119    /// if let Some(x) = map.get_mut(&1) {
2120    ///     *x = "b";
2121    /// }
2122    /// assert_eq!(map.get(&1), Some(&"b"));
2123    /// ```
2124    #[inline]
2125    pub fn get_mut<Q>(
2126        &mut self,
2127        key: &Q,
2128    ) -> Option<&mut T>
2129    where
2130        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
2131    {
2132        self.table
2133            .find_mut(self.hasher.hash_one(key), |k| {
2134                k.data(&self.nodes).key.equivalent(key)
2135            })
2136            .map(|ptr| &mut ptr.data_mut(&mut self.nodes).value)
2137    }
2138
2139    /// Returns `true` if the map contains a value for the specified key.
2140    ///
2141    /// The key may be any borrowed form of the map's key type, but
2142    /// `Hash` and `Eq` on the borrowed form must match those for the key type.
2143    ///
2144    /// # Examples
2145    ///
2146    /// ```
2147    /// use tether_map::LinkedHashMap;
2148    ///
2149    /// let mut map = LinkedHashMap::new();
2150    /// map.insert(1, "a");
2151    /// assert_eq!(map.contains_key(&1), true);
2152    /// assert_eq!(map.contains_key(&2), false);
2153    /// ```
2154    #[inline]
2155    pub fn contains_key<Q>(
2156        &self,
2157        key: &Q,
2158    ) -> bool
2159    where
2160        Q: Equivalent<K> + Hash + Borrow<K> + ?Sized,
2161    {
2162        self.get_ptr(key).is_some()
2163    }
2164}
2165
2166impl<K, T, S> Index<&K> for LinkedHashMap<K, T, S>
2167where
2168    K: Hash + Eq,
2169    S: BuildHasher,
2170{
2171    type Output = T;
2172
2173    #[inline]
2174    fn index(
2175        &self,
2176        key: &K,
2177    ) -> &Self::Output {
2178        self.get(key).expect("no entry found for key")
2179    }
2180}
2181
2182impl<K, T, S> IndexMut<&K> for LinkedHashMap<K, T, S>
2183where
2184    K: Hash + Eq,
2185    S: BuildHasher,
2186{
2187    #[inline]
2188    fn index_mut(
2189        &mut self,
2190        key: &K,
2191    ) -> &mut Self::Output {
2192        self.get_mut(key).expect("no entry found for key")
2193    }
2194}
2195
2196impl<K, T, S> Index<Ptr> for LinkedHashMap<K, T, S> {
2197    type Output = T;
2198
2199    #[inline]
2200    fn index(
2201        &self,
2202        index: Ptr,
2203    ) -> &Self::Output {
2204        &self.nodes[index].value
2205    }
2206}
2207
2208impl<K, T, S> IndexMut<Ptr> for LinkedHashMap<K, T, S> {
2209    #[inline]
2210    fn index_mut(
2211        &mut self,
2212        index: Ptr,
2213    ) -> &mut Self::Output {
2214        &mut self.nodes[index].value
2215    }
2216}
2217
2218#[cfg(test)]
2219mod tests {
2220    use alloc::format;
2221    use alloc::string::ToString;
2222    use alloc::vec;
2223    use core::assert_eq;
2224    use core::panic;
2225
2226    use super::*;
2227    use crate::LinkedHashMap;
2228
2229    #[test]
2230    fn test_new_and_default() {
2231        let map: LinkedHashMap<i32, Vec<i32>> = LinkedHashMap::default();
2232        assert!(map.is_empty());
2233        assert_eq!(map.len(), 0);
2234        assert_eq!(map.head_ptr(), None);
2235        assert_eq!(map.tail_ptr(), None);
2236    }
2237
2238    #[test]
2239    fn test_with_capacity() {
2240        let map: LinkedHashMap<i32, Vec<i32>> = LinkedHashMap::with_capacity(10);
2241        assert!(map.is_empty());
2242        assert_eq!(map.len(), 0);
2243    }
2244
2245    #[test]
2246    fn test_clear() {
2247        let mut map = LinkedHashMap::default();
2248        map.insert_tail(1, vec![1]);
2249        map.insert_tail(2, vec![2]);
2250
2251        assert_eq!(map.len(), 2);
2252        assert!(!map.is_empty());
2253
2254        map.clear();
2255
2256        assert_eq!(map.len(), 0);
2257        assert!(map.is_empty());
2258        assert_eq!(map.head_ptr(), None);
2259        assert_eq!(map.tail_ptr(), None);
2260    }
2261
2262    #[test]
2263    fn test_insert_tail() {
2264        let mut map = LinkedHashMap::default();
2265
2266        let result = map.insert_tail(1, vec![1]);
2267        assert_eq!(result, None);
2268        assert_eq!(map.len(), 1);
2269        assert_eq!(map.get(&1), Some(&vec![1]));
2270        assert_eq!(map.head_ptr(), map.tail_ptr());
2271
2272        let result = map.insert_tail(2, vec![2]);
2273        assert_eq!(result, None);
2274        assert_eq!(map.len(), 2);
2275        assert_ne!(map.head_ptr(), map.tail_ptr());
2276
2277        map.insert_tail(3, vec![3]);
2278        assert_eq!(map.len(), 3);
2279
2280        let items: Vec<_> = map.iter().collect();
2281        assert_eq!(items, vec![(&1, &vec![1]), (&2, &vec![2]), (&3, &vec![3])]);
2282
2283        let result = map.insert_tail(2, vec![2]);
2284        assert_eq!(result, Some(vec![2]));
2285        assert_eq!(map.len(), 3);
2286        assert_eq!(map.get(&2), Some(&vec![2]));
2287
2288        let items: Vec<_> = map.iter().collect();
2289        assert_eq!(items, vec![(&1, &vec![1]), (&3, &vec![3]), (&2, &vec![2])]);
2290    }
2291
2292    #[test]
2293    fn test_insert_head() {
2294        let mut map = LinkedHashMap::default();
2295
2296        let result = map.insert_head(1, vec![1]);
2297        assert_eq!(result, None);
2298        assert_eq!(map.len(), 1);
2299        assert_eq!(map.get(&1), Some(&vec![1]));
2300        assert_eq!(map.head_ptr(), map.tail_ptr());
2301
2302        let result = map.insert_head(2, vec![2]);
2303        assert_eq!(result, None);
2304        assert_eq!(map.len(), 2);
2305        assert_ne!(map.head_ptr(), map.tail_ptr());
2306
2307        map.insert_head(3, vec![3]);
2308        assert_eq!(map.len(), 3);
2309
2310        let items: Vec<_> = map.iter().collect();
2311        assert_eq!(items, vec![(&3, &vec![3]), (&2, &vec![2]), (&1, &vec![1])]);
2312
2313        let result = map.insert_head(2, vec![2]);
2314        assert_eq!(result, Some(vec![2]));
2315        assert_eq!(map.len(), 3);
2316        assert_eq!(map.get(&2), Some(&vec![2]));
2317
2318        let items: Vec<_> = map.iter().collect();
2319        assert_eq!(items, vec![(&2, &vec![2]), (&3, &vec![3]), (&1, &vec![1])]);
2320    }
2321
2322    #[test]
2323    fn test_mixed_insertion() {
2324        let mut map = LinkedHashMap::default();
2325
2326        map.insert_tail(1, "one");
2327        map.insert_head(2, "two");
2328        map.insert_tail(3, "three");
2329        map.insert_head(4, "four");
2330
2331        let items: Vec<_> = map.iter().collect();
2332        assert_eq!(
2333            items,
2334            vec![(&4, &"four"), (&2, &"two"), (&1, &"one"), (&3, &"three")]
2335        );
2336        assert_eq!(map.len(), 4);
2337    }
2338
2339    #[test]
2340    fn test_get_operations() {
2341        let mut map = LinkedHashMap::default();
2342        map.insert_tail(1, vec![1]);
2343        map.insert_tail(2, vec![2]);
2344        map.insert_tail(3, vec![3]);
2345
2346        assert_eq!(map.get(&1), Some(&vec![1]));
2347        assert_eq!(map.get(&2), Some(&vec![2]));
2348        assert_eq!(map.get(&3), Some(&vec![3]));
2349        assert_eq!(map.get(&4), None);
2350
2351        let value = map.get_mut(&2).unwrap();
2352        *value = vec![2];
2353        assert_eq!(map.get(&2), Some(&vec![2]));
2354
2355        assert!(map.contains_key(&1));
2356        assert!(map.contains_key(&2));
2357        assert!(map.contains_key(&3));
2358        assert!(!map.contains_key(&4));
2359        assert!(!map.contains_key(&0));
2360    }
2361
2362    #[test]
2363    fn test_get_ptr_operations() {
2364        let mut map = LinkedHashMap::default();
2365        map.insert_tail(1, vec![1]);
2366        map.insert_tail(2, vec![2]);
2367
2368        let ptr1 = map.get_ptr(&1).unwrap();
2369        let ptr2 = map.get_ptr(&2).unwrap();
2370        assert_ne!(ptr1, ptr2);
2371        assert_eq!(map.get_ptr(&99), None);
2372
2373        assert_eq!(map.ptr_get(ptr1), Some(&vec![1]));
2374        assert_eq!(map.ptr_get(ptr2), Some(&vec![2]));
2375
2376        let value = map.ptr_get_mut(ptr1).unwrap();
2377        *value = vec![1];
2378        assert_eq!(map.ptr_get(ptr1), Some(&vec![1]));
2379
2380        let (key, value) = map.ptr_get_entry(ptr1).unwrap();
2381        assert_eq!(key, &1);
2382        assert_eq!(value, &vec![1]);
2383
2384        let (key, value) = map.ptr_get_entry_mut(ptr2).unwrap();
2385        assert_eq!(key, &2);
2386        *value = vec![2];
2387        assert_eq!(map.get(&2), Some(&vec![2]));
2388
2389        assert_eq!(map.ptr_get_key(ptr1), Some(&1));
2390        assert_eq!(map.ptr_get_key(ptr2), Some(&2));
2391
2392        assert!(map.contains_ptr(ptr1));
2393        assert!(map.contains_ptr(ptr2));
2394    }
2395
2396    #[test]
2397    fn test_index_operations() {
2398        let mut map = LinkedHashMap::default();
2399        map.insert_tail(1, vec![1]);
2400        map.insert_tail(2, vec![2]);
2401
2402        let ptr1 = map.get_ptr(&1).unwrap();
2403        let ptr2 = map.get_ptr(&2).unwrap();
2404
2405        assert_eq!(&map[ptr1], &vec![1]);
2406        assert_eq!(&map[ptr2], &vec![2]);
2407
2408        map[ptr1] = vec![1];
2409        assert_eq!(&map[ptr1], &vec![1]);
2410        assert_eq!(map.get(&1), Some(&vec![1]));
2411    }
2412
2413    #[test]
2414    fn test_remove_by_key() {
2415        let mut map: LinkedHashMap<i32, Vec<i32>> = LinkedHashMap::default();
2416        map.insert_tail(1, vec![1]);
2417        map.insert_tail(2, vec![2]);
2418        map.insert_tail(3, vec![3]);
2419
2420        let removed = map.remove_full(&2).unwrap().1;
2421        assert_eq!(
2422            removed,
2423            RemovedEntry {
2424                key: 2,
2425                value: vec![2],
2426                prev: map.get_ptr(&1),
2427                next: map.get_ptr(&3),
2428            }
2429        );
2430        assert_eq!(map.len(), 2);
2431        assert!(!map.contains_key(&2));
2432
2433        let items: Vec<_> = map.iter().collect();
2434        assert_eq!(items, vec![(&1, &vec![1]), (&3, &vec![3])]);
2435
2436        let removed = map.remove_full(&1).unwrap().1;
2437        assert_eq!(
2438            removed,
2439            RemovedEntry {
2440                key: 1,
2441                value: vec![1],
2442                prev: map.get_ptr(&3),
2443                next: map.get_ptr(&3),
2444            }
2445        );
2446        assert_eq!(map.len(), 1);
2447        assert_eq!(map.head_ptr(), map.tail_ptr());
2448
2449        let removed = map.remove_full(&3).unwrap().1;
2450        assert_eq!(
2451            removed,
2452            RemovedEntry {
2453                key: 3,
2454                value: vec![3],
2455                prev: None,
2456                next: None,
2457            }
2458        );
2459        assert_eq!(map.len(), 0);
2460        assert!(map.is_empty());
2461        assert_eq!(map.head_ptr(), None);
2462        assert_eq!(map.tail_ptr(), None);
2463
2464        let removed = map.remove(&1);
2465        assert_eq!(removed, None);
2466    }
2467
2468    #[test]
2469    fn test_remove_by_ptr() {
2470        let mut map = LinkedHashMap::default();
2471        map.insert_tail(1, vec![1]);
2472        map.insert_tail(2, vec![2]);
2473        map.insert_tail(3, vec![3]);
2474
2475        let removed = map.remove_ptr(map.get_ptr(&2).unwrap());
2476        assert_eq!(
2477            removed,
2478            Some(RemovedEntry {
2479                key: 2,
2480                value: vec![2],
2481                prev: map.get_ptr(&1),
2482                next: map.get_ptr(&3),
2483            })
2484        );
2485        assert_eq!(map.len(), 2);
2486        assert!(!map.contains_key(&2));
2487
2488        let removed = map.remove_ptr(map.get_ptr(&1).unwrap());
2489        assert_eq!(
2490            removed,
2491            Some(RemovedEntry {
2492                key: 1,
2493                value: vec![1],
2494                prev: map.get_ptr(&3),
2495                next: map.get_ptr(&3),
2496            })
2497        );
2498        assert_eq!(map.len(), 1);
2499        assert_eq!(map.head_ptr(), map.get_ptr(&3));
2500        assert_eq!(map.tail_ptr(), map.get_ptr(&3));
2501
2502        let removed = map.remove_ptr(map.get_ptr(&3).unwrap());
2503        assert_eq!(
2504            removed,
2505            Some(RemovedEntry {
2506                key: 3,
2507                value: vec![3],
2508                prev: None,
2509                next: None,
2510            })
2511        );
2512        assert!(map.is_empty());
2513    }
2514
2515    #[test]
2516    fn test_remove_single_element() {
2517        let mut map = LinkedHashMap::default();
2518        map.insert_tail(42, vec![42]);
2519
2520        assert_eq!(map.len(), 1);
2521        assert_eq!(map.head_ptr(), map.tail_ptr());
2522
2523        let removed = map.remove_full(&42).unwrap().1;
2524        assert_eq!(
2525            removed,
2526            RemovedEntry {
2527                key: 42,
2528                value: vec![42],
2529                prev: None,
2530                next: None,
2531            }
2532        );
2533        assert!(map.is_empty());
2534        assert_eq!(map.head_ptr(), None);
2535        assert_eq!(map.tail_ptr(), None);
2536    }
2537
2538    #[test]
2539    fn test_remove_head_and_tail() {
2540        let mut map = LinkedHashMap::default();
2541        for i in 1..=5 {
2542            map.insert_tail(i, vec![1]);
2543        }
2544
2545        let removed = map.remove_full(&1).unwrap().1;
2546        assert_eq!(
2547            removed,
2548            RemovedEntry {
2549                key: 1,
2550                value: vec![1],
2551                prev: map.get_ptr(&5),
2552                next: map.get_ptr(&2),
2553            }
2554        );
2555        assert_eq!(map.tail_ptr(), map.get_ptr(&5));
2556
2557        let removed = map.remove_full(&5).unwrap().1;
2558        assert_eq!(
2559            removed,
2560            RemovedEntry {
2561                key: 5,
2562                value: vec![1],
2563                prev: map.get_ptr(&4),
2564                next: map.get_ptr(&2),
2565            }
2566        );
2567        assert_eq!(map.len(), 3);
2568
2569        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2570        assert_eq!(items, vec![2, 3, 4]);
2571    }
2572
2573    #[test]
2574    fn test_move_to_head() {
2575        let mut map = LinkedHashMap::default();
2576        for i in 1..=4 {
2577            map.insert_tail(i, format!("value{}", i));
2578        }
2579
2580        let ptr3 = map.get_ptr(&3).unwrap();
2581
2582        map.move_to_head(ptr3);
2583
2584        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2585        assert_eq!(items, vec![3, 1, 2, 4]);
2586        assert_eq!(map.head_ptr(), Some(ptr3));
2587
2588        let old_head = map.head_ptr().unwrap();
2589        map.move_to_head(old_head);
2590        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2591        assert_eq!(items, vec![3, 1, 2, 4]);
2592
2593        let ptr4 = map.get_ptr(&4).unwrap();
2594        map.move_to_head(ptr4).unwrap();
2595
2596        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2597        assert_eq!(items, vec![4, 3, 1, 2]);
2598        assert_eq!(map.head_ptr(), Some(ptr4));
2599    }
2600
2601    #[test]
2602    fn test_move_to_tail() {
2603        let mut map = LinkedHashMap::default();
2604        for i in 1..=4 {
2605            map.insert_tail(i, format!("value{}", i));
2606        }
2607
2608        let ptr2 = map.get_ptr(&2).unwrap();
2609
2610        map.move_to_tail(ptr2);
2611
2612        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2613        assert_eq!(items, vec![1, 3, 4, 2]);
2614        assert_eq!(map.tail_ptr(), Some(ptr2));
2615
2616        let old_tail = map.tail_ptr().unwrap();
2617        map.move_to_tail(old_tail);
2618        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2619        assert_eq!(items, vec![1, 3, 4, 2]);
2620
2621        let ptr1 = map.get_ptr(&1).unwrap();
2622        map.move_to_tail(ptr1);
2623
2624        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2625        assert_eq!(items, vec![3, 4, 2, 1]);
2626        assert_eq!(map.tail_ptr(), Some(ptr1));
2627    }
2628
2629    #[test]
2630    fn test_move_after() {
2631        let mut map = LinkedHashMap::default();
2632        for i in 1..=5 {
2633            map.insert_tail(i, format!("value{}", i));
2634        }
2635
2636        let ptr1 = map.get_ptr(&1).unwrap();
2637        let ptr3 = map.get_ptr(&3).unwrap();
2638        let ptr5 = map.get_ptr(&5).unwrap();
2639
2640        map.move_after(ptr5, ptr1);
2641        assert_eq!(map.next_ptr(ptr1), Some(ptr5));
2642        assert_eq!(map.prev_ptr(ptr5), Some(ptr1));
2643        assert_eq!(map.next_ptr(ptr5), map.get_ptr(&2));
2644        assert_eq!(map.prev_ptr(map.get_ptr(&2).unwrap()), Some(ptr5));
2645        assert_eq!(map.next_ptr(ptr3), map.get_ptr(&4));
2646        assert_eq!(map.prev_ptr(map.get_ptr(&4).unwrap()), Some(ptr3));
2647
2648        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2649        assert_eq!(items, vec![1, 5, 2, 3, 4]);
2650
2651        let ptr2 = map.get_ptr(&2).unwrap();
2652        let ptr4 = map.get_ptr(&4).unwrap();
2653        map.move_after(ptr2, ptr4);
2654        assert_eq!(map.next_ptr(ptr4), Some(ptr2));
2655        assert_eq!(map.prev_ptr(ptr2), Some(ptr4));
2656        assert_eq!(map.next_ptr(ptr5), Some(ptr3));
2657        assert_eq!(map.prev_ptr(ptr3), Some(ptr5));
2658
2659        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2660        assert_eq!(items, vec![1, 5, 3, 4, 2]);
2661
2662        map.move_after(ptr3, ptr3);
2663        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2664        assert_eq!(items, vec![1, 5, 3, 4, 2]);
2665
2666        map.move_after(ptr4, ptr3);
2667        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2668        assert_eq!(items, vec![1, 5, 3, 4, 2]);
2669    }
2670
2671    #[test]
2672    fn test_move_before() {
2673        let mut map = LinkedHashMap::default();
2674        for i in 1..=5 {
2675            map.insert_tail(i, format!("value{}", i));
2676        }
2677
2678        let ptr1 = map.get_ptr(&1).unwrap();
2679        let ptr3 = map.get_ptr(&3).unwrap();
2680        let ptr5 = map.get_ptr(&5).unwrap();
2681
2682        map.move_before(ptr5, ptr3);
2683
2684        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2685        assert_eq!(items, vec![1, 2, 5, 3, 4]);
2686
2687        let ptr4 = map.get_ptr(&4).unwrap();
2688        map.move_before(ptr1, ptr4);
2689
2690        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2691        assert_eq!(items, vec![2, 5, 3, 1, 4]);
2692
2693        map.move_before(ptr3, ptr3);
2694        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2695        assert_eq!(items, vec![2, 5, 3, 1, 4]);
2696
2697        let ptr2 = map.get_ptr(&2).unwrap();
2698        map.move_before(ptr2, ptr5);
2699        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2700        assert_eq!(items, vec![2, 5, 3, 1, 4]);
2701    }
2702
2703    #[test]
2704    fn test_pointer_navigation() {
2705        let mut map = LinkedHashMap::default();
2706        for i in 1..=3 {
2707            map.insert_tail(i, format!("value{}", i));
2708        }
2709
2710        let ptr1 = map.get_ptr(&1).unwrap();
2711        let ptr2 = map.get_ptr(&2).unwrap();
2712        let ptr3 = map.get_ptr(&3).unwrap();
2713
2714        assert_eq!(map.next_ptr(ptr1), Some(ptr2));
2715        assert_eq!(map.next_ptr(ptr2), Some(ptr3));
2716        assert_eq!(map.next_ptr(ptr3), Some(ptr1));
2717
2718        assert_eq!(map.prev_ptr(ptr1), Some(ptr3));
2719        assert_eq!(map.prev_ptr(ptr2), Some(ptr1));
2720        assert_eq!(map.prev_ptr(ptr3), Some(ptr2));
2721    }
2722
2723    #[test]
2724    fn test_move_operations_edge_cases() {
2725        let mut map = LinkedHashMap::default();
2726
2727        map.insert_tail(1, "one");
2728        let ptr1 = map.get_ptr(&1).unwrap();
2729
2730        map.move_to_head(ptr1);
2731        assert_eq!(map.len(), 1);
2732        assert_eq!(map.head_ptr(), Some(ptr1));
2733        assert_eq!(map.tail_ptr(), Some(ptr1));
2734
2735        map.move_to_tail(ptr1);
2736        assert_eq!(map.len(), 1);
2737        assert_eq!(map.head_ptr(), Some(ptr1));
2738        assert_eq!(map.tail_ptr(), Some(ptr1));
2739    }
2740
2741    #[test]
2742    fn test_iter() {
2743        let mut map = LinkedHashMap::default();
2744
2745        let items: Vec<_> = map.iter().collect();
2746        assert_eq!(items, vec![]);
2747
2748        for i in 1..=4 {
2749            map.insert_tail(i, vec![i]);
2750        }
2751
2752        let items: Vec<_> = map.iter().collect();
2753        assert_eq!(
2754            items,
2755            vec![
2756                (&1, &vec![1]),
2757                (&2, &vec![2]),
2758                (&3, &vec![3]),
2759                (&4, &vec![4])
2760            ]
2761        );
2762
2763        map.insert_head(0, vec![0]);
2764        let items: Vec<_> = map.iter().collect();
2765        assert_eq!(
2766            items,
2767            vec![
2768                (&0, &vec![0]),
2769                (&1, &vec![1]),
2770                (&2, &vec![2]),
2771                (&3, &vec![3]),
2772                (&4, &vec![4])
2773            ]
2774        );
2775    }
2776
2777    #[test]
2778    fn test_iter_rev() {
2779        let mut map = LinkedHashMap::default();
2780
2781        let items: Vec<_> = map.iter().rev().collect();
2782        assert_eq!(items, vec![]);
2783
2784        for i in 1..=4 {
2785            map.insert_tail(i, format!("value{}", i));
2786        }
2787
2788        let items: Vec<_> = map.iter().rev().collect();
2789        assert_eq!(
2790            items,
2791            vec![
2792                (&4, &"value4".to_string()),
2793                (&3, &"value3".to_string()),
2794                (&2, &"value2".to_string()),
2795                (&1, &"value1".to_string())
2796            ]
2797        );
2798
2799        map.insert_head(0, "value0".to_string());
2800        let items: Vec<_> = map.iter().rev().collect();
2801        assert_eq!(
2802            items,
2803            vec![
2804                (&4, &"value4".to_string()),
2805                (&3, &"value3".to_string()),
2806                (&2, &"value2".to_string()),
2807                (&1, &"value1".to_string()),
2808                (&0, &"value0".to_string())
2809            ]
2810        );
2811    }
2812
2813    #[test]
2814    fn test_into_iter() {
2815        let mut map = LinkedHashMap::default();
2816
2817        for i in 1..=4 {
2818            map.insert_tail(i, format!("value{}", i));
2819        }
2820
2821        let items: Vec<_> = map.into_iter().collect();
2822        assert_eq!(
2823            items,
2824            vec![
2825                (1, "value1".to_string()),
2826                (2, "value2".to_string()),
2827                (3, "value3".to_string()),
2828                (4, "value4".to_string())
2829            ]
2830        );
2831    }
2832
2833    #[test]
2834    fn test_into_iter_rev() {
2835        let mut map = LinkedHashMap::default();
2836
2837        for i in 1..=4 {
2838            map.insert_tail(i, format!("value{}", i));
2839        }
2840
2841        let items: Vec<_> = map.into_iter().rev().collect();
2842        assert_eq!(
2843            items,
2844            vec![
2845                (4, "value4".to_string()),
2846                (3, "value3".to_string()),
2847                (2, "value2".to_string()),
2848                (1, "value1".to_string())
2849            ]
2850        );
2851    }
2852
2853    #[test]
2854    fn test_iteration_after_modifications() {
2855        let mut map = LinkedHashMap::default();
2856        for i in 1..=5 {
2857            map.insert_tail(i, format!("value{}", i));
2858        }
2859
2860        map.remove(&3);
2861
2862        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2863        assert_eq!(items, vec![1, 2, 4, 5]);
2864
2865        let ptr2 = map.get_ptr(&2).unwrap();
2866        map.move_to_tail(ptr2);
2867
2868        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
2869        assert_eq!(items, vec![1, 4, 5, 2]);
2870
2871        let items: Vec<_> = map.iter().rev().map(|(k, _)| *k).collect();
2872        assert_eq!(items, vec![2, 5, 4, 1]);
2873    }
2874
2875    #[test]
2876    fn test_empty_iteration() {
2877        let map: LinkedHashMap<i32, Vec<i32>> = LinkedHashMap::default();
2878
2879        assert_eq!(map.iter().count(), 0);
2880        assert_eq!(map.iter().rev().count(), 0);
2881
2882        let empty_map: LinkedHashMap<i32, Vec<i32>> = LinkedHashMap::default();
2883        assert_eq!(empty_map.into_iter().count(), 0);
2884
2885        let empty_map: LinkedHashMap<i32, Vec<i32>> = LinkedHashMap::default();
2886        assert_eq!(empty_map.into_iter().rev().count(), 0);
2887    }
2888
2889    #[test]
2890    fn test_single_element_iteration() {
2891        let mut map = LinkedHashMap::default();
2892        map.insert_tail(42, "answer".to_string());
2893
2894        let items: Vec<_> = map.iter().collect();
2895        assert_eq!(items, vec![(&42, &"answer".to_string())]);
2896
2897        let items: Vec<_> = map.iter().rev().collect();
2898        assert_eq!(items, vec![(&42, &"answer".to_string())]);
2899    }
2900
2901    #[test]
2902    fn test_entry_api_vacant() {
2903        let mut map = LinkedHashMap::default();
2904
2905        match map.entry(1) {
2906            Entry::Vacant(entry) => {
2907                assert_eq!(entry.key(), &1);
2908                let value = entry.insert_tail(vec![1]).1;
2909                assert_eq!(value, &vec![1]);
2910            }
2911            Entry::Occupied(_) => panic!("Expected vacant entry"),
2912        }
2913
2914        assert_eq!(map.len(), 1);
2915        assert_eq!(map.get(&1), Some(&vec![1]));
2916
2917        match map.entry(2) {
2918            Entry::Vacant(entry) => {
2919                let key = entry.into_key();
2920                assert_eq!(key, 2);
2921            }
2922            Entry::Occupied(_) => panic!("Expected vacant entry"),
2923        }
2924
2925        assert_eq!(map.len(), 1);
2926        assert!(!map.contains_key(&2));
2927    }
2928
2929    #[test]
2930    fn test_entry_api_occupied() {
2931        let mut map = LinkedHashMap::default();
2932        map.insert_tail(1, vec![1]);
2933        map.insert_tail(2, vec![2]);
2934
2935        match map.entry(1) {
2936            Entry::Occupied(entry) => {
2937                assert_eq!(entry.key(), &1);
2938                assert_eq!(entry.get(), &vec![1]);
2939            }
2940            Entry::Vacant(_) => panic!("Expected occupied entry"),
2941        }
2942
2943        match map.entry(2) {
2944            Entry::Occupied(mut entry) => {
2945                let value = entry.get_mut();
2946                *value = vec![2];
2947            }
2948            Entry::Vacant(_) => panic!("Expected occupied entry"),
2949        }
2950
2951        assert_eq!(map.get(&2), Some(&vec![2]));
2952
2953        match map.entry(1) {
2954            Entry::Occupied(entry) => {
2955                let old_value = entry.insert_no_move(vec![1]);
2956                assert_eq!(old_value, vec![1]);
2957            }
2958            Entry::Vacant(_) => panic!("Expected occupied entry"),
2959        }
2960
2961        assert_eq!(map.get(&1), Some(&vec![1]));
2962        assert_eq!(map.len(), 2);
2963    }
2964
2965    #[test]
2966    fn test_entry_api_mixed_operations() {
2967        let mut map = LinkedHashMap::default();
2968
2969        for i in 1..=3 {
2970            match map.entry(i) {
2971                Entry::Vacant(entry) => {
2972                    entry.insert_tail(format!("value{}", i));
2973                }
2974                Entry::Occupied(_) => panic!("Unexpected occupied entry"),
2975            }
2976        }
2977
2978        assert_eq!(map.len(), 3);
2979
2980        match map.entry(2) {
2981            Entry::Occupied(entry) => {
2982                entry.insert_no_move("updated".to_string());
2983            }
2984            Entry::Vacant(_) => panic!("Expected occupied entry"),
2985        }
2986
2987        let items: Vec<_> = map.iter().collect();
2988        assert_eq!(
2989            items,
2990            vec![
2991                (&1, &"value1".to_string()),
2992                (&2, &"updated".to_string()),
2993                (&3, &"value3".to_string())
2994            ]
2995        );
2996    }
2997
2998    #[test]
2999    fn test_cursor_mut_basic_operations() {
3000        let mut map = LinkedHashMap::default();
3001        for i in 1..=4 {
3002            map.insert_tail(i, format!("value{}", i));
3003        }
3004
3005        let mut cursor = map.head_cursor_mut();
3006        assert_eq!(cursor.current(), Some((&1, &"value1".to_string())));
3007
3008        cursor.move_next();
3009        assert_eq!(cursor.current(), Some((&2, &"value2".to_string())));
3010
3011        cursor.move_next();
3012        assert_eq!(cursor.current(), Some((&3, &"value3".to_string())));
3013
3014        cursor.move_prev();
3015        assert_eq!(cursor.current(), Some((&2, &"value2".to_string())));
3016
3017        let mut cursor = map.tail_cursor_mut();
3018        assert_eq!(cursor.current(), Some((&4, &"value4".to_string())));
3019
3020        cursor.move_prev();
3021        assert_eq!(cursor.current(), Some((&3, &"value3".to_string())));
3022    }
3023
3024    #[test]
3025    fn test_cursor_mut_current_operations() {
3026        let mut map = LinkedHashMap::default();
3027        map.insert_tail(1, vec![1]);
3028        map.insert_tail(2, vec![2]);
3029
3030        let mut cursor = map.key_cursor_mut(&1);
3031
3032        if let Some((key, value)) = cursor.current_mut() {
3033            assert_eq!(key, &1);
3034            *value = vec![1];
3035        }
3036
3037        assert_eq!(map.get(&1), Some(&vec![1]));
3038    }
3039
3040    #[test]
3041    fn test_cursor_mut_next_prev_operations() {
3042        let mut map = LinkedHashMap::default();
3043        for i in 1..=3 {
3044            map.insert_tail(i, format!("value{}", i));
3045        }
3046
3047        let mut cursor = map.head_cursor_mut();
3048
3049        assert_eq!(cursor.next(), Some((&2, &"value2".to_string())));
3050
3051        if let Some((key, value)) = cursor.next_mut() {
3052            assert_eq!(key, &2);
3053            *value = "VALUE2".to_string();
3054        }
3055
3056        cursor.move_next();
3057        cursor.move_next();
3058
3059        assert_eq!(cursor.prev(), Some((&2, &"VALUE2".to_string())));
3060
3061        if let Some((key, value)) = cursor.prev_mut() {
3062            assert_eq!(key, &2);
3063            *value = "value2_updated".to_string();
3064        }
3065
3066        assert_eq!(map.get(&2), Some(&"value2_updated".to_string()));
3067    }
3068
3069    #[test]
3070    fn test_cursor_mut_insert_after_move_to() {
3071        let mut map = LinkedHashMap::default();
3072        map.insert_tail(1, vec![1]);
3073        map.insert_tail(3, vec![3]);
3074
3075        let mut cursor = map.key_cursor_mut(&1);
3076
3077        let old_value = cursor.insert_after_move_to(2, vec![2]);
3078        assert_eq!(old_value, None);
3079
3080        let items: Vec<_> = cursor.iter().map(|(k, _)| *k).collect();
3081        assert_eq!(items, vec![2, 3, 1]);
3082
3083        let old_value = cursor.insert_after_move_to(2, vec![2]);
3084        assert_eq!(old_value, Some(vec![2]));
3085
3086        assert_eq!(map.get(&2), Some(&vec![2]));
3087    }
3088
3089    #[test]
3090    fn test_cursor_mut_insert_before_move_to() {
3091        let mut map = LinkedHashMap::default();
3092        map.insert_tail(1, vec![1]);
3093        map.insert_tail(3, vec![3]);
3094
3095        let mut cursor = map.key_cursor_mut(&3);
3096
3097        let old_value = cursor.insert_before_move_to(2, vec![2]);
3098        assert_eq!(old_value, None);
3099
3100        let items: Vec<_> = cursor.iter().map(|(k, _)| *k).collect();
3101        assert_eq!(items, vec![2, 3, 1]);
3102
3103        let old_value = cursor.insert_before_move_to(2, vec![2]);
3104        assert_eq!(old_value, Some(vec![2]));
3105
3106        assert_eq!(map.get(&2), Some(&vec![2]));
3107    }
3108
3109    #[test]
3110    fn test_cursor_mut_remove_operations() {
3111        let mut map = LinkedHashMap::default();
3112        for i in 1..=5 {
3113            map.insert_tail(i, format!("value{}", i));
3114        }
3115
3116        let mut cursor = map.key_cursor_mut(&3);
3117
3118        let (_, removed) = cursor.remove_next().unwrap();
3119        assert_eq!(
3120            removed,
3121            RemovedEntry {
3122                key: 4,
3123                value: "value4".to_string(),
3124                prev: cursor.get_ptr(&3),
3125                next: cursor.get_ptr(&5),
3126            }
3127        );
3128
3129        let (_, removed) = cursor.remove_prev().unwrap();
3130        assert_eq!(
3131            removed,
3132            RemovedEntry {
3133                key: 2,
3134                value: "value2".to_string(),
3135                prev: cursor.get_ptr(&1),
3136                next: cursor.get_ptr(&3),
3137            }
3138        );
3139
3140        let (_, removed) = cursor.remove().unwrap();
3141        assert_eq!(
3142            removed,
3143            RemovedEntry {
3144                key: 3,
3145                value: "value3".to_string(),
3146                prev: map.get_ptr(&1),
3147                next: map.get_ptr(&5),
3148            }
3149        );
3150        assert!(!map.contains_key(&3));
3151
3152        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
3153        assert_eq!(items, vec![1, 5]);
3154    }
3155
3156    #[test]
3157    fn test_cursor_mut_remove_entry() {
3158        let mut map = LinkedHashMap::default();
3159        map.insert_tail(1, vec![1]);
3160        map.insert_tail(2, vec![2]);
3161
3162        let cursor = map.key_cursor_mut(&1);
3163        let (_, removed) = cursor.remove().unwrap();
3164        assert_eq!(
3165            removed,
3166            RemovedEntry {
3167                key: 1,
3168                value: vec![1],
3169                prev: map.get_ptr(&2),
3170                next: map.get_ptr(&2),
3171            }
3172        );
3173
3174        assert_eq!(map.len(), 1);
3175        assert!(!map.contains_key(&1));
3176        assert_eq!(map.get(&2), Some(&vec![2]));
3177    }
3178
3179    #[test]
3180    fn test_cursor_mut_empty_map() {
3181        let mut map: LinkedHashMap<i32, Vec<i32>> = LinkedHashMap::default();
3182
3183        let mut cursor = map.head_cursor_mut();
3184        assert_eq!(cursor.current(), None);
3185        assert_eq!(cursor.next(), None);
3186        assert_eq!(cursor.prev(), None);
3187        assert_eq!(cursor.next_ptr(), None);
3188        assert_eq!(cursor.prev_ptr(), None);
3189
3190        let old_value = cursor.insert_after_move_to(1, vec![1]);
3191        assert_eq!(old_value, None);
3192        assert_eq!(map.len(), 1);
3193        assert_eq!(map.get(&1), Some(&vec![1]));
3194    }
3195
3196    #[test]
3197    fn test_complex_movement_patterns() {
3198        let mut map = LinkedHashMap::default();
3199        for i in 1..=10 {
3200            map.insert_tail(i, i);
3201        }
3202
3203        let ptr5 = map.get_ptr(&5).unwrap();
3204        let ptr2 = map.get_ptr(&2).unwrap();
3205        let ptr8 = map.get_ptr(&8).unwrap();
3206
3207        map.move_after(ptr5, ptr8);
3208
3209        map.move_before(ptr2, ptr5);
3210
3211        map.move_to_head(ptr8);
3212
3213        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
3214        assert_eq!(items[0], 8);
3215        assert!(items.contains(&2));
3216        assert!(items.contains(&5));
3217        assert_eq!(map.len(), 10);
3218
3219        for i in 1..=10 {
3220            assert!(map.contains_key(&i));
3221        }
3222    }
3223
3224    #[test]
3225    fn test_iteration_consistency_after_modifications() {
3226        let mut map = LinkedHashMap::default();
3227        for i in 1..=5 {
3228            map.insert_tail(i, i * 10);
3229        }
3230
3231        map.remove(&3);
3232        if let Some(ptr) = map.get_ptr(&1) {
3233            map.move_to_tail(ptr);
3234        }
3235        map.insert_head(0, 0);
3236
3237        let forward: Vec<_> = map.iter().map(|(k, _)| *k).collect();
3238        let backward: Vec<_> = map.iter().rev().map(|(k, _)| *k).collect();
3239        let mut backward_rev = backward.clone();
3240        backward_rev.reverse();
3241
3242        assert_eq!(forward, backward_rev);
3243
3244        let map_clone = map.clone();
3245        let consumed: Vec<_> = map_clone.into_iter().map(|(k, _)| k).collect();
3246        assert_eq!(forward, consumed);
3247
3248        let consumed_rev: Vec<_> = map.into_iter().rev().map(|(k, _)| k).collect();
3249        assert_eq!(backward, consumed_rev);
3250    }
3251
3252    #[test]
3253    fn test_shrink_to_fit() {
3254        let mut map = LinkedHashMap::with_capacity(100);
3255
3256        for i in 1..=5 {
3257            map.insert_tail(i, format!("value{}", i));
3258        }
3259
3260        map.shrink_to_fit();
3261
3262        assert_eq!(map.len(), 5);
3263        for i in 1..=5 {
3264            assert_eq!(map.get(&i), Some(&format!("value{}", i)));
3265        }
3266
3267        map.insert_tail(6, "value6".to_string());
3268        assert_eq!(map.len(), 6);
3269    }
3270
3271    #[test]
3272    fn test_cursor_mut_with_ptr() {
3273        let mut map = LinkedHashMap::default();
3274        map.insert_tail(1, vec![1]);
3275        map.insert_tail(2, vec![2]);
3276
3277        let ptr1 = map.get_ptr(&1).unwrap();
3278        let mut cursor = map.ptr_cursor_mut(ptr1);
3279
3280        assert_eq!(cursor.ptr(), Some(ptr1));
3281        assert_eq!(cursor.current(), Some((&1, &vec![1])));
3282
3283        cursor.move_next();
3284        assert_eq!(cursor.current(), Some((&2, &vec![2])));
3285        assert_ne!(cursor.ptr(), Some(ptr1));
3286    }
3287
3288    #[test]
3289    fn test_cursor_mut_nonexistent_key() {
3290        let mut map = LinkedHashMap::default();
3291        map.insert_tail(1, vec![1]);
3292
3293        let mut cursor = map.key_cursor_mut(&999);
3294        assert_eq!(cursor.current(), None);
3295        assert_eq!(cursor.ptr(), None);
3296
3297        let old_value = cursor.insert_after_move_to(999, vec![999]);
3298        assert_eq!(old_value, None);
3299        assert_eq!(map.get(&999), Some(&vec![999]));
3300    }
3301
3302    #[test]
3303    fn test_comprehensive_ordering_invariants() {
3304        let mut map = LinkedHashMap::default();
3305
3306        for i in 1..=5 {
3307            map.insert_tail(i, i);
3308        }
3309
3310        map.insert_head(0, 0);
3311        map.remove(&3);
3312        if let Some(ptr) = map.get_ptr(&4) {
3313            map.move_to_head(ptr);
3314        }
3315        map.insert_tail(6, 6);
3316        if let Some(ptr) = map.get_ptr(&1) {
3317            map.move_to_tail(ptr);
3318        }
3319
3320        let items: Vec<_> = map.iter().map(|(k, _)| *k).collect();
3321        let head_key = map.ptr_get_entry(map.head_ptr().unwrap()).map(|(k, _)| *k);
3322        let tail_key = map.ptr_get_entry(map.tail_ptr().unwrap()).map(|(k, _)| *k);
3323
3324        assert_eq!(head_key, Some(items[0]));
3325        assert_eq!(tail_key, Some(items[items.len() - 1]));
3326
3327        let mut forward_ptrs = Vec::new();
3328        let mut current_ptr = map.head_ptr().unwrap();
3329        let mut looped = false;
3330        while !looped {
3331            forward_ptrs.push(current_ptr);
3332            current_ptr = map.next_ptr(current_ptr).unwrap();
3333            looped = current_ptr == map.head_ptr().unwrap();
3334        }
3335
3336        let mut backward_ptrs = Vec::new();
3337        let mut current_ptr = map.tail_ptr().unwrap();
3338        let mut looped = false;
3339        while !looped {
3340            backward_ptrs.push(current_ptr);
3341            current_ptr = map.prev_ptr(current_ptr).unwrap();
3342            looped = current_ptr == map.tail_ptr().unwrap();
3343        }
3344
3345        backward_ptrs.reverse();
3346        assert_eq!(forward_ptrs, backward_ptrs);
3347        assert_eq!(forward_ptrs.len(), map.len());
3348    }
3349
3350    #[test]
3351    fn test_iter_mut_basic_iteration() {
3352        let mut map = LinkedHashMap::default();
3353        for i in 1..=4 {
3354            map.insert_tail(i, i * 10);
3355        }
3356
3357        let mut iter = map.iter_mut();
3358
3359        let (k1, v1) = iter.next().unwrap();
3360        assert_eq!(*k1, 1);
3361        assert_eq!(*v1, 10);
3362        *v1 = 100;
3363
3364        let (k2, v2) = iter.next().unwrap();
3365        assert_eq!(*k2, 2);
3366        assert_eq!(*v2, 20);
3367        *v2 = 200;
3368
3369        let (k3, v3) = iter.next().unwrap();
3370        assert_eq!(*k3, 3);
3371        assert_eq!(*v3, 30);
3372
3373        let (k4, v4) = iter.next().unwrap();
3374        assert_eq!(*k4, 4);
3375        assert_eq!(*v4, 40);
3376
3377        assert!(iter.next().is_none());
3378
3379        assert_eq!(map.get(&1), Some(&100));
3380        assert_eq!(map.get(&2), Some(&200));
3381        assert_eq!(map.get(&3), Some(&30));
3382        assert_eq!(map.get(&4), Some(&40));
3383    }
3384
3385    #[test]
3386    fn test_iter_mut_backward_iteration() {
3387        let mut map = LinkedHashMap::default();
3388        for i in 1..=4 {
3389            map.insert_tail(i, format!("value{}", i));
3390        }
3391
3392        let mut iter = map.iter_mut();
3393
3394        let (k4, v4) = iter.next_back().unwrap();
3395        assert_eq!(*k4, 4);
3396        assert_eq!(*v4, "value4");
3397        *v4 = "VALUE4".to_string();
3398
3399        let (k3, v3) = iter.next_back().unwrap();
3400        assert_eq!(*k3, 3);
3401        assert_eq!(*v3, "value3");
3402
3403        let (k2, v2) = iter.next_back().unwrap();
3404        assert_eq!(*k2, 2);
3405        assert_eq!(*v2, "value2");
3406        *v2 = "VALUE2".to_string();
3407
3408        let (k1, v1) = iter.next_back().unwrap();
3409        assert_eq!(*k1, 1);
3410        assert_eq!(*v1, "value1");
3411
3412        assert!(iter.next_back().is_none());
3413
3414        assert_eq!(map.get(&1), Some(&"value1".to_string()));
3415        assert_eq!(map.get(&2), Some(&"VALUE2".to_string()));
3416        assert_eq!(map.get(&3), Some(&"value3".to_string()));
3417        assert_eq!(map.get(&4), Some(&"VALUE4".to_string()));
3418    }
3419
3420    #[test]
3421    fn test_iter_mut_bidirectional_iteration() {
3422        let mut map = LinkedHashMap::default();
3423        for i in 1..=6 {
3424            map.insert_tail(i, i * 10);
3425        }
3426
3427        let mut iter = map.iter_mut();
3428
3429        let (k1, v1) = iter.next().unwrap();
3430        assert_eq!(*k1, 1);
3431        *v1 = 11;
3432
3433        let (k6, v6) = iter.next_back().unwrap();
3434        assert_eq!(*k6, 6);
3435        *v6 = 66;
3436
3437        let (k2, v2) = iter.next().unwrap();
3438        assert_eq!(*k2, 2);
3439        *v2 = 22;
3440
3441        let (k5, v5) = iter.next_back().unwrap();
3442        assert_eq!(*k5, 5);
3443        *v5 = 55;
3444
3445        let (k3, v3) = iter.next().unwrap();
3446        assert_eq!(*k3, 3);
3447        *v3 = 33;
3448
3449        let (k4, v4) = iter.next_back().unwrap();
3450        assert_eq!(*k4, 4);
3451        *v4 = 44;
3452
3453        assert_eq!(iter.next(), None);
3454        assert_eq!(iter.next_back(), None);
3455
3456        assert_eq!(map.get(&1), Some(&11));
3457        assert_eq!(map.get(&2), Some(&22));
3458        assert_eq!(map.get(&3), Some(&33));
3459        assert_eq!(map.get(&4), Some(&44));
3460        assert_eq!(map.get(&5), Some(&55));
3461        assert_eq!(map.get(&6), Some(&66));
3462    }
3463
3464    #[test]
3465    fn test_iter_mut_empty_map() {
3466        use alloc::string::String;
3467        let mut map: LinkedHashMap<i32, String> = LinkedHashMap::default();
3468
3469        let mut iter = map.iter_mut();
3470        assert!(iter.next().is_none());
3471        assert!(iter.next_back().is_none());
3472
3473        assert!(map.is_empty());
3474    }
3475
3476    #[test]
3477    fn test_iter_mut_single_element() {
3478        let mut map = LinkedHashMap::default();
3479        map.insert_tail(42, "answer".to_string());
3480
3481        let mut iter = map.iter_mut();
3482
3483        let (key, value) = iter.next().unwrap();
3484        assert_eq!(*key, 42);
3485        assert_eq!(*value, "answer");
3486        *value = "ANSWER".to_string();
3487
3488        assert!(iter.next().is_none());
3489        assert!(iter.next_back().is_none());
3490
3491        assert_eq!(map.get(&42), Some(&"ANSWER".to_string()));
3492    }
3493
3494    #[test]
3495    fn test_iter_mut_single_element_backward() {
3496        let mut map = LinkedHashMap::default();
3497        map.insert_tail(42, vec![1, 2, 3]);
3498
3499        let mut iter = map.iter_mut();
3500
3501        let (key, value) = iter.next_back().unwrap();
3502        assert_eq!(*key, 42);
3503        assert_eq!(*value, vec![1, 2, 3]);
3504        value.push(4);
3505
3506        assert!(iter.next().is_none());
3507        assert!(iter.next_back().is_none());
3508
3509        assert_eq!(map.get(&42), Some(&vec![1, 2, 3, 4]));
3510    }
3511
3512    #[test]
3513    fn test_iter_mut_modification_patterns() {
3514        let mut map = LinkedHashMap::default();
3515        for i in 1..=5 {
3516            map.insert_tail(i, vec![i]);
3517        }
3518
3519        for (key, value) in map.iter_mut() {
3520            if *key % 2 == 0 {
3521                value.push(*key * 10);
3522            } else {
3523                value.clear();
3524                value.push(*key * 100);
3525            }
3526        }
3527
3528        assert_eq!(map.get(&1), Some(&vec![100]));
3529        assert_eq!(map.get(&2), Some(&vec![2, 20]));
3530        assert_eq!(map.get(&3), Some(&vec![300]));
3531        assert_eq!(map.get(&4), Some(&vec![4, 40]));
3532        assert_eq!(map.get(&5), Some(&vec![500]));
3533    }
3534
3535    #[test]
3536    fn test_iter_mut_complex_value_modifications() {
3537        let mut map = LinkedHashMap::default();
3538        map.insert_tail("first", vec!["a", "b"]);
3539        map.insert_tail("second", vec!["c", "d", "e"]);
3540        map.insert_tail("third", vec!["f"]);
3541
3542        for (key, value) in map.iter_mut() {
3543            match *key {
3544                "first" => {
3545                    value.reverse();
3546                    value.push("new");
3547                }
3548                "second" => {
3549                    value.retain(|&s| s != "d");
3550                }
3551                "third" => {
3552                    value.extend_from_slice(&["g", "h"]);
3553                }
3554                _ => {}
3555            }
3556        }
3557
3558        assert_eq!(map.get(&"first"), Some(&vec!["b", "a", "new"]));
3559        assert_eq!(map.get(&"second"), Some(&vec!["c", "e"]));
3560        assert_eq!(map.get(&"third"), Some(&vec!["f", "g", "h"]));
3561    }
3562
3563    #[test]
3564    fn test_values_mut_iterator() {
3565        let mut map = LinkedHashMap::default();
3566        for i in 1..=4 {
3567            map.insert_tail(i, i * 10);
3568        }
3569
3570        let mut values: Vec<_> = map.values_mut().collect();
3571
3572        for value in values.iter_mut() {
3573            **value += 5;
3574        }
3575
3576        for value in map.values_mut() {
3577            *value *= 2;
3578        }
3579
3580        assert_eq!(map.get(&1), Some(&30));
3581        assert_eq!(map.get(&2), Some(&50));
3582        assert_eq!(map.get(&3), Some(&70));
3583        assert_eq!(map.get(&4), Some(&90));
3584    }
3585
3586    #[test]
3587    fn test_values_mut_backward_iteration() {
3588        let mut map = LinkedHashMap::default();
3589        for i in 1..=3 {
3590            map.insert_tail(i, format!("value{}", i));
3591        }
3592
3593        let values: Vec<_> = map.values_mut().rev().collect();
3594
3595        assert_eq!(values.len(), 3);
3596        assert_eq!(*values[0], "value3");
3597        assert_eq!(*values[1], "value2");
3598        assert_eq!(*values[2], "value1");
3599
3600        for (i, value) in values.into_iter().enumerate() {
3601            *value = format!("modified{}", i);
3602        }
3603
3604        assert_eq!(map.get(&1), Some(&"modified2".to_string()));
3605        assert_eq!(map.get(&2), Some(&"modified1".to_string()));
3606        assert_eq!(map.get(&3), Some(&"modified0".to_string()));
3607    }
3608
3609    #[test]
3610    fn test_iter_mut_with_complex_ordering() {
3611        let mut map = LinkedHashMap::default();
3612        for i in 1..=5 {
3613            map.insert_tail(i, i);
3614        }
3615
3616        let ptr3 = map.get_ptr(&3).unwrap();
3617        map.move_to_head(ptr3);
3618        map.insert_head(0, 0);
3619        map.remove(&4);
3620
3621        let expected_keys = [0, 3, 1, 2, 5];
3622        let mut iter = map.iter_mut();
3623
3624        for expected_key in expected_keys.iter() {
3625            let (key, value) = iter.next().unwrap();
3626            assert_eq!(*key, *expected_key);
3627            *value = *expected_key * 100;
3628        }
3629
3630        assert!(iter.next().is_none());
3631
3632        assert_eq!(map.get(&0), Some(&0));
3633        assert_eq!(map.get(&3), Some(&300));
3634        assert_eq!(map.get(&1), Some(&100));
3635        assert_eq!(map.get(&2), Some(&200));
3636        assert_eq!(map.get(&5), Some(&500));
3637    }
3638
3639    #[test]
3640    fn test_iter_mut_exhausted_iterator_behavior() {
3641        let mut map = LinkedHashMap::default();
3642        map.insert_tail(1, "one");
3643        map.insert_tail(2, "two");
3644
3645        let mut iter = map.iter_mut();
3646
3647        assert!(iter.next().is_some());
3648        assert!(iter.next().is_some());
3649        assert!(iter.next().is_none());
3650
3651        assert!(iter.next().is_none());
3652        assert!(iter.next_back().is_none());
3653    }
3654
3655    #[test]
3656    fn test_clone() {
3657        let mut map = LinkedHashMap::default();
3658        map.insert_tail("a", 1);
3659        map.insert_tail("b", 2);
3660        map.insert_tail("c", 3);
3661
3662        let cloned = map.clone();
3663
3664        assert_eq!(map.len(), cloned.len());
3665        assert_eq!(
3666            map.iter().collect::<Vec<_>>(),
3667            cloned.iter().collect::<Vec<_>>()
3668        );
3669
3670        // Verify they are independent
3671        map.insert_tail("d", 4);
3672        assert_ne!(map.len(), cloned.len());
3673    }
3674
3675    #[test]
3676    fn test_partial_eq() {
3677        let mut map1 = LinkedHashMap::default();
3678        let mut map2 = LinkedHashMap::default();
3679
3680        // Empty maps are equal
3681        assert_eq!(map1, map2);
3682
3683        // Add same elements in same order
3684        map1.insert_tail("a", 1);
3685        map1.insert_tail("b", 2);
3686        map2.insert_tail("a", 1);
3687        map2.insert_tail("b", 2);
3688        assert_eq!(map1, map2);
3689
3690        // Different values
3691        map2.insert_tail("a", 3);
3692        assert_ne!(map1, map2);
3693
3694        // Different lengths
3695        map1.insert_tail("c", 3);
3696        assert_ne!(map1, map2);
3697
3698        // Same content but different order (should be equal since PartialEq doesn't
3699        // care about order)
3700        let mut map3 = LinkedHashMap::default();
3701        map3.insert_tail("b", 2);
3702        map3.insert_tail("a", 1);
3703        map3.insert_tail("c", 3);
3704
3705        let mut map4 = LinkedHashMap::default();
3706        map4.insert_tail("a", 1);
3707        map4.insert_tail("b", 2);
3708        map4.insert_tail("c", 3);
3709
3710        assert_eq!(map3, map4);
3711    }
3712
3713    #[test]
3714    fn test_from_iterator() {
3715        let vec = vec![("a", 1), ("b", 2), ("c", 3)];
3716        let map: LinkedHashMap<&str, i32> = vec.into_iter().collect();
3717
3718        assert_eq!(map.len(), 3);
3719        assert_eq!(map.get(&"a"), Some(&1));
3720        assert_eq!(map.get(&"b"), Some(&2));
3721        assert_eq!(map.get(&"c"), Some(&3));
3722
3723        let entries: Vec<_> = map.iter().collect();
3724        assert_eq!(entries, vec![(&"a", &1), (&"b", &2), (&"c", &3)]);
3725    }
3726
3727    #[test]
3728    fn test_extend_from_iterator() {
3729        let mut map = LinkedHashMap::default();
3730        map.insert_tail("existing", 0);
3731
3732        let vec = vec![("a", 1), ("b", 2), ("c", 3)];
3733        map.extend(vec);
3734
3735        assert_eq!(map.len(), 4);
3736        let entries: Vec<_> = map.iter().collect();
3737        assert_eq!(
3738            entries,
3739            vec![(&"existing", &0), (&"a", &1), (&"b", &2), (&"c", &3)]
3740        );
3741    }
3742
3743    #[test]
3744    fn test_extend_from_references() {
3745        let mut map = LinkedHashMap::default();
3746        map.insert_tail("existing", 0);
3747
3748        let vec = vec![("a", 1), ("b", 2), ("c", 3)];
3749        map.extend(vec);
3750
3751        assert_eq!(map.len(), 4);
3752        let entries: Vec<_> = map.iter().collect();
3753        assert_eq!(
3754            entries,
3755            vec![(&"existing", &0), (&"a", &1), (&"b", &2), (&"c", &3)]
3756        );
3757    }
3758
3759    #[test]
3760    fn test_with_capacity_and_hasher() {
3761        use crate::RandomState;
3762        let hasher = RandomState::default();
3763        let mut map: crate::linked_hash_map::LinkedHashMap<&str, i32, _> =
3764            LinkedHashMap::with_capacity_and_hasher(10, hasher);
3765
3766        assert_eq!(map.len(), 0);
3767        assert!(map.is_empty());
3768
3769        map.insert_tail("key", 42);
3770        assert_eq!(map.get(&"key"), Some(&42));
3771    }
3772
3773    #[test]
3774    fn test_link_operations() {
3775        let mut map = LinkedHashMap::default();
3776        let (ptr1, _) = map.insert_tail_full("first", 1);
3777        let (ptr2, _) = map.insert_tail_full("second", 2);
3778
3779        let removed = map.remove_ptr(ptr2).unwrap();
3780        assert_eq!(removed.key, "second");
3781
3782        let (ptr3, _) = map.insert_tail_full("third", 3);
3783        assert!(map.link_after(ptr3, ptr1).is_some());
3784
3785        let (ptr4, _) = map.insert_tail_full("fourth", 4);
3786        assert!(map.link_before(ptr4, ptr1).is_some());
3787    }
3788
3789    #[test]
3790    fn test_ptr_operations_comprehensive() {
3791        let mut map = LinkedHashMap::default();
3792        let (ptr1, _) = map.insert_tail_full("a", 1);
3793        let (ptr2, _) = map.insert_tail_full("b", 2);
3794        let (ptr3, _) = map.insert_tail_full("c", 3);
3795
3796        assert_eq!(map.next_ptr(ptr1), Some(ptr2));
3797        assert_eq!(map.next_ptr(ptr2), Some(ptr3));
3798        assert_eq!(map.next_ptr(ptr3), Some(ptr1));
3799
3800        assert_eq!(map.prev_ptr(ptr1), Some(ptr3));
3801        assert_eq!(map.prev_ptr(ptr2), Some(ptr1));
3802        assert_eq!(map.prev_ptr(ptr3), Some(ptr2));
3803
3804        assert_eq!(map.ptr_get(ptr1), Some(&1));
3805        assert_eq!(map.ptr_get_key(ptr2), Some(&"b"));
3806        assert_eq!(map.ptr_get_entry(ptr3), Some((&"c", &3)));
3807
3808        *map.ptr_get_mut(ptr1).unwrap() = 10;
3809        assert_eq!(map.ptr_get(ptr1), Some(&10));
3810
3811        let (key, value) = map.ptr_get_entry_mut(ptr2).unwrap();
3812        assert_eq!(key, &"b");
3813        *value = 20;
3814        assert_eq!(map.ptr_get(ptr2), Some(&20));
3815    }
3816
3817    #[test]
3818    fn test_cursors() {
3819        let mut map = LinkedHashMap::default();
3820        map.insert_tail_full("a", 1);
3821        let (ptr2, _) = map.insert_tail_full("b", 2);
3822        let (ptr3, _) = map.insert_tail_full("c", 3);
3823
3824        let mut cursor = map.ptr_cursor_mut(ptr2);
3825        if let Some((key, value)) = cursor.current_mut() {
3826            assert_eq!(key, &"b");
3827            *value = 20;
3828        }
3829        assert_eq!(map.ptr_get(ptr2), Some(&20));
3830
3831        let mut cursor = map.key_cursor_mut(&"c");
3832        if let Some((key, value)) = cursor.current_mut() {
3833            assert_eq!(key, &"c");
3834            *value = 30;
3835        }
3836        assert_eq!(map.ptr_get(ptr3), Some(&30));
3837
3838        let cursor = map.head_cursor_mut();
3839        if let Some((key, _)) = cursor.current() {
3840            assert_eq!(key, &"a");
3841        }
3842
3843        let cursor = map.tail_cursor_mut();
3844        if let Some((key, _)) = cursor.current() {
3845            assert_eq!(key, &"c");
3846        }
3847    }
3848
3849    #[test]
3850    fn test_remove_operations_comprehensive() {
3851        let mut map = LinkedHashMap::default();
3852        map.insert_tail_full("a", 1);
3853        let (ptr2, _) = map.insert_tail_full("b", 2);
3854        map.insert_tail_full("c", 3);
3855
3856        let (_, removed) = map.remove_head().unwrap();
3857        assert_eq!(removed.key, "a");
3858        assert_eq!(removed.value, 1);
3859        assert_eq!(map.len(), 2);
3860
3861        let (_, removed) = map.remove_tail().unwrap();
3862        assert_eq!(removed.key, "c");
3863        assert_eq!(removed.value, 3);
3864        assert_eq!(map.len(), 1);
3865
3866        let (removed_ptr, removed_entry) = map.remove_full(&"b").unwrap();
3867        assert_eq!(removed_ptr, ptr2);
3868        assert_eq!(removed_entry.key, "b");
3869        assert_eq!(removed_entry.value, 2);
3870        assert_eq!(map.len(), 0);
3871
3872        assert_eq!(map.remove_head(), None);
3873        assert_eq!(map.remove_tail(), None);
3874        assert_eq!(map.remove_full(&"nonexistent"), None);
3875    }
3876
3877    #[test]
3878    fn test_values_and_keys_iterators() {
3879        let mut map = LinkedHashMap::default();
3880        map.insert_tail("a", 1);
3881        map.insert_tail("b", 2);
3882        map.insert_tail("c", 3);
3883
3884        let keys: Vec<_> = map.keys().cloned().collect();
3885        assert_eq!(keys, vec!["a", "b", "c"]);
3886
3887        let values: Vec<_> = map.values().cloned().collect();
3888        assert_eq!(values, vec![1, 2, 3]);
3889
3890        for value in map.values_mut() {
3891            *value *= 2;
3892        }
3893
3894        let values: Vec<_> = map.values().cloned().collect();
3895        assert_eq!(values, vec![2, 4, 6]);
3896    }
3897
3898    #[test]
3899    fn test_empty_map_edge_cases() {
3900        let mut map: LinkedHashMap<&str, i32> = LinkedHashMap::default();
3901
3902        assert_eq!(map.head_ptr(), None);
3903        assert_eq!(map.tail_ptr(), None);
3904        assert_eq!(map.remove(&"nonexistent"), None);
3905        assert_eq!(map.remove_entry(&"nonexistent"), None);
3906        assert_eq!(map.get_ptr(&"nonexistent"), None);
3907        #[cfg(feature = "generational")]
3908        assert!(!map.contains_ptr(Ptr::unchecked_from(0, 0)));
3909        #[cfg(not(feature = "generational"))]
3910        assert!(!map.contains_ptr(Ptr::unchecked_from(0)));
3911
3912        assert_eq!(map.iter().count(), 0);
3913        assert_eq!(map.iter_mut().count(), 0);
3914        assert_eq!(map.keys().count(), 0);
3915        assert_eq!(map.values().count(), 0);
3916        assert_eq!(map.values_mut().count(), 0);
3917
3918        map.retain(|_, _| true);
3919        assert!(map.is_empty());
3920
3921        map.shrink_to_fit();
3922    }
3923
3924    #[test]
3925    fn test_link_as_head_and_tail_with_unlinked_push() {
3926        let mut map = LinkedHashMap::default();
3927
3928        let ptr_x = match map.entry("x") {
3929            Entry::Vacant(v) => v.insert_unlinked(10).0,
3930            _ => unreachable!(),
3931        };
3932
3933        assert_eq!(map.head_ptr(), None);
3934        assert_eq!(map.tail_ptr(), None);
3935        assert_eq!(map.iter().count(), 0);
3936
3937        assert!(map.link_as_head(ptr_x).is_some());
3938        assert_eq!(map.head_ptr(), Some(ptr_x));
3939        assert_eq!(map.tail_ptr(), Some(ptr_x));
3940
3941        let items: Vec<_> = map.iter().collect();
3942        assert_eq!(items, vec![(&"x", &10)]);
3943
3944        let ptr_y = match map.entry("y") {
3945            Entry::Vacant(v) => v.insert_unlinked(20).0,
3946            _ => unreachable!(),
3947        };
3948        assert!(map.link_as_tail(ptr_y).is_some());
3949
3950        let items: Vec<_> = map.iter().collect();
3951        assert_eq!(items, vec![(&"x", &10), (&"y", &20)]);
3952        assert_eq!(map.tail_ptr(), Some(ptr_y));
3953    }
3954
3955    #[test]
3956    fn test_link_after_and_before_with_unlinked_nodes() {
3957        let mut map = LinkedHashMap::default();
3958        let (ptr_a, _) = map.insert_tail_full("a", 1);
3959        let (_ptr_c, _) = map.insert_tail_full("c", 3);
3960
3961        let ptr_b = match map.entry("b") {
3962            Entry::Vacant(v) => v.insert_unlinked(2).0,
3963            _ => unreachable!(),
3964        };
3965        assert!(map.link_after(ptr_b, ptr_a).is_some());
3966        let keys: Vec<_> = map.iter().map(|(k, _)| *k).collect();
3967        assert_eq!(keys, vec!["a", "b", "c"]);
3968
3969        let ptr_0 = match map.entry("0") {
3970            Entry::Vacant(v) => v.insert_unlinked(0).0,
3971            _ => unreachable!(),
3972        };
3973        assert!(map.link_before(ptr_0, map.head_ptr().unwrap()).is_some());
3974        let keys: Vec<_> = map.iter().map(|(k, _)| *k).collect();
3975        assert_eq!(keys, vec!["0", "a", "b", "c"]);
3976    }
3977
3978    #[test]
3979    fn test_entry_or_insert_and_and_modify() {
3980        let mut map = LinkedHashMap::default();
3981
3982        {
3983            let v_ref = map.entry("k").or_insert(1);
3984            assert_eq!(*v_ref, 1);
3985        }
3986        assert_eq!(map.get(&"k"), Some(&1));
3987
3988        {
3989            let e = map.entry("k").and_modify(|v| *v *= 10);
3990            let v_ref = e.or_insert(999);
3991            assert_eq!(*v_ref, 10);
3992        }
3993        assert_eq!(map.get(&"k"), Some(&10));
3994    }
3995
3996    #[test]
3997    fn test_retain_filter_and_mutation() {
3998        let mut map = LinkedHashMap::default();
3999        for i in 1..=6 {
4000            map.insert_tail(i, i);
4001        }
4002
4003        map.retain(|k, v| {
4004            *v *= 10;
4005            k % 2 == 0
4006        });
4007
4008        let keys: Vec<_> = map.iter().map(|(k, _)| *k).collect();
4009        assert_eq!(keys, vec![2, 4, 6]);
4010        assert_eq!(map.get(&2), Some(&20));
4011        assert_eq!(map.get(&4), Some(&40));
4012        assert_eq!(map.get(&6), Some(&60));
4013        assert_eq!(map.len(), 3);
4014    }
4015
4016    #[test]
4017    #[should_panic]
4018    fn test_index_key_panic_on_missing() {
4019        let map: LinkedHashMap<&str, i32> = LinkedHashMap::default();
4020        let _ = map[&"missing"];
4021    }
4022
4023    #[test]
4024    #[should_panic]
4025    fn test_index_key_mut_panic_on_missing() {
4026        let mut map: LinkedHashMap<&str, i32> = LinkedHashMap::default();
4027        map[&"missing"] = 1;
4028    }
4029
4030    #[test]
4031    #[should_panic]
4032    fn test_index_ptr_panic_after_removal() {
4033        let mut map = LinkedHashMap::default();
4034        let (ptr, _) = map.insert_tail_full("a", 1);
4035        let _ = map.remove_ptr(ptr).unwrap();
4036        let _ = map[ptr];
4037    }
4038
4039    #[test]
4040    #[cfg(feature = "generational")]
4041    #[should_panic]
4042    fn test_generational_ptr() {
4043        let mut map = LinkedHashMap::default();
4044        let (ptr, _) = map.insert_tail_full("a", 1);
4045        let _ = map.remove_ptr(ptr).unwrap();
4046        let ptr2 = map.insert_tail_full("b", 2).0;
4047        assert_eq!(ptr.unchecked_get(), ptr2.unchecked_get());
4048        dbg!(ptr, ptr2);
4049        let _ = map[ptr];
4050    }
4051}