Skip to content

Commit

Permalink
Add first_entry and last_entry similar to BTreeMap
Browse files Browse the repository at this point in the history
  • Loading branch information
cuviper committed Aug 28, 2024
1 parent 9b93dd5 commit e1f5f26
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1098,6 +1098,13 @@ impl<K, V, S> IndexMap<K, V, S> {
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<IndexedEntry<'_, K, V>> {
self.get_index_entry(0)
}

/// Get the last key-value pair
///
/// Computes in **O(1)** time.
Expand All @@ -1112,6 +1119,13 @@ impl<K, V, S> IndexMap<K, V, S> {
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<IndexedEntry<'_, K, V>> {
self.get_index_entry(self.len().checked_sub(1)?)
}

/// Remove the key-value pair by index
///
/// Valid indices are *0 <= index < self.len()*
Expand Down
14 changes: 14 additions & 0 deletions src/map/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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]
Expand Down

0 comments on commit e1f5f26

Please sign in to comment.