[meta] Add a MapWithDefault trait;
This traits augments HashMap so they have a `get_or_default` method that can be used to avoid boilerplate around usage of `entry.or_default`.
This commit is contained in:
19
cranelift/codegen/meta/src/default_map.rs
Normal file
19
cranelift/codegen/meta/src/default_map.rs
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::hash::Hash;
|
||||||
|
|
||||||
|
pub trait MapWithDefault<K, V: Default> {
|
||||||
|
fn get_or_default(&mut self, k: K) -> &mut V;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<K: Eq + Hash, V: Default> MapWithDefault<K, V> for HashMap<K, V> {
|
||||||
|
fn get_or_default(&mut self, k: K) -> &mut V {
|
||||||
|
self.entry(k).or_insert_with(|| V::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_default() {
|
||||||
|
let mut hash_map = HashMap::new();
|
||||||
|
hash_map.insert(42, "hello");
|
||||||
|
assert_eq!(*hash_map.get_or_default(43), "");
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ mod gen_settings;
|
|||||||
mod gen_types;
|
mod gen_types;
|
||||||
|
|
||||||
mod constant_hash;
|
mod constant_hash;
|
||||||
|
mod default_map;
|
||||||
mod shared;
|
mod shared;
|
||||||
mod unique_table;
|
mod unique_table;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user