From 765cd357dd8a3e7006a270752af18a299c911034 Mon Sep 17 00:00:00 2001 From: Pavel Ivanov Date: Sat, 28 Dec 2024 09:10:58 +0100 Subject: [PATCH] feat(indexmap): added `get_index` and `get_index_mut` --- src/indexmap.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/indexmap.rs b/src/indexmap.rs index 1d99d72a43..8662bf81e4 100644 --- a/src/indexmap.rs +++ b/src/indexmap.rs @@ -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