diff --git a/src/lib.rs b/src/lib.rs index 30debdd..2f4b1a8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 { + self.iter().map(|(k, _)| k) + } + + /// An iterator over all the values in the map + pub fn values(&self) -> impl Iterator { + self.iter().map(|(_, v)| v) + } + + /// A mutable iterator over all the values in the map + pub fn values_mut(&mut self) -> impl Iterator { + 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 std::iter::Extend<(K,V)> for Map } use std::hash::{Hash, Hasher,}; -impl Collapse for T +use std::ops::{Index, IndexMut}; + +impl Collapse for T { fn collapse(&self) -> u8 { struct CollapseHasher(u8); @@ -537,6 +554,29 @@ impl Collapse for T h.0 } } + +impl Index<&Q> for Map + where + K: Collapse + Borrow, + Q: ?Sized + Collapse + Eq, +{ + type Output = V; + + fn index(&self, key: &Q) -> &Self::Output { + self.get(key).expect("Key not found") + } +} + +impl IndexMut<&Q> for Map + where + K: Collapse + Borrow, + 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; diff --git a/src/tests.rs b/src/tests.rs index 0de4229..64d746a 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -129,6 +129,68 @@ fn reverse() assert_eq!(expected.reverse().into_iter().map(|(_, v)| v).sum::(), 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::(); + assert_eq!(expect_sum, got_sum); +} + #[cfg(nightly)] mod benchmarks {