Skip to content

Commit

Permalink
feat(indexmap): added get_index and get_index_mut
Browse files Browse the repository at this point in the history
  • Loading branch information
pamburus committed Dec 28, 2024
1 parent 0ebca23 commit 765cd35
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/indexmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1084,6 +1084,46 @@ where
}
}

/// Returns a tuple of references to the key and the value corresponding to the index.
///
/// Computes in *O*(1) time (average).
///
/// ```
/// use heapless::FnvIndexMap;
///
/// let mut map = FnvIndexMap::<_, _, 16>::new();
/// map.insert(1, "a").unwrap();
/// assert_eq!(map.get_index(0), Some((&1, &"a")));
/// assert_eq!(map.get_index(1), None);
/// ```
pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
self.core
.entries
.get(index)
.map(|entry| (&entry.key, &entry.value))
}

/// Returns a tuple of references to the key and the mutable value corresponding to the index.
///
/// Computes in *O*(1) time (average).
///
/// ```
/// use heapless::FnvIndexMap;
///
/// let mut map = FnvIndexMap::<_, _, 8>::new();
/// map.insert(1, "a").unwrap();
/// if let Some((_, x)) = map.get_index_mut(0) {
/// *x = "b";
/// }
/// assert_eq!(map[&1], "b");
/// ```
pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
self.core
.entries
.get_mut(index)
.map(|entry| (&entry.key, &mut entry.value))
}

/// Inserts a key-value pair into the map.
///
/// If an equivalent key already exists in the map: the key remains and retains in its place in
Expand Down

0 comments on commit 765cd35

Please sign in to comment.