use core::{
borrow::Borrow,
hash::{BuildHasher, Hash},
};
#[macro_export]
macro_rules! hashmap {
(@single $($x:tt)*) => (());
(@count $($rest:expr),*) => (<[()]>::len(&[ $($crate::hashmap!(@single $rest)),* ]));
( hasher = $hasher:expr, strict, data = { $( $key:expr => $value:expr, )+ } $( , )? ) => {{
$crate::hashmap!(hasher = $hasher, strict, data = { $( $key => $value ),+ })
}};
( hasher = $hasher:expr, strict, data = { $( $key:expr => $value:expr ),* } $( , )? ) => {{
use $crate::{HashMapExt, Peep};
let _cap = $crate::hashmap!(@count $($key),*);
$crate::lib::HashMap::with_capacity_and_hasher(_cap, $hasher)
$(
.peep(|map| assert!(map.get(&$key).is_some()) )
.inserted($key, $value)
)*
}};
( strict, data = { $( $key:expr => $value:expr, )+ } $( , )? ) => {{
$crate::hashmap!(strict, data = { $( $key => $value ),+ })
}};
( strict, data = { $( $key:expr => $value:expr ),* } $( , )? ) => {{
use $crate::{HashMapExt, Peep};
let _cap = $crate::hashmap!(@count $($key),*);
$crate::lib::HashMap::with_capacity(_cap)
$(
.peep(|map| assert!(map.get(&$key).is_some()) )
.inserted($key, $value)
)*
}};
( hasher = $hasher:expr, data = { $( $key:expr => $value:expr, )+ } $( , )? ) => {{
$crate::hashmap!(hasher = $hasher, data = { $( $key => $value ),+ })
}};
( hasher = $hasher:expr, data = { $( $key:expr => $value:expr ),* } $( , )? ) => {{
use $crate::HashMapExt;
let _cap = $crate::hashmap!(@count $($key),*);
$crate::lib::HashMap::with_capacity_and_hasher(_cap, $hasher)
$(
.inserted($key, $value)
)*
}};
( $( $key:expr => $value:expr, )+ ) => {{
$crate::hashmap!( $( $key => $value ),+ )
}};
( $( $key:expr => $value:expr ),* ) => {{
use $crate::HashMapExt;
let _cap = $crate::hashmap!(@count $($key),*);
$crate::lib::HashMap::with_capacity(_cap)
$(
.inserted($key, $value)
)*
}};
() => {
$crate::lib::HashMap::new()
};
}
pub trait HashMapExt<K, V, S> {
fn cleared(self) -> Self;
fn inserted(self, k: K, v: V) -> Self
where
K: Eq + Hash,
S: BuildHasher;
fn removed<Q>(self, k: &Q) -> Self
where
K: Eq + Hash + Borrow<Q>,
S: BuildHasher,
Q: Eq + Hash;
fn retained<F>(self, f: F) -> Self
where
K: Eq + Hash,
S: BuildHasher,
F: FnMut(&K, &mut V) -> bool;
fn shrinked_to_fit(self) -> Self
where
K: Eq + Hash,
S: BuildHasher;
}
impl<K, V, S> HashMapExt<K, V, S> for super::lib::HashMap<K, V, S> {
fn cleared(mut self) -> Self {
self.clear();
self
}
fn inserted(mut self, k: K, v: V) -> Self
where
K: Eq + Hash,
S: BuildHasher,
{
let _ = self.insert(k, v);
self
}
fn removed<Q>(mut self, k: &Q) -> Self
where
K: Eq + Hash + Borrow<Q>,
S: BuildHasher,
Q: Eq + Hash,
{
let _ = self.remove(k);
self
}
fn retained<F>(mut self, f: F) -> Self
where
K: Eq + Hash,
S: BuildHasher,
F: FnMut(&K, &mut V) -> bool,
{
self.retain(f);
self
}
fn shrinked_to_fit(mut self) -> Self
where
K: Eq + Hash,
S: BuildHasher,
{
self.shrink_to_fit();
self
}
}