Skip to content

Commit 0c6728c

Browse files
authored
Merge pull request #526 from pamburus/feature/indexmap/truncate
feat(indexmap): added `truncate`
2 parents 4b78bc1 + 1e7f5b8 commit 0c6728c

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
4141
- Added `Deque::{swap, swap_unchecked, swap_remove_front, swap_remove_back}`.
4242
- Make `String::from_utf8_unchecked` const.
4343
- Implemented `PartialEq` and `Eq` for `Deque`.
44+
- Added `truncate` to `IndexMap`.
4445

4546
### Changed
4647

src/indexmap.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1169,6 +1169,33 @@ where
11691169
self.core.retain_in_order(move |k, v| f(k, v));
11701170
}
11711171

1172+
/// Shortens the map, keeping the first `len` elements and dropping the rest.
1173+
///
1174+
/// If `len` is greater than the map's current length, this has no effect.
1175+
///
1176+
/// Computes in *O*(1) time (average).
1177+
///
1178+
/// # Examples
1179+
///
1180+
/// ```
1181+
/// use heapless::FnvIndexMap;
1182+
///
1183+
/// let mut map = FnvIndexMap::<_, _, 8>::new();
1184+
/// map.insert(3, "a").unwrap();
1185+
/// map.insert(2, "b").unwrap();
1186+
/// map.insert(1, "c").unwrap();
1187+
/// map.truncate(2);
1188+
/// assert_eq!(map.len(), 2);
1189+
///
1190+
/// let mut iter = map.iter();
1191+
/// assert_eq!(iter.next(), Some((&3, &"a")));
1192+
/// assert_eq!(iter.next(), Some((&2, &"b")));
1193+
/// assert_eq!(iter.next(), None);
1194+
/// ```
1195+
pub fn truncate(&mut self, len: usize) {
1196+
self.core.entries.truncate(len);
1197+
}
1198+
11721199
/* Private API */
11731200
/// Return probe (indices) and position (entries)
11741201
fn find<Q>(&self, key: &Q) -> Option<(usize, usize)>

0 commit comments

Comments
 (0)