diff --git a/src/map.rs b/src/map.rs index 85310934..b224aace 100644 --- a/src/map.rs +++ b/src/map.rs @@ -821,6 +821,7 @@ impl IndexMap { /// This preserves the order of the remaining elements. /// /// Computes in **O(1)** time (average). + #[doc(alias = "pop_last")] // like `BTreeMap` pub fn pop(&mut self) -> Option<(K, V)> { self.core.pop() } @@ -1087,6 +1088,7 @@ impl IndexMap { /// Get the first key-value pair /// /// Computes in **O(1)** time. + #[doc(alias = "first_key_value")] // like `BTreeMap` pub fn first(&self) -> Option<(&K, &V)> { self.as_entries().first().map(Bucket::refs) } @@ -1098,9 +1100,17 @@ impl IndexMap { self.as_entries_mut().first_mut().map(Bucket::ref_mut) } + /// Get the first entry in the map for in-place manipulation. + /// + /// Computes in **O(1)** time. + pub fn first_entry(&mut self) -> Option> { + self.get_index_entry(0) + } + /// Get the last key-value pair /// /// Computes in **O(1)** time. + #[doc(alias = "last_key_value")] // like `BTreeMap` pub fn last(&self) -> Option<(&K, &V)> { self.as_entries().last().map(Bucket::refs) } @@ -1112,6 +1122,13 @@ impl IndexMap { self.as_entries_mut().last_mut().map(Bucket::ref_mut) } + /// Get the last entry in the map for in-place manipulation. + /// + /// Computes in **O(1)** time. + pub fn last_entry(&mut self) -> Option> { + self.get_index_entry(self.len().checked_sub(1)?) + } + /// Remove the key-value pair by index /// /// Valid indices are *0 <= index < self.len()* diff --git a/src/map/tests.rs b/src/map/tests.rs index 00600892..0c7d93b3 100644 --- a/src/map/tests.rs +++ b/src/map/tests.rs @@ -391,6 +391,8 @@ fn get_index_entry() { let mut map = IndexMap::new(); assert!(map.get_index_entry(0).is_none()); + assert!(map.first_entry().is_none()); + assert!(map.last_entry().is_none()); map.insert(0, "0"); map.insert(1, "1"); @@ -414,6 +416,18 @@ fn get_index_entry() { } assert_eq!(*map.get(&3).unwrap(), "4"); + + { + let e = map.first_entry().unwrap(); + assert_eq!(*e.key(), 0); + assert_eq!(*e.get(), "0"); + } + + { + let e = map.last_entry().unwrap(); + assert_eq!(*e.key(), 2); + assert_eq!(*e.get(), "2"); + } } #[test] diff --git a/src/set.rs b/src/set.rs index 835ccf02..7a8ac4df 100644 --- a/src/set.rs +++ b/src/set.rs @@ -708,6 +708,7 @@ impl IndexSet { /// This preserves the order of the remaining elements. /// /// Computes in **O(1)** time (average). + #[doc(alias = "pop_last")] // like `BTreeSet` pub fn pop(&mut self) -> Option { self.map.pop().map(|(x, ())| x) }