From c92c857075da2f4a3ba6c11e9a1867eb255e29b6 Mon Sep 17 00:00:00 2001 From: wuanzhuan <1691111985@qq.com> Date: Tue, 16 Jul 2024 14:15:57 +0800 Subject: [PATCH 1/2] add front_mut() and back_mut() --- src/lib.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index d34d5ac..5ee85fe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -547,6 +547,30 @@ impl LinkedHashMap { .map(|e| unsafe { (&(**e).key, &(**e).value) }) } + /// Gets the first entry, but the value is mutable. + /// + /// # Examples + /// + /// ``` + /// use linked_hash_map::LinkedHashMap; + /// let mut map = LinkedHashMap::new(); + /// map.insert(1, 10); + /// map.insert(2, 20); + /// assert_eq!(map.front_mut(), Some((&1, &mut 10))); + /// ``` + #[inline] + pub fn front_mut(&mut self) -> Option<(&K, &mut V)> { + if self.is_empty() { + return None; + } + let lru = unsafe { (*self.head).prev }; + self.map + .get_mut(&KeyRef { + k: unsafe { &(*lru).key }, + }) + .map(|e| unsafe { (&(**e).key, &mut (**e).value) }) + } + /// Removes the last entry. /// /// # Examples @@ -601,6 +625,30 @@ impl LinkedHashMap { .map(|e| unsafe { (&(**e).key, &(**e).value) }) } + /// Gets the last entry, but the value is mutable. + /// + /// # Examples + /// + /// ``` + /// use linked_hash_map::LinkedHashMap; + /// let mut map = LinkedHashMap::new(); + /// map.insert(1, 10); + /// map.insert(2, 20); + /// assert_eq!(map.back_mut(), Some((&2, &mut 20))); + /// ``` + #[inline] + pub fn back_mut(&mut self) -> Option<(&K, &mut V)> { + if self.is_empty() { + return None; + } + let mru = unsafe { (*self.head).next }; + self.map + .get_mut(&KeyRef { + k: unsafe { &(*mru).key }, + }) + .map(|e| unsafe { (&(**e).key, &mut (**e).value) }) + } + /// Returns the number of key-value pairs in the map. pub fn len(&self) -> usize { self.map.len() From 49effd2276c919b081ebff4f256332f89236c269 Mon Sep 17 00:00:00 2001 From: wuanzhuan <1691111985@qq.com> Date: Tue, 16 Jul 2024 15:51:39 +0800 Subject: [PATCH 2/2] close warning can't use let _ it drop immediately --- src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5ee85fe..56f31b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -162,7 +162,7 @@ impl LinkedHashMap { let mut cur = (*self.head).next; while cur != self.head { let next = (*cur).next; - Box::from_raw(cur); + let _cur = Box::from_raw(cur); cur = next; } } @@ -1345,7 +1345,7 @@ impl Drop for IntoIter { for _ in 0..self.remaining { unsafe { let next = (*self.tail).next; - Box::from_raw(self.tail); + let _tail = Box::from_raw(self.tail); self.tail = next; } }