From 6be3e66f53ad6f8137abfb68e02d9d3a2a1a4891 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`, `get_index_mut` and `get_index_of` --- CHANGELOG.md | 1 + src/indexmap.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e823923213..b33485d0de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Added `SortedLinkedListView`, the `!Sized` version of `SortedLinkedList`. - Added implementation of `Borrow` and `BorrowMut` for `String` and `Vec`. - Added `Deque::{swap, swap_unchecked, swap_remove_front, swap_remove_back}`. +- Added `get_index` and `get_index_mut` to `IndexMap` ### Changed diff --git a/src/indexmap.rs b/src/indexmap.rs index 1d99d72a43..b9c0ad4116 100644 --- a/src/indexmap.rs +++ b/src/indexmap.rs @@ -1084,6 +1084,71 @@ 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)) + } + + /// Returns the index of the key-value pair corresponding to the key. + /// + /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed + /// form *must* match those for the key type. + /// + /// Computes in *O*(1) time (average). + /// + /// ``` + /// use heapless::FnvIndexMap; + /// + /// let mut map = FnvIndexMap::<_, _, 8>::new(); + /// map.insert(1, "a").unwrap(); + /// map.insert(0, "b").unwrap(); + /// assert_eq!(map.get_index_of(&0), Some(1)); + /// assert_eq!(map.get_index_of(&1), Some(0)); + /// assert_eq!(map.get_index_of(&2), None); + /// ``` + pub fn get_index_of(&self, key: &Q) -> Option + where + K: Borrow, + Q: ?Sized + Hash + Eq, + { + self.find(key).map(|(_, found)| found) + } + /// 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