use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections;
use std::collections::hash_map::RandomState;
use std::fmt::{Debug, Error, Formatter};
use std::hash::{BuildHasher, Hash, Hasher};
use std::iter::{FromIterator, FusedIterator, Sum};
use std::mem;
use std::ops::{Add, Index, IndexMut};
use crate::nodes::hamt::{
hash_key, Drain as NodeDrain, HashBits, HashValue, Iter as NodeIter, IterMut as NodeIterMut,
Node,
};
use crate::util::{Pool, PoolRef, Ref};
#[macro_export]
macro_rules! hashmap {
() => { $crate::hashmap::HashMap::new() };
( $( $key:expr => $value:expr ),* ) => {{
let mut map = $crate::hashmap::HashMap::new();
$({
map.insert($key, $value);
})*;
map
}};
( $( $key:expr => $value:expr ,)* ) => {{
let mut map = $crate::hashmap::HashMap::new();
$({
map.insert($key, $value);
})*;
map
}};
}
def_pool!(HashMapPool<K,V>, Node<(K,V)>);
pub struct HashMap<K, V, S = RandomState> {
size: usize,
pool: HashMapPool<K, V>,
root: PoolRef<Node<(K, V)>>,
hasher: Ref<S>,
}
impl<K, V> HashValue for (K, V)
where
K: Eq,
{
type Key = K;
fn extract_key(&self) -> &Self::Key {
&self.0
}
fn ptr_eq(&self, _other: &Self) -> bool {
false
}
}
impl<K, V> HashMap<K, V, RandomState> {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[cfg(feature = "pool")]
#[must_use]
pub fn with_pool(pool: &HashMapPool<K, V>) -> Self {
let root = PoolRef::default(&pool.0);
Self {
size: 0,
hasher: Default::default(),
pool: pool.clone(),
root,
}
}
}
impl<K, V> HashMap<K, V, RandomState>
where
K: Hash + Eq + Clone,
V: Clone,
{
#[inline]
#[must_use]
pub fn unit(k: K, v: V) -> HashMap<K, V> {
HashMap::new().update(k, v)
}
}
impl<K, V, S> HashMap<K, V, S> {
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.size
}
pub fn ptr_eq(&self, other: &Self) -> bool {
std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
}
#[cfg(feature = "pool")]
pub fn pool(&self) -> &HashMapPool<K, V> {
&self.pool
}
#[inline]
#[must_use]
pub fn with_hasher<RS>(hasher: RS) -> Self
where
Ref<S>: From<RS>,
{
let pool = HashMapPool::default();
let root = PoolRef::default(&pool.0);
HashMap {
size: 0,
hasher: hasher.into(),
pool,
root,
}
}
#[cfg(feature = "pool")]
#[must_use]
pub fn with_pool_hasher<RS>(pool: &HashMapPool<K, V>, hasher: RS) -> Self
where
Ref<S>: From<RS>,
{
let root = PoolRef::default(&pool.0);
Self {
size: 0,
hasher: hasher.into(),
pool: pool.clone(),
root,
}
}
#[must_use]
pub fn hasher(&self) -> &Ref<S> {
&self.hasher
}
#[inline]
#[must_use]
pub fn new_from<K1, V1>(&self) -> HashMap<K1, V1, S>
where
K1: Hash + Eq + Clone,
V1: Clone,
{
let pool = HashMapPool::default();
let root = PoolRef::default(&pool.0);
HashMap {
size: 0,
pool,
root,
hasher: self.hasher.clone(),
}
}
#[inline]
#[must_use]
pub fn iter(&self) -> Iter<'_, K, V> {
Iter {
it: NodeIter::new(&self.root, self.size),
}
}
#[inline]
#[must_use]
pub fn keys(&self) -> Keys<'_, K, V> {
Keys {
it: NodeIter::new(&self.root, self.size),
}
}
#[inline]
#[must_use]
pub fn values(&self) -> Values<'_, K, V> {
Values {
it: NodeIter::new(&self.root, self.size),
}
}
pub fn clear(&mut self) {
if !self.is_empty() {
self.root = PoolRef::default(&self.pool.0);
self.size = 0;
}
}
}
impl<K, V, S> HashMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
fn test_eq(&self, other: &Self) -> bool
where
K: Hash + Eq,
V: PartialEq,
{
if self.len() != other.len() {
return false;
}
let mut seen = collections::HashSet::new();
for (key, value) in self.iter() {
if Some(value) != other.get(key) {
return false;
}
seen.insert(key);
}
for key in other.keys() {
if !seen.contains(&key) {
return false;
}
}
true
}
#[must_use]
pub fn get<BK>(&self, key: &BK) -> Option<&V>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
self.root
.get(hash_key(&*self.hasher, key), 0, key)
.map(|&(_, ref v)| v)
}
#[must_use]
pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
self.root
.get(hash_key(&*self.hasher, key), 0, key)
.map(|&(ref k, ref v)| (k, v))
}
#[inline]
#[must_use]
pub fn contains_key<BK>(&self, k: &BK) -> bool
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
self.get(k).is_some()
}
#[must_use]
pub fn is_submap_by<B, RM, F>(&self, other: RM, mut cmp: F) -> bool
where
F: FnMut(&V, &B) -> bool,
RM: Borrow<HashMap<K, B, S>>,
{
self.iter()
.all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
}
#[must_use]
pub fn is_proper_submap_by<B, RM, F>(&self, other: RM, cmp: F) -> bool
where
F: FnMut(&V, &B) -> bool,
RM: Borrow<HashMap<K, B, S>>,
{
self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
}
#[inline]
#[must_use]
pub fn is_submap<RM>(&self, other: RM) -> bool
where
V: PartialEq,
RM: Borrow<Self>,
{
self.is_submap_by(other.borrow(), PartialEq::eq)
}
#[inline]
#[must_use]
pub fn is_proper_submap<RM>(&self, other: RM) -> bool
where
V: PartialEq,
RM: Borrow<Self>,
{
self.is_proper_submap_by(other.borrow(), PartialEq::eq)
}
}
impl<K, V, S> HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
#[inline]
#[must_use]
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
IterMut {
it: NodeIterMut::new(&self.pool.0, root, self.size),
}
}
#[must_use]
pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.get_mut(&self.pool.0, hash_key(&*self.hasher, key), 0, key) {
None => None,
Some(&mut (_, ref mut value)) => Some(value),
}
}
#[inline]
pub fn insert(&mut self, k: K, v: V) -> Option<V> {
let hash = hash_key(&*self.hasher, &k);
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
let result = root.insert(&self.pool.0, hash, 0, (k, v));
if result.is_none() {
self.size += 1;
}
result.map(|(_, v)| v)
}
pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
self.remove_with_key(k).map(|(_, v)| v)
}
pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
let result = root.remove(&self.pool.0, hash_key(&*self.hasher, k), 0, k);
if result.is_some() {
self.size -= 1;
}
result
}
#[must_use]
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S> {
let hash = hash_key(&*self.hasher, &key);
if self.root.get(hash, 0, &key).is_some() {
Entry::Occupied(OccupiedEntry {
map: self,
hash,
key,
})
} else {
Entry::Vacant(VacantEntry {
map: self,
hash,
key,
})
}
}
#[inline]
#[must_use]
pub fn update(&self, k: K, v: V) -> Self {
let mut out = self.clone();
out.insert(k, v);
out
}
#[must_use]
pub fn update_with<F>(&self, k: K, v: V, f: F) -> Self
where
F: FnOnce(V, V) -> V,
{
match self.extract_with_key(&k) {
None => self.update(k, v),
Some((_, v2, m)) => m.update(k, f(v2, v)),
}
}
#[must_use]
pub fn update_with_key<F>(&self, k: K, v: V, f: F) -> Self
where
F: FnOnce(&K, V, V) -> V,
{
match self.extract_with_key(&k) {
None => self.update(k, v),
Some((_, v2, m)) => {
let out_v = f(&k, v2, v);
m.update(k, out_v)
}
}
}
#[must_use]
pub fn update_lookup_with_key<F>(&self, k: K, v: V, f: F) -> (Option<V>, Self)
where
F: FnOnce(&K, &V, V) -> V,
{
match self.extract_with_key(&k) {
None => (None, self.update(k, v)),
Some((_, v2, m)) => {
let out_v = f(&k, &v2, v);
(Some(v2), m.update(k, out_v))
}
}
}
#[must_use]
pub fn alter<F>(&self, f: F, k: K) -> Self
where
F: FnOnce(Option<V>) -> Option<V>,
{
let pop = self.extract_with_key(&k);
match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) {
(None, None) => self.clone(),
(Some(v), None) => self.update(k, v),
(None, Some((_, _, m))) => m,
(Some(v), Some((_, _, m))) => m.update(k, v),
}
}
#[must_use]
pub fn without<BK>(&self, k: &BK) -> Self
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
match self.extract_with_key(k) {
None => self.clone(),
Some((_, _, map)) => map,
}
}
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&K, &V) -> bool,
{
let old_root = self.root.clone();
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
for ((key, value), hash) in NodeIter::new(&old_root, self.size) {
if !f(key, value) && root.remove(&self.pool.0, hash, 0, key).is_some() {
self.size -= 1;
}
}
}
#[must_use]
pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
self.extract_with_key(k).map(|(_, v, m)| (v, m))
}
#[must_use]
pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
let mut out = self.clone();
out.remove_with_key(k).map(|(k, v)| (k, v, out))
}
#[must_use]
pub fn union(self, other: Self) -> Self {
let (mut to_mutate, to_consume) = if self.len() >= other.len() {
(self, other)
} else {
(other, self)
};
for (k, v) in to_consume {
to_mutate.entry(k).or_insert(v);
}
to_mutate
}
#[inline]
#[must_use]
pub fn union_with<F>(self, other: Self, mut f: F) -> Self
where
F: FnMut(V, V) -> V,
{
self.union_with_key(other, |_, v1, v2| f(v1, v2))
}
#[must_use]
pub fn union_with_key<F>(self, other: Self, mut f: F) -> Self
where
F: FnMut(&K, V, V) -> V,
{
if self.len() >= other.len() {
self.union_with_key_inner(other, f)
} else {
other.union_with_key_inner(self, |key, other_value, self_value| {
f(key, self_value, other_value)
})
}
}
fn union_with_key_inner<F>(mut self, other: Self, mut f: F) -> Self
where
F: FnMut(&K, V, V) -> V,
{
for (key, right_value) in other {
match self.remove(&key) {
None => {
self.insert(key, right_value);
}
Some(left_value) => {
let final_value = f(&key, left_value, right_value);
self.insert(key, final_value);
}
}
}
self
}
#[must_use]
pub fn unions<I>(i: I) -> Self
where
S: Default,
I: IntoIterator<Item = Self>,
{
i.into_iter().fold(Self::default(), Self::union)
}
#[must_use]
pub fn unions_with<I, F>(i: I, f: F) -> Self
where
S: Default,
I: IntoIterator<Item = Self>,
F: Fn(V, V) -> V,
{
i.into_iter()
.fold(Self::default(), |a, b| a.union_with(b, &f))
}
#[must_use]
pub fn unions_with_key<I, F>(i: I, f: F) -> Self
where
S: Default,
I: IntoIterator<Item = Self>,
F: Fn(&K, V, V) -> V,
{
i.into_iter()
.fold(Self::default(), |a, b| a.union_with_key(b, &f))
}
#[inline]
#[must_use]
pub fn difference(self, other: Self) -> Self {
self.symmetric_difference(other)
}
#[inline]
#[must_use]
pub fn symmetric_difference(self, other: Self) -> Self {
self.symmetric_difference_with_key(other, |_, _, _| None)
}
#[inline]
#[must_use]
pub fn difference_with<F>(self, other: Self, f: F) -> Self
where
F: FnMut(V, V) -> Option<V>,
{
self.symmetric_difference_with(other, f)
}
#[inline]
#[must_use]
pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
where
F: FnMut(V, V) -> Option<V>,
{
self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
}
#[must_use]
pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
where
F: FnMut(&K, V, V) -> Option<V>,
{
self.symmetric_difference_with_key(other, f)
}
#[must_use]
pub fn symmetric_difference_with_key<F>(mut self, other: Self, mut f: F) -> Self
where
F: FnMut(&K, V, V) -> Option<V>,
{
let mut out = self.new_from();
for (key, right_value) in other {
match self.remove(&key) {
None => {
out.insert(key, right_value);
}
Some(left_value) => {
if let Some(final_value) = f(&key, left_value, right_value) {
out.insert(key, final_value);
}
}
}
}
out.union(self)
}
#[inline]
#[must_use]
pub fn relative_complement(mut self, other: Self) -> Self {
for (key, _) in other {
let _ = self.remove(&key);
}
self
}
#[inline]
#[must_use]
pub fn intersection(self, other: Self) -> Self {
self.intersection_with_key(other, |_, v, _| v)
}
#[inline]
#[must_use]
pub fn intersection_with<B, C, F>(self, other: HashMap<K, B, S>, mut f: F) -> HashMap<K, C, S>
where
B: Clone,
C: Clone,
F: FnMut(V, B) -> C,
{
self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
}
#[must_use]
pub fn intersection_with_key<B, C, F>(
mut self,
other: HashMap<K, B, S>,
mut f: F,
) -> HashMap<K, C, S>
where
B: Clone,
C: Clone,
F: FnMut(&K, V, B) -> C,
{
let mut out = self.new_from();
for (key, right_value) in other {
match self.remove(&key) {
None => (),
Some(left_value) => {
let result = f(&key, left_value, right_value);
out.insert(key, result);
}
}
}
out
}
}
pub enum Entry<'a, K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
Occupied(OccupiedEntry<'a, K, V, S>),
Vacant(VacantEntry<'a, K, V, S>),
}
impl<'a, K, V, S> Entry<'a, K, V, S>
where
K: 'a + Hash + Eq + Clone,
V: 'a + Clone,
S: 'a + BuildHasher,
{
pub fn or_insert(self, default: V) -> &'a mut V {
self.or_insert_with(|| default)
}
pub fn or_insert_with<F>(self, default: F) -> &'a mut V
where
F: FnOnce() -> V,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default()),
}
}
pub fn or_default(self) -> &'a mut V
where
V: Default,
{
self.or_insert_with(Default::default)
}
#[must_use]
pub fn key(&self) -> &K {
match self {
Entry::Occupied(entry) => entry.key(),
Entry::Vacant(entry) => entry.key(),
}
}
pub fn and_modify<F>(mut self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match &mut self {
Entry::Occupied(ref mut entry) => f(entry.get_mut()),
Entry::Vacant(_) => (),
}
self
}
}
pub struct OccupiedEntry<'a, K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
map: &'a mut HashMap<K, V, S>,
hash: HashBits,
key: K,
}
impl<'a, K, V, S> OccupiedEntry<'a, K, V, S>
where
K: 'a + Hash + Eq + Clone,
V: 'a + Clone,
S: 'a + BuildHasher,
{
#[must_use]
pub fn key(&self) -> &K {
&self.key
}
pub fn remove_entry(self) -> (K, V) {
let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root);
let result = root.remove(&self.map.pool.0, self.hash, 0, &self.key);
self.map.size -= 1;
result.unwrap()
}
#[must_use]
pub fn get(&self) -> &V {
&self.map.root.get(self.hash, 0, &self.key).unwrap().1
}
#[must_use]
pub fn get_mut(&mut self) -> &mut V {
let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root);
&mut root
.get_mut(&self.map.pool.0, self.hash, 0, &self.key)
.unwrap()
.1
}
#[must_use]
pub fn into_mut(self) -> &'a mut V {
let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root);
&mut root
.get_mut(&self.map.pool.0, self.hash, 0, &self.key)
.unwrap()
.1
}
pub fn insert(&mut self, value: V) -> V {
mem::replace(self.get_mut(), value)
}
pub fn remove(self) -> V {
self.remove_entry().1
}
}
pub struct VacantEntry<'a, K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
map: &'a mut HashMap<K, V, S>,
hash: HashBits,
key: K,
}
impl<'a, K, V, S> VacantEntry<'a, K, V, S>
where
K: 'a + Hash + Eq + Clone,
V: 'a + Clone,
S: 'a + BuildHasher,
{
#[must_use]
pub fn key(&self) -> &K {
&self.key
}
#[must_use]
pub fn into_key(self) -> K {
self.key
}
pub fn insert(self, value: V) -> &'a mut V {
let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root);
if root
.insert(&self.map.pool.0, self.hash, 0, (self.key.clone(), value))
.is_none()
{
self.map.size += 1;
}
&mut root
.get_mut(&self.map.pool.0, self.hash, 0, &self.key)
.unwrap()
.1
}
}
impl<K, V, S> Clone for HashMap<K, V, S>
where
K: Clone,
V: Clone,
{
#[inline]
fn clone(&self) -> Self {
HashMap {
root: self.root.clone(),
pool: self.pool.clone(),
size: self.size,
hasher: self.hasher.clone(),
}
}
}
#[cfg(not(has_specialisation))]
impl<K, V, S> PartialEq for HashMap<K, V, S>
where
K: Hash + Eq,
V: PartialEq,
S: BuildHasher,
{
fn eq(&self, other: &Self) -> bool {
self.test_eq(other)
}
}
#[cfg(has_specialisation)]
impl<K, V, S> PartialEq for HashMap<K, V, S>
where
K: Hash + Eq,
V: PartialEq,
S: BuildHasher,
{
default fn eq(&self, other: &Self) -> bool {
self.test_eq(other)
}
}
#[cfg(has_specialisation)]
impl<K, V, S> PartialEq for HashMap<K, V, S>
where
K: Hash + Eq,
V: Eq,
S: BuildHasher,
{
fn eq(&self, other: &Self) -> bool {
if PoolRef::ptr_eq(&self.root, &other.root) {
return true;
}
self.test_eq(other)
}
}
impl<K, V, S> Eq for HashMap<K, V, S>
where
K: Hash + Eq,
V: Eq,
S: BuildHasher,
{
}
impl<K, V, S> PartialOrd for HashMap<K, V, S>
where
K: Hash + Eq + Clone + PartialOrd,
V: PartialOrd + Clone,
S: BuildHasher,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if Ref::ptr_eq(&self.hasher, &other.hasher) {
return self.iter().partial_cmp(other.iter());
}
self.iter().partial_cmp(other.iter())
}
}
impl<K, V, S> Ord for HashMap<K, V, S>
where
K: Hash + Eq + Ord + Clone,
V: Ord + Clone,
S: BuildHasher,
{
fn cmp(&self, other: &Self) -> Ordering {
if Ref::ptr_eq(&self.hasher, &other.hasher) {
return self.iter().cmp(other.iter());
}
self.iter().cmp(other.iter())
}
}
impl<K, V, S> Hash for HashMap<K, V, S>
where
K: Hash + Eq,
V: Hash,
S: BuildHasher,
{
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
for i in self.iter() {
i.hash(state);
}
}
}
impl<K, V, S> Default for HashMap<K, V, S>
where
S: BuildHasher + Default,
{
#[inline]
fn default() -> Self {
let pool = HashMapPool::default();
let root = PoolRef::default(&pool.0);
HashMap {
size: 0,
pool,
root,
hasher: Ref::<S>::default(),
}
}
}
impl<K, V, S> Add for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
type Output = HashMap<K, V, S>;
fn add(self, other: Self) -> Self::Output {
self.union(other)
}
}
impl<'a, K, V, S> Add for &'a HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
type Output = HashMap<K, V, S>;
fn add(self, other: Self) -> Self::Output {
self.clone().union(other.clone())
}
}
impl<K, V, S> Sum for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn sum<I>(it: I) -> Self
where
I: Iterator<Item = Self>,
{
it.fold(Self::default(), |a, b| a + b)
}
}
impl<K, V, S, RK, RV> Extend<(RK, RV)> for HashMap<K, V, S>
where
K: Hash + Eq + Clone + From<RK>,
V: Clone + From<RV>,
S: BuildHasher,
{
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = (RK, RV)>,
{
for (key, value) in iter {
self.insert(From::from(key), From::from(value));
}
}
}
impl<'a, BK, K, V, S> Index<&'a BK> for HashMap<K, V, S>
where
BK: Hash + Eq + ?Sized,
K: Hash + Eq + Borrow<BK>,
S: BuildHasher,
{
type Output = V;
fn index(&self, key: &BK) -> &Self::Output {
match self.root.get(hash_key(&*self.hasher, key), 0, key) {
None => panic!("HashMap::index: invalid key"),
Some(&(_, ref value)) => value,
}
}
}
impl<'a, BK, K, V, S> IndexMut<&'a BK> for HashMap<K, V, S>
where
BK: Hash + Eq + ?Sized,
K: Hash + Eq + Clone + Borrow<BK>,
V: Clone,
S: BuildHasher,
{
fn index_mut(&mut self, key: &BK) -> &mut Self::Output {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.get_mut(&self.pool.0, hash_key(&*self.hasher, key), 0, key) {
None => panic!("HashMap::index_mut: invalid key"),
Some(&mut (_, ref mut value)) => value,
}
}
}
#[cfg(not(has_specialisation))]
impl<K, V, S> Debug for HashMap<K, V, S>
where
K: Hash + Eq + Debug,
V: Debug,
S: BuildHasher,
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut d = f.debug_map();
for (k, v) in self {
d.entry(k, v);
}
d.finish()
}
}
#[cfg(has_specialisation)]
impl<K, V, S> Debug for HashMap<K, V, S>
where
K: Hash + Eq + Debug,
V: Debug,
S: BuildHasher,
{
default fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut d = f.debug_map();
for (k, v) in self {
d.entry(k, v);
}
d.finish()
}
}
#[cfg(has_specialisation)]
impl<K, V, S> Debug for HashMap<K, V, S>
where
K: Hash + Eq + Ord + Debug,
V: Debug,
S: BuildHasher,
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut keys = collections::BTreeSet::new();
keys.extend(self.keys());
let mut d = f.debug_map();
for key in keys {
d.entry(key, &self[key]);
}
d.finish()
}
}
pub struct Iter<'a, K, V> {
it: NodeIter<'a, (K, V)>,
}
impl<'a, K, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|((k, v), _)| (k, v))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {}
impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
pub struct IterMut<'a, K, V>
where
K: Clone,
V: Clone,
{
it: NodeIterMut<'a, (K, V)>,
}
impl<'a, K, V> Iterator for IterMut<'a, K, V>
where
K: Clone,
V: Clone,
{
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|((k, v), _)| (&*k, v))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V>
where
K: Clone,
V: Clone,
{
}
impl<'a, K, V> FusedIterator for IterMut<'a, K, V>
where
K: Clone,
V: Clone,
{
}
pub struct ConsumingIter<A: HashValue> {
it: NodeDrain<A>,
}
impl<A> Iterator for ConsumingIter<A>
where
A: HashValue + Clone,
{
type Item = A;
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|(p, _)| p)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<A> ExactSizeIterator for ConsumingIter<A> where A: HashValue + Clone {}
impl<A> FusedIterator for ConsumingIter<A> where A: HashValue + Clone {}
pub struct Keys<'a, K, V> {
it: NodeIter<'a, (K, V)>,
}
impl<'a, K, V> Iterator for Keys<'a, K, V> {
type Item = &'a K;
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|((k, _), _)| k)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {}
impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
pub struct Values<'a, K, V> {
it: NodeIter<'a, (K, V)>,
}
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|((_, v), _)| v)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {}
impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<K, V, S> IntoIterator for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
type Item = (K, V);
type IntoIter = ConsumingIter<(K, V)>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
ConsumingIter {
it: NodeDrain::new(&self.pool.0, self.root, self.size),
}
}
}
impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from_iter<T>(i: T) -> Self
where
T: IntoIterator<Item = (K, V)>,
{
let mut map = Self::default();
for (k, v) in i {
map.insert(k, v);
}
map
}
}
impl<K, V, S> AsRef<HashMap<K, V, S>> for HashMap<K, V, S> {
#[inline]
fn as_ref(&self) -> &Self {
self
}
}
impl<'m, 'k, 'v, K, V, OK, OV, SA, SB> From<&'m HashMap<&'k K, &'v V, SA>> for HashMap<OK, OV, SB>
where
K: Hash + Eq + ToOwned<Owned = OK> + ?Sized,
V: ToOwned<Owned = OV> + ?Sized,
OK: Hash + Eq + Clone + Borrow<K>,
OV: Borrow<V> + Clone,
SA: BuildHasher,
SB: BuildHasher + Default,
{
fn from(m: &HashMap<&K, &V, SA>) -> Self {
m.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect()
}
}
impl<'a, K, V, S> From<&'a [(K, V)]> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from(m: &'a [(K, V)]) -> Self {
m.iter().cloned().collect()
}
}
impl<K, V, S> From<Vec<(K, V)>> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from(m: Vec<(K, V)>) -> Self {
m.into_iter().collect()
}
}
impl<'a, K, V, S> From<&'a Vec<(K, V)>> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from(m: &'a Vec<(K, V)>) -> Self {
m.iter().cloned().collect()
}
}
impl<K, V, S> From<collections::HashMap<K, V>> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from(m: collections::HashMap<K, V>) -> Self {
m.into_iter().collect()
}
}
impl<'a, K, V, S> From<&'a collections::HashMap<K, V>> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from(m: &'a collections::HashMap<K, V>) -> Self {
m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
}
}
impl<K, V, S> From<collections::BTreeMap<K, V>> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from(m: collections::BTreeMap<K, V>) -> Self {
m.into_iter().collect()
}
}
impl<'a, K, V, S> From<&'a collections::BTreeMap<K, V>> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher + Default,
{
fn from(m: &'a collections::BTreeMap<K, V>) -> Self {
m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
}
}
#[cfg(any(test, feature = "proptest"))]
#[doc(hidden)]
pub mod proptest {
#[deprecated(
since = "14.3.0",
note = "proptest strategies have moved to im::proptest"
)]
pub use crate::proptest::hash_map;
}
#[cfg(test)]
mod test {
use super::*;
use crate::test::LolHasher;
use ::proptest::num::{i16, usize};
use ::proptest::{collection, proptest};
use std::hash::BuildHasherDefault;
#[test]
fn safe_mutation() {
let v1: HashMap<usize, usize> = (0..131_072).map(|i| (i, i)).collect::<HashMap<_, _>>();
let mut v2 = v1.clone();
v2.insert(131_000, 23);
assert_eq!(Some(&23), v2.get(&131_000));
assert_eq!(Some(&131_000), v1.get(&131_000));
}
#[test]
fn index_operator() {
let mut map = hashmap![1 => 2, 3 => 4, 5 => 6];
assert_eq!(4, map[&3]);
map[&3] = 8;
assert_eq!(hashmap![1 => 2, 3 => 8, 5 => 6], map);
}
#[test]
fn proper_formatting() {
let map = hashmap![1 => 2];
assert_eq!("{1: 2}", format!("{:?}", map));
assert_eq!("{}", format!("{:?}", HashMap::<(), ()>::new()));
}
#[test]
fn remove_failing() {
let pairs = [(1469, 0), (-67, 0)];
let mut m: collections::HashMap<i16, i16, _> =
collections::HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
for &(ref k, ref v) in &pairs {
m.insert(*k, *v);
}
let mut map: HashMap<i16, i16, _> =
HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
for (k, v) in &m {
map = map.update(*k, *v);
}
for k in m.keys() {
let l = map.len();
assert_eq!(m.get(k).cloned(), map.get(k).cloned());
map = map.without(k);
assert_eq!(None, map.get(k));
assert_eq!(l - 1, map.len());
}
}
#[test]
fn match_string_keys_with_string_slices() {
let mut map: HashMap<String, i32> =
From::from(&hashmap! { "foo" => &1, "bar" => &2, "baz" => &3 });
assert_eq!(Some(&1), map.get("foo"));
map = map.without("foo");
assert_eq!(Some(3), map.remove("baz"));
map["bar"] = 8;
assert_eq!(8, map["bar"]);
}
#[test]
fn macro_allows_trailing_comma() {
let map1 = hashmap! {"x" => 1, "y" => 2};
let map2 = hashmap! {
"x" => 1,
"y" => 2,
};
assert_eq!(map1, map2);
}
#[test]
fn remove_top_level_collisions() {
let pairs = vec![9, 2569, 27145];
let mut map: HashMap<i16, i16, BuildHasherDefault<LolHasher>> = Default::default();
for k in pairs.clone() {
map.insert(k, k);
}
assert_eq!(pairs.len(), map.len());
let keys: Vec<_> = map.keys().cloned().collect();
for k in keys {
let l = map.len();
assert_eq!(Some(&k), map.get(&k));
map.remove(&k);
assert_eq!(None, map.get(&k));
assert_eq!(l - 1, map.len());
}
}
#[test]
fn entry_api() {
let mut map = hashmap! {"bar" => 5};
map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
assert_eq!(1, map[&"foo"]);
map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
assert_eq!(6, map[&"foo"]);
map.entry("bar").and_modify(|v| *v += 5).or_insert(1);
assert_eq!(10, map[&"bar"]);
assert_eq!(
10,
match map.entry("bar") {
Entry::Occupied(entry) => entry.remove(),
_ => panic!(),
}
);
assert!(!map.contains_key(&"bar"));
}
#[test]
fn refpool_crash() {
let _map = HashMap::<u128, usize>::new();
}
#[test]
fn large_map() {
let mut map = HashMap::new();
let size = 32769;
for i in 0..size {
map.insert(i, i);
}
assert_eq!(size, map.len());
for i in 0..size {
assert_eq!(Some(&i), map.get(&i));
}
}
proptest! {
#[test]
fn update_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) {
let mut map: HashMap<i16, i16, BuildHasherDefault<LolHasher>> = Default::default();
for (index, (k, v)) in m.iter().enumerate() {
map = map.update(*k, *v);
assert_eq!(Some(v), map.get(k));
assert_eq!(index + 1, map.len());
}
}
#[test]
fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) {
let map: HashMap<i16, i16> =
FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
assert_eq!(m.len(), map.len());
}
#[test]
fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) {
let map: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
assert_eq!(m.len(), map.iter().count());
}
#[test]
fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) {
let map1: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
let map2: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
assert_eq!(map1, map2);
}
#[test]
fn lookup(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) {
let map: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
for (k, v) in m {
assert_eq!(Some(*v), map.get(k).cloned());
}
}
#[test]
fn without(ref pairs in collection::vec((i16::ANY, i16::ANY), 0..100)) {
let mut m: collections::HashMap<i16, i16, _> =
collections::HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
for &(ref k, ref v) in pairs {
m.insert(*k, *v);
}
let mut map: HashMap<i16, i16, _> = HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
for (k, v) in &m {
map = map.update(*k, *v);
}
for k in m.keys() {
let l = map.len();
assert_eq!(m.get(k).cloned(), map.get(k).cloned());
map = map.without(k);
assert_eq!(None, map.get(k));
assert_eq!(l - 1, map.len());
}
}
#[test]
fn insert(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) {
let mut mut_map: HashMap<i16, i16, BuildHasherDefault<LolHasher>> = Default::default();
let mut map: HashMap<i16, i16, BuildHasherDefault<LolHasher>> = Default::default();
for (count, (k, v)) in m.iter().enumerate() {
map = map.update(*k, *v);
mut_map.insert(*k, *v);
assert_eq!(count + 1, map.len());
assert_eq!(count + 1, mut_map.len());
}
assert_eq!(map, mut_map);
}
#[test]
fn remove(ref pairs in collection::vec((i16::ANY, i16::ANY), 0..100)) {
let mut m: collections::HashMap<i16, i16, _> =
collections::HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
for &(ref k, ref v) in pairs {
m.insert(*k, *v);
}
let mut map: HashMap<i16, i16, _> = HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
for (k, v) in &m {
map.insert(*k, *v);
}
for k in m.keys() {
let l = map.len();
assert_eq!(m.get(k).cloned(), map.get(k).cloned());
map.remove(k);
assert_eq!(None, map.get(k));
assert_eq!(l - 1, map.len());
}
}
#[test]
fn delete_and_reinsert(
ref input in collection::hash_map(i16::ANY, i16::ANY, 1..100),
index_rand in usize::ANY
) {
let index = *input.keys().nth(index_rand % input.len()).unwrap();
let map1: HashMap<_, _> = HashMap::from_iter(input.clone());
let (val, map2) = map1.extract(&index).unwrap();
let map3 = map2.update(index, val);
for key in map2.keys() {
assert!(*key != index);
}
assert_eq!(map1.len(), map2.len() + 1);
assert_eq!(map1, map3);
}
#[test]
fn proptest_works(ref m in proptest::hash_map(0..9999, ".*", 10..100)) {
assert!(m.len() < 100);
assert!(m.len() >= 10);
}
#[test]
fn exact_size_iterator(ref m in proptest::hash_map(i16::ANY, i16::ANY, 0..100)) {
let mut should_be = m.len();
let mut it = m.iter();
loop {
assert_eq!(should_be, it.len());
match it.next() {
None => break,
Some(_) => should_be -= 1,
}
}
assert_eq!(0, it.len());
}
}
}