Add some methods to make the map more compatible with std HashMap

master
gramar 2 years ago
parent 1a58d3a734
commit 76333387c5

@ -322,6 +322,21 @@ where K: Collapse
Iter(None, self.pages())
}
/// An iterator over all the keys in the map
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.iter().map(|(k, _)| k)
}
/// An iterator over all the values in the map
pub fn values(&self) -> impl Iterator<Item = &V> {
self.iter().map(|(_, v)| v)
}
/// A mutable iterator over all the values in the map
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
self.iter_mut().map(|(_, v)| v)
}
/// A mutable iterator over all elements in the map
pub fn iter_mut(&mut self) -> IterMut<'_, K, V>
{
@ -481,7 +496,9 @@ impl<K: Collapse, V> std::iter::Extend<(K,V)> for Map<K,V>
}
use std::hash::{Hash, Hasher,};
impl<T: Hash+ Eq> Collapse for T
use std::ops::{Index, IndexMut};
impl<T: ?Sized + Hash + Eq> Collapse for T
{
fn collapse(&self) -> u8 {
struct CollapseHasher(u8);
@ -537,6 +554,29 @@ impl<T: Hash+ Eq> Collapse for T
h.0
}
}
impl<K, Q, V> Index<&Q> for Map<K, V>
where
K: Collapse + Borrow<Q>,
Q: ?Sized + Collapse + Eq,
{
type Output = V;
fn index(&self, key: &Q) -> &Self::Output {
self.get(key).expect("Key not found")
}
}
impl<K, Q, V> IndexMut<&Q> for Map<K, V>
where
K: Collapse + Borrow<Q>,
Q: ?Sized + Collapse + Eq,
{
fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
self.get_mut(key).expect("Key not found")
}
}
#[cfg(test)]
mod tests;

@ -129,6 +129,68 @@ fn reverse()
assert_eq!(expected.reverse().into_iter().map(|(_, v)| v).sum::<i32>(), 4+3+2+1);
}
#[test]
fn index_index_mut() {
let mut map = smallmap![
{"one" => 1},
{"two" => 2},
];
assert_eq!(1, map["one"]);
map["two"] = 3;
assert_eq!(3, map["two"]);
}
#[test]
fn get_keys() {
let map = smallmap![
{"one" => 1},
{"two" => 2},
{"three" => 3},
{"four" => 4},
];
let keys = map.keys();
let expect_sum = 10;
let mut got_sum = 0;
for key in keys {
got_sum += map[key];
}
assert_eq!(expect_sum, got_sum);
}
#[test]
fn get_values() {
let map = smallmap![
{"one" => 1},
{"two" => 2},
{"three" => 3},
{"four" => 4},
];
let values = map.values();
let expect_sum = 10;
let mut got_sum = 0;
for val in values {
got_sum += val;
}
assert_eq!(expect_sum, got_sum);
}
#[test]
fn get_values_mut() {
let mut map = smallmap![
{"one" => 1},
{"two" => 2},
{"three" => 3},
{"four" => 4},
];
let values = map.values_mut();
let expect_sum = 20;
for val in values {
*val *= 2;
}
let got_sum = map.values().sum::<i32>();
assert_eq!(expect_sum, got_sum);
}
#[cfg(nightly)]
mod benchmarks
{

Loading…
Cancel
Save