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