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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Make `String::from_utf8_unchecked` const.
- Implemented `PartialEq` and `Eq` for `Deque`.
- Added `truncate` to `IndexMap`.
- Added `get_index` and `get_index_mut` to `IndexMap`.

### Changed

Expand Down
71 changes: 71 additions & 0 deletions src/indexmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1085,6 +1085,77 @@ where
}
}

/// Returns a tuple of references to the key and the value corresponding to the index.
///
/// Computes in *O*(1) time (average).
///
/// # Examples
///
/// ```
/// 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).
///
/// # Examples
///
/// ```
/// 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).
///
/// # Examples
///
/// ```
/// 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<Q>(&self, key: &Q) -> Option<usize>
where
K: Borrow<Q>,
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
Expand Down