Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,7 @@ impl<K, V, S> IndexMap<K, V, S> {
/// 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()
}
Expand Down Expand Up @@ -1087,6 +1088,7 @@ impl<K, V, S> IndexMap<K, V, S> {
/// 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)
}
Expand All @@ -1098,9 +1100,17 @@ 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.
#[doc(alias = "last_key_value")] // like `BTreeMap`
pub fn last(&self) -> Option<(&K, &V)> {
self.as_entries().last().map(Bucket::refs)
}
Expand All @@ -1112,6 +1122,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
1 change: 1 addition & 0 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,7 @@ impl<T, S> IndexSet<T, S> {
/// 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<T> {
self.map.pop().map(|(x, ())| x)
}
Expand Down