use crate::raw::{Allocator, Bucket, Global, RawDrain, RawIntoIter, RawIter, RawTable};
use crate::{Equivalent, TryReserveError};
use core::borrow::Borrow;
use core::fmt::{self, Debug};
use core::hash::{BuildHasher, Hash};
use core::iter::{FromIterator, FusedIterator};
use core::marker::PhantomData;
use core::mem;
use core::ops::Index;
#[cfg(feature = "ahash")]
pub type DefaultHashBuilder = core::hash::BuildHasherDefault<ahash::AHasher>;
#[cfg(not(feature = "ahash"))]
pub enum DefaultHashBuilder {}
pub struct HashMap<K, V, S = DefaultHashBuilder, A: Allocator + Clone = Global> {
pub(crate) hash_builder: S,
pub(crate) table: RawTable<(K, V), A>,
}
impl<K: Clone, V: Clone, S: Clone, A: Allocator + Clone> Clone for HashMap<K, V, S, A> {
fn clone(&self) -> Self {
HashMap {
hash_builder: self.hash_builder.clone(),
table: self.table.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.table.clone_from(&source.table);
self.hash_builder.clone_from(&source.hash_builder);
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) fn make_hasher<Q, V, S>(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_
where
Q: Hash,
S: BuildHasher,
{
move |val| make_hash::<Q, S>(hash_builder, &val.0)
}
#[cfg_attr(feature = "inline-more", inline)]
fn equivalent_key<Q, K, V>(k: &Q) -> impl Fn(&(K, V)) -> bool + '_
where
Q: ?Sized + Equivalent<K>,
{
move |x| k.equivalent(&x.0)
}
#[cfg_attr(feature = "inline-more", inline)]
fn equivalent<Q, K>(k: &Q) -> impl Fn(&K) -> bool + '_
where
Q: ?Sized + Equivalent<K>,
{
move |x| k.equivalent(x)
}
#[cfg(not(feature = "nightly"))]
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
where
Q: Hash + ?Sized,
S: BuildHasher,
{
use core::hash::Hasher;
let mut state = hash_builder.build_hasher();
val.hash(&mut state);
state.finish()
}
#[cfg(feature = "nightly")]
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
where
Q: Hash + ?Sized,
S: BuildHasher,
{
hash_builder.hash_one(val)
}
#[cfg(not(feature = "nightly"))]
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) fn make_insert_hash<K, S>(hash_builder: &S, val: &K) -> u64
where
K: Hash,
S: BuildHasher,
{
use core::hash::Hasher;
let mut state = hash_builder.build_hasher();
val.hash(&mut state);
state.finish()
}
#[cfg(feature = "nightly")]
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) fn make_insert_hash<K, S>(hash_builder: &S, val: &K) -> u64
where
K: Hash,
S: BuildHasher,
{
hash_builder.hash_one(val)
}
#[cfg(feature = "ahash")]
impl<K, V> HashMap<K, V, DefaultHashBuilder> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn new() -> Self {
Self::default()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity(capacity: usize) -> Self {
Self::with_capacity_and_hasher(capacity, DefaultHashBuilder::default())
}
}
#[cfg(feature = "ahash")]
impl<K, V, A: Allocator + Clone> HashMap<K, V, DefaultHashBuilder, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn new_in(alloc: A) -> Self {
Self::with_hasher_in(DefaultHashBuilder::default(), alloc)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
Self::with_capacity_and_hasher_in(capacity, DefaultHashBuilder::default(), alloc)
}
}
impl<K, V, S> HashMap<K, V, S> {
#[cfg_attr(feature = "inline-more", inline)]
pub const fn with_hasher(hash_builder: S) -> Self {
Self {
hash_builder,
table: RawTable::new(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
Self {
hash_builder,
table: RawTable::with_capacity(capacity),
}
}
}
impl<K, V, S, A: Allocator + Clone> HashMap<K, V, S, A> {
#[inline]
pub fn allocator(&self) -> &A {
self.table.allocator()
}
#[cfg_attr(feature = "inline-more", inline)]
pub const fn with_hasher_in(hash_builder: S, alloc: A) -> Self {
Self {
hash_builder,
table: RawTable::new_in(alloc),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> Self {
Self {
hash_builder,
table: RawTable::with_capacity_in(capacity, alloc),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn hasher(&self) -> &S {
&self.hash_builder
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn capacity(&self) -> usize {
self.table.capacity()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn keys(&self) -> Keys<'_, K, V> {
Keys { inner: self.iter() }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn values(&self) -> Values<'_, K, V> {
Values { inner: self.iter() }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
ValuesMut {
inner: self.iter_mut(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter(&self) -> Iter<'_, K, V> {
unsafe {
Iter {
inner: self.table.iter(),
marker: PhantomData,
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
unsafe {
IterMut {
inner: self.table.iter(),
marker: PhantomData,
}
}
}
#[cfg(test)]
#[cfg_attr(feature = "inline-more", inline)]
fn raw_capacity(&self) -> usize {
self.table.buckets()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn len(&self) -> usize {
self.table.len()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn drain(&mut self) -> Drain<'_, K, V, A> {
Drain {
inner: self.table.drain(),
}
}
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&K, &mut V) -> bool,
{
unsafe {
for item in self.table.iter() {
let &mut (ref key, ref mut value) = item.as_mut();
if !f(key, value) {
self.table.erase(item);
}
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn drain_filter<F>(&mut self, f: F) -> DrainFilter<'_, K, V, F, A>
where
F: FnMut(&K, &mut V) -> bool,
{
DrainFilter {
f,
inner: DrainFilterInner {
iter: unsafe { self.table.iter() },
table: &mut self.table,
},
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn clear(&mut self) {
self.table.clear();
}
#[inline]
pub fn into_keys(self) -> IntoKeys<K, V, A> {
IntoKeys {
inner: self.into_iter(),
}
}
#[inline]
pub fn into_values(self) -> IntoValues<K, V, A> {
IntoValues {
inner: self.into_iter(),
}
}
}
impl<K, V, S, A> HashMap<K, V, S, A>
where
K: Eq + Hash,
S: BuildHasher,
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
pub fn reserve(&mut self, additional: usize) {
self.table
.reserve(additional, make_hasher::<_, V, S>(&self.hash_builder));
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.table
.try_reserve(additional, make_hasher::<_, V, S>(&self.hash_builder))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn shrink_to_fit(&mut self) {
self.table
.shrink_to(0, make_hasher::<_, V, S>(&self.hash_builder));
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.table
.shrink_to(min_capacity, make_hasher::<_, V, S>(&self.hash_builder));
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> {
let hash = make_insert_hash::<K, S>(&self.hash_builder, &key);
if let Some(elem) = self.table.find(hash, equivalent_key(&key)) {
Entry::Occupied(OccupiedEntry {
hash,
key: Some(key),
elem,
table: self,
})
} else {
Entry::Vacant(VacantEntry {
hash,
key,
table: self,
})
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn entry_ref<'a, 'b, Q: ?Sized>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A>
where
Q: Hash + Equivalent<K>,
{
let hash = make_hash::<Q, S>(&self.hash_builder, key);
if let Some(elem) = self.table.find(hash, equivalent_key(key)) {
EntryRef::Occupied(OccupiedEntryRef {
hash,
key: Some(KeyOrRef::Borrowed(key)),
elem,
table: self,
})
} else {
EntryRef::Vacant(VacantEntryRef {
hash,
key: KeyOrRef::Borrowed(key),
table: self,
})
}
}
#[inline]
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
where
Q: Hash + Equivalent<K>,
{
match self.get_inner(k) {
Some(&(_, ref v)) => Some(v),
None => None,
}
}
#[inline]
pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
where
Q: Hash + Equivalent<K>,
{
match self.get_inner(k) {
Some(&(ref key, ref value)) => Some((key, value)),
None => None,
}
}
#[inline]
fn get_inner<Q: ?Sized>(&self, k: &Q) -> Option<&(K, V)>
where
Q: Hash + Equivalent<K>,
{
if self.table.is_empty() {
None
} else {
let hash = make_hash::<Q, S>(&self.hash_builder, k);
self.table.get(hash, equivalent_key(k))
}
}
#[inline]
pub fn get_key_value_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<(&K, &mut V)>
where
Q: Hash + Equivalent<K>,
{
match self.get_inner_mut(k) {
Some(&mut (ref key, ref mut value)) => Some((key, value)),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
where
Q: Hash + Equivalent<K>,
{
self.get_inner(k).is_some()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
where
Q: Hash + Equivalent<K>,
{
match self.get_inner_mut(k) {
Some(&mut (_, ref mut v)) => Some(v),
None => None,
}
}
#[inline]
fn get_inner_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut (K, V)>
where
Q: Hash + Equivalent<K>,
{
if self.table.is_empty() {
None
} else {
let hash = make_hash::<Q, S>(&self.hash_builder, k);
self.table.get_mut(hash, equivalent_key(k))
}
}
pub fn get_many_mut<Q: ?Sized, const N: usize>(&mut self, ks: [&Q; N]) -> Option<[&'_ mut V; N]>
where
Q: Hash + Equivalent<K>,
{
self.get_many_mut_inner(ks).map(|res| res.map(|(_, v)| v))
}
pub unsafe fn get_many_unchecked_mut<Q: ?Sized, const N: usize>(
&mut self,
ks: [&Q; N],
) -> Option<[&'_ mut V; N]>
where
Q: Hash + Equivalent<K>,
{
self.get_many_unchecked_mut_inner(ks)
.map(|res| res.map(|(_, v)| v))
}
pub fn get_many_key_value_mut<Q: ?Sized, const N: usize>(
&mut self,
ks: [&Q; N],
) -> Option<[(&'_ K, &'_ mut V); N]>
where
Q: Hash + Equivalent<K>,
{
self.get_many_mut_inner(ks)
.map(|res| res.map(|(k, v)| (&*k, v)))
}
pub unsafe fn get_many_key_value_unchecked_mut<Q: ?Sized, const N: usize>(
&mut self,
ks: [&Q; N],
) -> Option<[(&'_ K, &'_ mut V); N]>
where
Q: Hash + Equivalent<K>,
{
self.get_many_unchecked_mut_inner(ks)
.map(|res| res.map(|(k, v)| (&*k, v)))
}
fn get_many_mut_inner<Q: ?Sized, const N: usize>(
&mut self,
ks: [&Q; N],
) -> Option<[&'_ mut (K, V); N]>
where
Q: Hash + Equivalent<K>,
{
let hashes = self.build_hashes_inner(ks);
self.table
.get_many_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
}
unsafe fn get_many_unchecked_mut_inner<Q: ?Sized, const N: usize>(
&mut self,
ks: [&Q; N],
) -> Option<[&'_ mut (K, V); N]>
where
Q: Hash + Equivalent<K>,
{
let hashes = self.build_hashes_inner(ks);
self.table
.get_many_unchecked_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
}
fn build_hashes_inner<Q: ?Sized, const N: usize>(&self, ks: [&Q; N]) -> [u64; N]
where
Q: Hash + Equivalent<K>,
{
let mut hashes = [0_u64; N];
for i in 0..N {
hashes[i] = make_hash::<Q, S>(&self.hash_builder, ks[i]);
}
hashes
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&mut self, k: K, v: V) -> Option<V> {
let hash = make_insert_hash::<K, S>(&self.hash_builder, &k);
if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) {
Some(mem::replace(item, v))
} else {
self.table
.insert(hash, (k, v), make_hasher::<_, V, S>(&self.hash_builder));
None
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) {
let hash = make_insert_hash::<K, S>(&self.hash_builder, &k);
let bucket = self
.table
.insert(hash, (k, v), make_hasher::<_, V, S>(&self.hash_builder));
let (k_ref, v_ref) = unsafe { bucket.as_mut() };
(k_ref, v_ref)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn try_insert(
&mut self,
key: K,
value: V,
) -> Result<&mut V, OccupiedError<'_, K, V, S, A>> {
match self.entry(key) {
Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
Entry::Vacant(entry) => Ok(entry.insert(value)),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
where
Q: Hash + Equivalent<K>,
{
match self.remove_entry(k) {
Some((_, v)) => Some(v),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
where
Q: Hash + Equivalent<K>,
{
let hash = make_hash::<Q, S>(&self.hash_builder, k);
self.table.remove_entry(hash, equivalent_key(k))
}
}
impl<K, V, S, A: Allocator + Clone> HashMap<K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S, A> {
RawEntryBuilderMut { map: self }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S, A> {
RawEntryBuilder { map: self }
}
#[cfg(feature = "raw")]
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_table(&mut self) -> &mut RawTable<(K, V), A> {
&mut self.table
}
}
impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
where
K: Eq + Hash,
V: PartialEq,
S: BuildHasher,
A: Allocator + Clone,
{
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
self.iter()
.all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
}
}
impl<K, V, S, A> Eq for HashMap<K, V, S, A>
where
K: Eq + Hash,
V: Eq,
S: BuildHasher,
A: Allocator + Clone,
{
}
impl<K, V, S, A> Debug for HashMap<K, V, S, A>
where
K: Debug,
V: Debug,
A: Allocator + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<K, V, S, A> Default for HashMap<K, V, S, A>
where
S: Default,
A: Default + Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn default() -> Self {
Self::with_hasher_in(Default::default(), Default::default())
}
}
impl<K, Q: ?Sized, V, S, A> Index<&Q> for HashMap<K, V, S, A>
where
K: Eq + Hash,
Q: Hash + Equivalent<K>,
S: BuildHasher,
A: Allocator + Clone,
{
type Output = V;
#[cfg_attr(feature = "inline-more", inline)]
fn index(&self, key: &Q) -> &V {
self.get(key).expect("no entry found for key")
}
}
#[cfg(feature = "ahash")]
impl<K, V, A, const N: usize> From<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A>
where
K: Eq + Hash,
A: Default + Allocator + Clone,
{
fn from(arr: [(K, V); N]) -> Self {
arr.into_iter().collect()
}
}
pub struct Iter<'a, K, V> {
inner: RawIter<(K, V)>,
marker: PhantomData<(&'a K, &'a V)>,
}
impl<K, V> Clone for Iter<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Iter {
inner: self.inner.clone(),
marker: PhantomData,
}
}
}
impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub struct IterMut<'a, K, V> {
inner: RawIter<(K, V)>,
marker: PhantomData<(&'a K, &'a mut V)>,
}
unsafe impl<K: Send, V: Send> Send for IterMut<'_, K, V> {}
impl<K, V> IterMut<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
pub(super) fn iter(&self) -> Iter<'_, K, V> {
Iter {
inner: self.inner.clone(),
marker: PhantomData,
}
}
}
pub struct IntoIter<K, V, A: Allocator + Clone = Global> {
inner: RawIntoIter<(K, V), A>,
}
impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub(super) fn iter(&self) -> Iter<'_, K, V> {
Iter {
inner: self.inner.iter(),
marker: PhantomData,
}
}
}
pub struct IntoKeys<K, V, A: Allocator + Clone = Global> {
inner: IntoIter<K, V, A>,
}
impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
type Item = K;
#[inline]
fn next(&mut self) -> Option<K> {
self.inner.next().map(|(k, _)| k)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
#[inline]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
impl<K: Debug, V: Debug, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.inner.iter().map(|(k, _)| k))
.finish()
}
}
pub struct IntoValues<K, V, A: Allocator + Clone = Global> {
inner: IntoIter<K, V, A>,
}
impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
type Item = V;
#[inline]
fn next(&mut self) -> Option<V> {
self.inner.next().map(|(_, v)| v)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
#[inline]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
impl<K, V: Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.inner.iter().map(|(_, v)| v))
.finish()
}
}
pub struct Keys<'a, K, V> {
inner: Iter<'a, K, V>,
}
impl<K, V> Clone for Keys<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Keys {
inner: self.inner.clone(),
}
}
}
impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub struct Values<'a, K, V> {
inner: Iter<'a, K, V>,
}
impl<K, V> Clone for Values<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Values {
inner: self.inner.clone(),
}
}
}
impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub struct Drain<'a, K, V, A: Allocator + Clone = Global> {
inner: RawDrain<'a, (K, V), A>,
}
impl<K, V, A: Allocator + Clone> Drain<'_, K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub(super) fn iter(&self) -> Iter<'_, K, V> {
Iter {
inner: self.inner.iter(),
marker: PhantomData,
}
}
}
pub struct DrainFilter<'a, K, V, F, A: Allocator + Clone = Global>
where
F: FnMut(&K, &mut V) -> bool,
{
f: F,
inner: DrainFilterInner<'a, K, V, A>,
}
impl<'a, K, V, F, A> Drop for DrainFilter<'a, K, V, F, A>
where
F: FnMut(&K, &mut V) -> bool,
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn drop(&mut self) {
while let Some(item) = self.next() {
let guard = ConsumeAllOnDrop(self);
drop(item);
mem::forget(guard);
}
}
}
pub(super) struct ConsumeAllOnDrop<'a, T: Iterator>(pub &'a mut T);
impl<T: Iterator> Drop for ConsumeAllOnDrop<'_, T> {
#[cfg_attr(feature = "inline-more", inline)]
fn drop(&mut self) {
self.0.for_each(drop);
}
}
impl<K, V, F, A> Iterator for DrainFilter<'_, K, V, F, A>
where
F: FnMut(&K, &mut V) -> bool,
A: Allocator + Clone,
{
type Item = (K, V);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<Self::Item> {
self.inner.next(&mut self.f)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.inner.iter.size_hint().1)
}
}
impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
pub(super) struct DrainFilterInner<'a, K, V, A: Allocator + Clone> {
pub iter: RawIter<(K, V)>,
pub table: &'a mut RawTable<(K, V), A>,
}
impl<K, V, A: Allocator + Clone> DrainFilterInner<'_, K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub(super) fn next<F>(&mut self, f: &mut F) -> Option<(K, V)>
where
F: FnMut(&K, &mut V) -> bool,
{
unsafe {
for item in &mut self.iter {
let &mut (ref key, ref mut value) = item.as_mut();
if f(key, value) {
return Some(self.table.remove(item));
}
}
}
None
}
}
pub struct ValuesMut<'a, K, V> {
inner: IterMut<'a, K, V>,
}
pub struct RawEntryBuilderMut<'a, K, V, S, A: Allocator + Clone = Global> {
map: &'a mut HashMap<K, V, S, A>,
}
pub enum RawEntryMut<'a, K, V, S, A: Allocator + Clone = Global> {
Occupied(RawOccupiedEntryMut<'a, K, V, S, A>),
Vacant(RawVacantEntryMut<'a, K, V, S, A>),
}
pub struct RawOccupiedEntryMut<'a, K, V, S, A: Allocator + Clone = Global> {
elem: Bucket<(K, V)>,
table: &'a mut RawTable<(K, V), A>,
hash_builder: &'a S,
}
unsafe impl<K, V, S, A> Send for RawOccupiedEntryMut<'_, K, V, S, A>
where
K: Send,
V: Send,
S: Send,
A: Send + Allocator + Clone,
{
}
unsafe impl<K, V, S, A> Sync for RawOccupiedEntryMut<'_, K, V, S, A>
where
K: Sync,
V: Sync,
S: Sync,
A: Sync + Allocator + Clone,
{
}
pub struct RawVacantEntryMut<'a, K, V, S, A: Allocator + Clone = Global> {
table: &'a mut RawTable<(K, V), A>,
hash_builder: &'a S,
}
pub struct RawEntryBuilder<'a, K, V, S, A: Allocator + Clone = Global> {
map: &'a HashMap<K, V, S, A>,
}
impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::wrong_self_convention)]
pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S, A>
where
S: BuildHasher,
Q: Hash + Equivalent<K>,
{
let hash = make_hash::<Q, S>(&self.map.hash_builder, k);
self.from_key_hashed_nocheck(hash, k)
}
#[inline]
#[allow(clippy::wrong_self_convention)]
pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A>
where
Q: Equivalent<K>,
{
self.from_hash(hash, equivalent(k))
}
}
impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::wrong_self_convention)]
pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A>
where
for<'b> F: FnMut(&'b K) -> bool,
{
self.search(hash, is_match)
}
#[cfg_attr(feature = "inline-more", inline)]
fn search<F>(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A>
where
for<'b> F: FnMut(&'b K) -> bool,
{
match self.map.table.find(hash, |(k, _)| is_match(k)) {
Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut {
elem,
table: &mut self.map.table,
hash_builder: &self.map.hash_builder,
}),
None => RawEntryMut::Vacant(RawVacantEntryMut {
table: &mut self.map.table,
hash_builder: &self.map.hash_builder,
}),
}
}
}
impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::wrong_self_convention)]
pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
where
S: BuildHasher,
Q: Hash + Equivalent<K>,
{
let hash = make_hash::<Q, S>(&self.map.hash_builder, k);
self.from_key_hashed_nocheck(hash, k)
}
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::wrong_self_convention)]
pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
where
Q: Equivalent<K>,
{
self.from_hash(hash, equivalent(k))
}
#[cfg_attr(feature = "inline-more", inline)]
fn search<F>(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)>
where
F: FnMut(&K) -> bool,
{
match self.map.table.get(hash, |(k, _)| is_match(k)) {
Some(&(ref key, ref value)) => Some((key, value)),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::wrong_self_convention)]
pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
where
F: FnMut(&K) -> bool,
{
self.search(hash, is_match)
}
}
impl<'a, K, V, S, A: Allocator + Clone> RawEntryMut<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A>
where
K: Hash,
S: BuildHasher,
{
match self {
RawEntryMut::Occupied(mut entry) => {
entry.insert(value);
entry
}
RawEntryMut::Vacant(entry) => entry.insert_entry(key, value),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
where
K: Hash,
S: BuildHasher,
{
match self {
RawEntryMut::Occupied(entry) => entry.into_key_value(),
RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
where
F: FnOnce() -> (K, V),
K: Hash,
S: BuildHasher,
{
match self {
RawEntryMut::Occupied(entry) => entry.into_key_value(),
RawEntryMut::Vacant(entry) => {
let (k, v) = default();
entry.insert(k, v)
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut K, &mut V),
{
match self {
RawEntryMut::Occupied(mut entry) => {
{
let (k, v) = entry.get_key_value_mut();
f(k, v);
}
RawEntryMut::Occupied(entry)
}
RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_replace_entry_with<F>(self, f: F) -> Self
where
F: FnOnce(&K, V) -> Option<V>,
{
match self {
RawEntryMut::Occupied(entry) => entry.replace_entry_with(f),
RawEntryMut::Vacant(_) => self,
}
}
}
impl<'a, K, V, S, A: Allocator + Clone> RawOccupiedEntryMut<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &K {
unsafe { &self.elem.as_ref().0 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn key_mut(&mut self) -> &mut K {
unsafe { &mut self.elem.as_mut().0 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_key(self) -> &'a mut K {
unsafe { &mut self.elem.as_mut().0 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> &V {
unsafe { &self.elem.as_ref().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_mut(self) -> &'a mut V {
unsafe { &mut self.elem.as_mut().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut(&mut self) -> &mut V {
unsafe { &mut self.elem.as_mut().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_key_value(&self) -> (&K, &V) {
unsafe {
let &(ref key, ref value) = self.elem.as_ref();
(key, value)
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
unsafe {
let &mut (ref mut key, ref mut value) = self.elem.as_mut();
(key, value)
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
unsafe {
let &mut (ref mut key, ref mut value) = self.elem.as_mut();
(key, value)
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&mut self, value: V) -> V {
mem::replace(self.get_mut(), value)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_key(&mut self, key: K) -> K {
mem::replace(self.key_mut(), key)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove(self) -> V {
self.remove_entry().1
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry(self) -> (K, V) {
unsafe { self.table.remove(self.elem) }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry_with<F>(self, f: F) -> RawEntryMut<'a, K, V, S, A>
where
F: FnOnce(&K, V) -> Option<V>,
{
unsafe {
let still_occupied = self
.table
.replace_bucket_with(self.elem.clone(), |(key, value)| {
f(&key, value).map(|new_value| (key, new_value))
});
if still_occupied {
RawEntryMut::Occupied(self)
} else {
RawEntryMut::Vacant(RawVacantEntryMut {
table: self.table,
hash_builder: self.hash_builder,
})
}
}
}
}
impl<'a, K, V, S, A: Allocator + Clone> RawVacantEntryMut<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
where
K: Hash,
S: BuildHasher,
{
let hash = make_insert_hash::<K, S>(self.hash_builder, &key);
self.insert_hashed_nocheck(hash, key, value)
}
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::shadow_unrelated)]
pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
where
K: Hash,
S: BuildHasher,
{
let &mut (ref mut k, ref mut v) = self.table.insert_entry(
hash,
(key, value),
make_hasher::<_, V, S>(self.hash_builder),
);
(k, v)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_with_hasher<H>(
self,
hash: u64,
key: K,
value: V,
hasher: H,
) -> (&'a mut K, &'a mut V)
where
H: Fn(&K) -> u64,
{
let &mut (ref mut k, ref mut v) = self
.table
.insert_entry(hash, (key, value), |x| hasher(&x.0));
(k, v)
}
#[cfg_attr(feature = "inline-more", inline)]
fn insert_entry(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A>
where
K: Hash,
S: BuildHasher,
{
let hash = make_insert_hash::<K, S>(self.hash_builder, &key);
let elem = self.table.insert(
hash,
(key, value),
make_hasher::<_, V, S>(self.hash_builder),
);
RawOccupiedEntryMut {
elem,
table: self.table,
hash_builder: self.hash_builder,
}
}
}
impl<K, V, S, A: Allocator + Clone> Debug for RawEntryBuilderMut<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RawEntryBuilder").finish()
}
}
impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for RawEntryMut<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
}
}
}
impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for RawOccupiedEntryMut<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RawOccupiedEntryMut")
.field("key", self.key())
.field("value", self.get())
.finish()
}
}
impl<K, V, S, A: Allocator + Clone> Debug for RawVacantEntryMut<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RawVacantEntryMut").finish()
}
}
impl<K, V, S, A: Allocator + Clone> Debug for RawEntryBuilder<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RawEntryBuilder").finish()
}
}
pub enum Entry<'a, K, V, S, A = Global>
where
A: Allocator + Clone,
{
Occupied(OccupiedEntry<'a, K, V, S, A>),
Vacant(VacantEntry<'a, K, V, S, A>),
}
impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for Entry<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
}
}
}
pub struct OccupiedEntry<'a, K, V, S, A: Allocator + Clone = Global> {
hash: u64,
key: Option<K>,
elem: Bucket<(K, V)>,
table: &'a mut HashMap<K, V, S, A>,
}
unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A>
where
K: Send,
V: Send,
S: Send,
A: Send + Allocator + Clone,
{
}
unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A>
where
K: Sync,
V: Sync,
S: Sync,
A: Sync + Allocator + Clone,
{
}
impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for OccupiedEntry<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedEntry")
.field("key", self.key())
.field("value", self.get())
.finish()
}
}
pub struct VacantEntry<'a, K, V, S, A: Allocator + Clone = Global> {
hash: u64,
key: K,
table: &'a mut HashMap<K, V, S, A>,
}
impl<K: Debug, V, S, A: Allocator + Clone> Debug for VacantEntry<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("VacantEntry").field(self.key()).finish()
}
}
pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global>
where
A: Allocator + Clone,
{
Occupied(OccupiedEntryRef<'a, 'b, K, Q, V, S, A>),
Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>),
}
impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator + Clone> Debug
for EntryRef<'_, '_, K, Q, V, S, A>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
EntryRef::Vacant(ref v) => f.debug_tuple("EntryRef").field(v).finish(),
EntryRef::Occupied(ref o) => f.debug_tuple("EntryRef").field(o).finish(),
}
}
}
enum KeyOrRef<'a, K, Q: ?Sized> {
Borrowed(&'a Q),
Owned(K),
}
impl<'a, K, Q: ?Sized> KeyOrRef<'a, K, Q> {
fn into_owned(self) -> K
where
K: From<&'a Q>,
{
match self {
Self::Borrowed(borrowed) => borrowed.into(),
Self::Owned(owned) => owned,
}
}
}
impl<'a, K: Borrow<Q>, Q: ?Sized> AsRef<Q> for KeyOrRef<'a, K, Q> {
fn as_ref(&self) -> &Q {
match self {
Self::Borrowed(borrowed) => borrowed,
Self::Owned(owned) => owned.borrow(),
}
}
}
pub struct OccupiedEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone = Global> {
hash: u64,
key: Option<KeyOrRef<'b, K, Q>>,
elem: Bucket<(K, V)>,
table: &'a mut HashMap<K, V, S, A>,
}
unsafe impl<'a, 'b, K, Q, V, S, A> Send for OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
where
K: Send,
Q: Sync + ?Sized,
V: Send,
S: Send,
A: Send + Allocator + Clone,
{
}
unsafe impl<'a, 'b, K, Q, V, S, A> Sync for OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
where
K: Sync,
Q: Sync + ?Sized,
V: Sync,
S: Sync,
A: Sync + Allocator + Clone,
{
}
impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator + Clone> Debug
for OccupiedEntryRef<'_, '_, K, Q, V, S, A>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedEntryRef")
.field("key", &self.key())
.field("value", &self.get())
.finish()
}
}
pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone = Global> {
hash: u64,
key: KeyOrRef<'b, K, Q>,
table: &'a mut HashMap<K, V, S, A>,
}
impl<K: Borrow<Q>, Q: ?Sized + Debug, V, S, A: Allocator + Clone> Debug
for VacantEntryRef<'_, '_, K, Q, V, S, A>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
}
}
pub struct OccupiedError<'a, K, V, S, A: Allocator + Clone = Global> {
pub entry: OccupiedEntry<'a, K, V, S, A>,
pub value: V,
}
impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for OccupiedError<'_, K, V, S, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedError")
.field("key", self.entry.key())
.field("old_value", self.entry.get())
.field("new_value", &self.value)
.finish()
}
}
impl<'a, K: Debug, V: Debug, S, A: Allocator + Clone> fmt::Display
for OccupiedError<'a, K, V, S, A>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"failed to insert {:?}, key {:?} already exists with value {:?}",
self.value,
self.entry.key(),
self.entry.get(),
)
}
}
impl<'a, K, V, S, A: Allocator + Clone> IntoIterator for &'a HashMap<K, V, S, A> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
impl<'a, K, V, S, A: Allocator + Clone> IntoIterator for &'a mut HashMap<K, V, S, A> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> IterMut<'a, K, V> {
self.iter_mut()
}
}
impl<K, V, S, A: Allocator + Clone> IntoIterator for HashMap<K, V, S, A> {
type Item = (K, V);
type IntoIter = IntoIter<K, V, A>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> IntoIter<K, V, A> {
IntoIter {
inner: self.table.into_iter(),
}
}
}
impl<'a, K, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(&'a K, &'a V)> {
match self.inner.next() {
Some(x) => unsafe {
let r = x.as_ref();
Some((&r.0, &r.1))
},
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for Iter<'_, K, V> {}
impl<'a, K, V> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
match self.inner.next() {
Some(x) => unsafe {
let r = x.as_mut();
Some((&r.0, &mut r.1))
},
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for IterMut<'_, K, V> {}
impl<K, V> fmt::Debug for IterMut<'_, K, V>
where
K: fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
type Item = (K, V);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(K, V)> {
self.inner.next()
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
impl<K: Debug, V: Debug, A: Allocator + Clone> fmt::Debug for IntoIter<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<'a, K, V> Iterator for Keys<'a, K, V> {
type Item = &'a K;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a K> {
match self.inner.next() {
Some((k, _)) => Some(k),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for Keys<'_, K, V> {}
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a V> {
match self.inner.next() {
Some((_, v)) => Some(v),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V> ExactSizeIterator for Values<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for Values<'_, K, V> {}
impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
type Item = &'a mut V;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<&'a mut V> {
match self.inner.next() {
Some((_, v)) => Some(v),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.inner.iter().map(|(_, val)| val))
.finish()
}
}
impl<'a, K, V, A: Allocator + Clone> Iterator for Drain<'a, K, V, A> {
type Item = (K, V);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(K, V)> {
self.inner.next()
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V, A: Allocator + Clone> ExactSizeIterator for Drain<'_, K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V, A: Allocator + Clone> FusedIterator for Drain<'_, K, V, A> {}
impl<K, V, A> fmt::Debug for Drain<'_, K, V, A>
where
K: fmt::Debug,
V: fmt::Debug,
A: Allocator + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<'a, K, V, S, A: Allocator + Clone> Entry<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(mut entry) => {
entry.insert(value);
entry
}
Entry::Vacant(entry) => entry.insert_entry(value),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert(self, default: V) -> &'a mut V
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let value = default(entry.key());
entry.insert(value)
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &K {
match *self {
Entry::Occupied(ref entry) => entry.key(),
Entry::Vacant(ref entry) => entry.key(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
Entry::Occupied(mut entry) => {
f(entry.get_mut());
Entry::Occupied(entry)
}
Entry::Vacant(entry) => Entry::Vacant(entry),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_replace_entry_with<F>(self, f: F) -> Self
where
F: FnOnce(&K, V) -> Option<V>,
{
match self {
Entry::Occupied(entry) => entry.replace_entry_with(f),
Entry::Vacant(_) => self,
}
}
}
impl<'a, K, V: Default, S, A: Allocator + Clone> Entry<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_default(self) -> &'a mut V
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(Default::default()),
}
}
}
impl<'a, K, V, S, A: Allocator + Clone> OccupiedEntry<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &K {
unsafe { &self.elem.as_ref().0 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry(self) -> (K, V) {
unsafe { self.table.table.remove(self.elem) }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> &V {
unsafe { &self.elem.as_ref().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut(&mut self) -> &mut V {
unsafe { &mut self.elem.as_mut().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_mut(self) -> &'a mut V {
unsafe { &mut self.elem.as_mut().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&mut self, value: V) -> V {
mem::replace(self.get_mut(), value)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove(self) -> V {
self.remove_entry().1
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry(self, value: V) -> (K, V) {
let entry = unsafe { self.elem.as_mut() };
let old_key = mem::replace(&mut entry.0, self.key.unwrap());
let old_value = mem::replace(&mut entry.1, value);
(old_key, old_value)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_key(self) -> K {
let entry = unsafe { self.elem.as_mut() };
mem::replace(&mut entry.0, self.key.unwrap())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A>
where
F: FnOnce(&K, V) -> Option<V>,
{
unsafe {
let mut spare_key = None;
self.table
.table
.replace_bucket_with(self.elem.clone(), |(key, value)| {
if let Some(new_value) = f(&key, value) {
Some((key, new_value))
} else {
spare_key = Some(key);
None
}
});
if let Some(key) = spare_key {
Entry::Vacant(VacantEntry {
hash: self.hash,
key,
table: self.table,
})
} else {
Entry::Occupied(self)
}
}
}
}
impl<'a, K, V, S, A: Allocator + Clone> VacantEntry<'a, K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &K {
&self.key
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_key(self) -> K {
self.key
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self, value: V) -> &'a mut V
where
K: Hash,
S: BuildHasher,
{
let table = &mut self.table.table;
let entry = table.insert_entry(
self.hash,
(self.key, value),
make_hasher::<_, V, S>(&self.table.hash_builder),
);
&mut entry.1
}
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
where
K: Hash,
S: BuildHasher,
{
let elem = self.table.table.insert(
self.hash,
(self.key, value),
make_hasher::<_, V, S>(&self.table.hash_builder),
);
OccupiedEntry {
hash: self.hash,
key: None,
elem,
table: self.table,
}
}
}
impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone> EntryRef<'a, 'b, K, Q, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(mut entry) => {
entry.insert(value);
entry
}
EntryRef::Vacant(entry) => entry.insert_entry(value),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert(self, default: V) -> &'a mut V
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => entry.insert(default),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => entry.insert(default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> &'a mut V
where
K: Hash + Borrow<Q> + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => {
let value = default(entry.key.as_ref());
entry.insert(value)
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &Q
where
K: Borrow<Q>,
{
match *self {
EntryRef::Occupied(ref entry) => entry.key(),
EntryRef::Vacant(ref entry) => entry.key(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
EntryRef::Occupied(mut entry) => {
f(entry.get_mut());
EntryRef::Occupied(entry)
}
EntryRef::Vacant(entry) => EntryRef::Vacant(entry),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_replace_entry_with<F>(self, f: F) -> Self
where
F: FnOnce(&Q, V) -> Option<V>,
K: Borrow<Q>,
{
match self {
EntryRef::Occupied(entry) => entry.replace_entry_with(f),
EntryRef::Vacant(_) => self,
}
}
}
impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator + Clone> EntryRef<'a, 'b, K, Q, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_default(self) -> &'a mut V
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => entry.insert(Default::default()),
}
}
}
impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone> OccupiedEntryRef<'a, 'b, K, Q, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &Q
where
K: Borrow<Q>,
{
unsafe { &self.elem.as_ref().0 }.borrow()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry(self) -> (K, V) {
unsafe { self.table.table.remove(self.elem) }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> &V {
unsafe { &self.elem.as_ref().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut(&mut self) -> &mut V {
unsafe { &mut self.elem.as_mut().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_mut(self) -> &'a mut V {
unsafe { &mut self.elem.as_mut().1 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&mut self, value: V) -> V {
mem::replace(self.get_mut(), value)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove(self) -> V {
self.remove_entry().1
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry(self, value: V) -> (K, V)
where
K: From<&'b Q>,
{
let entry = unsafe { self.elem.as_mut() };
let old_key = mem::replace(&mut entry.0, self.key.unwrap().into_owned());
let old_value = mem::replace(&mut entry.1, value);
(old_key, old_value)
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_key(self) -> K
where
K: From<&'b Q>,
{
let entry = unsafe { self.elem.as_mut() };
mem::replace(&mut entry.0, self.key.unwrap().into_owned())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry_with<F>(self, f: F) -> EntryRef<'a, 'b, K, Q, V, S, A>
where
F: FnOnce(&Q, V) -> Option<V>,
K: Borrow<Q>,
{
unsafe {
let mut spare_key = None;
self.table
.table
.replace_bucket_with(self.elem.clone(), |(key, value)| {
if let Some(new_value) = f(key.borrow(), value) {
Some((key, new_value))
} else {
spare_key = Some(KeyOrRef::Owned(key));
None
}
});
if let Some(key) = spare_key {
EntryRef::Vacant(VacantEntryRef {
hash: self.hash,
key,
table: self.table,
})
} else {
EntryRef::Occupied(self)
}
}
}
}
impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone> VacantEntryRef<'a, 'b, K, Q, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &Q
where
K: Borrow<Q>,
{
self.key.as_ref()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_key(self) -> K
where
K: From<&'b Q>,
{
self.key.into_owned()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self, value: V) -> &'a mut V
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
let table = &mut self.table.table;
let entry = table.insert_entry(
self.hash,
(self.key.into_owned(), value),
make_hasher::<_, V, S>(&self.table.hash_builder),
);
&mut entry.1
}
#[cfg_attr(feature = "inline-more", inline)]
fn insert_entry(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
let elem = self.table.table.insert(
self.hash,
(self.key.into_owned(), value),
make_hasher::<_, V, S>(&self.table.hash_builder),
);
OccupiedEntryRef {
hash: self.hash,
key: None,
elem,
table: self.table,
}
}
}
impl<K, V, S, A> FromIterator<(K, V)> for HashMap<K, V, S, A>
where
K: Eq + Hash,
S: BuildHasher + Default,
A: Default + Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let iter = iter.into_iter();
let mut map =
Self::with_capacity_and_hasher_in(iter.size_hint().0, S::default(), A::default());
iter.for_each(|(k, v)| {
map.insert(k, v);
});
map
}
}
impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
where
K: Eq + Hash,
S: BuildHasher,
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
let iter = iter.into_iter();
let reserve = if self.is_empty() {
iter.size_hint().0
} else {
(iter.size_hint().0 + 1) / 2
};
self.reserve(reserve);
iter.for_each(move |(k, v)| {
self.insert(k, v);
});
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_one(&mut self, (k, v): (K, V)) {
self.insert(k, v);
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_reserve(&mut self, additional: usize) {
let reserve = if self.is_empty() {
additional
} else {
(additional + 1) / 2
};
self.reserve(reserve);
}
}
impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
where
K: Eq + Hash + Copy,
V: Copy,
S: BuildHasher,
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_one(&mut self, (k, v): (&'a K, &'a V)) {
self.insert(*k, *v);
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_reserve(&mut self, additional: usize) {
Extend::<(K, V)>::extend_reserve(self, additional);
}
}
impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap<K, V, S, A>
where
K: Eq + Hash + Copy,
V: Copy,
S: BuildHasher,
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(|&(key, value)| (key, value)));
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_one(&mut self, &(k, v): &'a (K, V)) {
self.insert(k, v);
}
#[inline]
#[cfg(feature = "nightly")]
fn extend_reserve(&mut self, additional: usize) {
Extend::<(K, V)>::extend_reserve(self, additional);
}
}
#[allow(dead_code)]
fn assert_covariance() {
fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
v
}
fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
v
}
fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
v
}
fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
v
}
fn into_iter_key<'new, A: Allocator + Clone>(
v: IntoIter<&'static str, u8, A>,
) -> IntoIter<&'new str, u8, A> {
v
}
fn into_iter_val<'new, A: Allocator + Clone>(
v: IntoIter<u8, &'static str, A>,
) -> IntoIter<u8, &'new str, A> {
v
}
fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
v
}
fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
v
}
fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
v
}
fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
v
}
fn drain<'new>(
d: Drain<'static, &'static str, &'static str>,
) -> Drain<'new, &'new str, &'new str> {
d
}
}
#[cfg(test)]
mod test_map {
use super::DefaultHashBuilder;
use super::Entry::{Occupied, Vacant};
use super::EntryRef;
use super::{HashMap, RawEntryMut};
use rand::{rngs::SmallRng, Rng, SeedableRng};
use std::borrow::ToOwned;
use std::cell::RefCell;
use std::usize;
use std::vec::Vec;
#[test]
fn test_zero_capacities() {
type HM = HashMap<i32, i32>;
let m = HM::new();
assert_eq!(m.capacity(), 0);
let m = HM::default();
assert_eq!(m.capacity(), 0);
let m = HM::with_hasher(DefaultHashBuilder::default());
assert_eq!(m.capacity(), 0);
let m = HM::with_capacity(0);
assert_eq!(m.capacity(), 0);
let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default());
assert_eq!(m.capacity(), 0);
let mut m = HM::new();
m.insert(1, 1);
m.insert(2, 2);
m.remove(&1);
m.remove(&2);
m.shrink_to_fit();
assert_eq!(m.capacity(), 0);
let mut m = HM::new();
m.reserve(0);
assert_eq!(m.capacity(), 0);
}
#[test]
fn test_create_capacity_zero() {
let mut m = HashMap::with_capacity(0);
assert!(m.insert(1, 1).is_none());
assert!(m.contains_key(&1));
assert!(!m.contains_key(&0));
}
#[test]
fn test_insert() {
let mut m = HashMap::new();
assert_eq!(m.len(), 0);
assert!(m.insert(1, 2).is_none());
assert_eq!(m.len(), 1);
assert!(m.insert(2, 4).is_none());
assert_eq!(m.len(), 2);
assert_eq!(*m.get(&1).unwrap(), 2);
assert_eq!(*m.get(&2).unwrap(), 4);
}
#[test]
fn test_clone() {
let mut m = HashMap::new();
assert_eq!(m.len(), 0);
assert!(m.insert(1, 2).is_none());
assert_eq!(m.len(), 1);
assert!(m.insert(2, 4).is_none());
assert_eq!(m.len(), 2);
#[allow(clippy::redundant_clone)]
let m2 = m.clone();
assert_eq!(*m2.get(&1).unwrap(), 2);
assert_eq!(*m2.get(&2).unwrap(), 4);
assert_eq!(m2.len(), 2);
}
#[test]
fn test_clone_from() {
let mut m = HashMap::new();
let mut m2 = HashMap::new();
assert_eq!(m.len(), 0);
assert!(m.insert(1, 2).is_none());
assert_eq!(m.len(), 1);
assert!(m.insert(2, 4).is_none());
assert_eq!(m.len(), 2);
m2.clone_from(&m);
assert_eq!(*m2.get(&1).unwrap(), 2);
assert_eq!(*m2.get(&2).unwrap(), 4);
assert_eq!(m2.len(), 2);
}
thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
#[derive(Hash, PartialEq, Eq)]
struct Droppable {
k: usize,
}
impl Droppable {
fn new(k: usize) -> Droppable {
DROP_VECTOR.with(|slot| {
slot.borrow_mut()[k] += 1;
});
Droppable { k }
}
}
impl Drop for Droppable {
fn drop(&mut self) {
DROP_VECTOR.with(|slot| {
slot.borrow_mut()[self.k] -= 1;
});
}
}
impl Clone for Droppable {
fn clone(&self) -> Self {
Droppable::new(self.k)
}
}
#[test]
fn test_drops() {
DROP_VECTOR.with(|slot| {
*slot.borrow_mut() = vec![0; 200];
});
{
let mut m = HashMap::new();
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 0);
}
});
for i in 0..100 {
let d1 = Droppable::new(i);
let d2 = Droppable::new(i + 100);
m.insert(d1, d2);
}
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 1);
}
});
for i in 0..50 {
let k = Droppable::new(i);
let v = m.remove(&k);
assert!(v.is_some());
DROP_VECTOR.with(|v| {
assert_eq!(v.borrow()[i], 1);
assert_eq!(v.borrow()[i + 100], 1);
});
}
DROP_VECTOR.with(|v| {
for i in 0..50 {
assert_eq!(v.borrow()[i], 0);
assert_eq!(v.borrow()[i + 100], 0);
}
for i in 50..100 {
assert_eq!(v.borrow()[i], 1);
assert_eq!(v.borrow()[i + 100], 1);
}
});
}
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 0);
}
});
}
#[test]
fn test_into_iter_drops() {
DROP_VECTOR.with(|v| {
*v.borrow_mut() = vec![0; 200];
});
let hm = {
let mut hm = HashMap::new();
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 0);
}
});
for i in 0..100 {
let d1 = Droppable::new(i);
let d2 = Droppable::new(i + 100);
hm.insert(d1, d2);
}
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 1);
}
});
hm
};
drop(hm.clone());
{
let mut half = hm.into_iter().take(50);
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 1);
}
});
#[allow(clippy::let_underscore_drop)] for _ in half.by_ref() {}
DROP_VECTOR.with(|v| {
let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
assert_eq!(nk, 50);
assert_eq!(nv, 50);
});
};
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 0);
}
});
}
#[test]
fn test_empty_remove() {
let mut m: HashMap<i32, bool> = HashMap::new();
assert_eq!(m.remove(&0), None);
}
#[test]
fn test_empty_entry() {
let mut m: HashMap<i32, bool> = HashMap::new();
match m.entry(0) {
Occupied(_) => panic!(),
Vacant(_) => {}
}
assert!(*m.entry(0).or_insert(true));
assert_eq!(m.len(), 1);
}
#[test]
fn test_empty_entry_ref() {
let mut m: HashMap<std::string::String, bool> = HashMap::new();
match m.entry_ref("poneyland") {
EntryRef::Occupied(_) => panic!(),
EntryRef::Vacant(_) => {}
}
assert!(*m.entry_ref("poneyland").or_insert(true));
assert_eq!(m.len(), 1);
}
#[test]
fn test_empty_iter() {
let mut m: HashMap<i32, bool> = HashMap::new();
assert_eq!(m.drain().next(), None);
assert_eq!(m.keys().next(), None);
assert_eq!(m.values().next(), None);
assert_eq!(m.values_mut().next(), None);
assert_eq!(m.iter().next(), None);
assert_eq!(m.iter_mut().next(), None);
assert_eq!(m.len(), 0);
assert!(m.is_empty());
assert_eq!(m.into_iter().next(), None);
}
#[test]
#[cfg_attr(miri, ignore)] fn test_lots_of_insertions() {
let mut m = HashMap::new();
for _ in 0..10 {
assert!(m.is_empty());
for i in 1..1001 {
assert!(m.insert(i, i).is_none());
for j in 1..=i {
let r = m.get(&j);
assert_eq!(r, Some(&j));
}
for j in i + 1..1001 {
let r = m.get(&j);
assert_eq!(r, None);
}
}
for i in 1001..2001 {
assert!(!m.contains_key(&i));
}
for i in 1..1001 {
assert!(m.remove(&i).is_some());
for j in 1..=i {
assert!(!m.contains_key(&j));
}
for j in i + 1..1001 {
assert!(m.contains_key(&j));
}
}
for i in 1..1001 {
assert!(!m.contains_key(&i));
}
for i in 1..1001 {
assert!(m.insert(i, i).is_none());
}
for i in (1..1001).rev() {
assert!(m.remove(&i).is_some());
for j in i..1001 {
assert!(!m.contains_key(&j));
}
for j in 1..i {
assert!(m.contains_key(&j));
}
}
}
}
#[test]
fn test_find_mut() {
let mut m = HashMap::new();
assert!(m.insert(1, 12).is_none());
assert!(m.insert(2, 8).is_none());
assert!(m.insert(5, 14).is_none());
let new = 100;
match m.get_mut(&5) {
None => panic!(),
Some(x) => *x = new,
}
assert_eq!(m.get(&5), Some(&new));
}
#[test]
fn test_insert_overwrite() {
let mut m = HashMap::new();
assert!(m.insert(1, 2).is_none());
assert_eq!(*m.get(&1).unwrap(), 2);
assert!(m.insert(1, 3).is_some());
assert_eq!(*m.get(&1).unwrap(), 3);
}
#[test]
fn test_insert_conflicts() {
let mut m = HashMap::with_capacity(4);
assert!(m.insert(1, 2).is_none());
assert!(m.insert(5, 3).is_none());
assert!(m.insert(9, 4).is_none());
assert_eq!(*m.get(&9).unwrap(), 4);
assert_eq!(*m.get(&5).unwrap(), 3);
assert_eq!(*m.get(&1).unwrap(), 2);
}
#[test]
fn test_conflict_remove() {
let mut m = HashMap::with_capacity(4);
assert!(m.insert(1, 2).is_none());
assert_eq!(*m.get(&1).unwrap(), 2);
assert!(m.insert(5, 3).is_none());
assert_eq!(*m.get(&1).unwrap(), 2);
assert_eq!(*m.get(&5).unwrap(), 3);
assert!(m.insert(9, 4).is_none());
assert_eq!(*m.get(&1).unwrap(), 2);
assert_eq!(*m.get(&5).unwrap(), 3);
assert_eq!(*m.get(&9).unwrap(), 4);
assert!(m.remove(&1).is_some());
assert_eq!(*m.get(&9).unwrap(), 4);
assert_eq!(*m.get(&5).unwrap(), 3);
}
#[test]
fn test_insert_unique_unchecked() {
let mut map = HashMap::new();
let (k1, v1) = map.insert_unique_unchecked(10, 11);
assert_eq!((&10, &mut 11), (k1, v1));
let (k2, v2) = map.insert_unique_unchecked(20, 21);
assert_eq!((&20, &mut 21), (k2, v2));
assert_eq!(Some(&11), map.get(&10));
assert_eq!(Some(&21), map.get(&20));
assert_eq!(None, map.get(&30));
}
#[test]
fn test_is_empty() {
let mut m = HashMap::with_capacity(4);
assert!(m.insert(1, 2).is_none());
assert!(!m.is_empty());
assert!(m.remove(&1).is_some());
assert!(m.is_empty());
}
#[test]
fn test_remove() {
let mut m = HashMap::new();
m.insert(1, 2);
assert_eq!(m.remove(&1), Some(2));
assert_eq!(m.remove(&1), None);
}
#[test]
fn test_remove_entry() {
let mut m = HashMap::new();
m.insert(1, 2);
assert_eq!(m.remove_entry(&1), Some((1, 2)));
assert_eq!(m.remove(&1), None);
}
#[test]
fn test_iterate() {
let mut m = HashMap::with_capacity(4);
for i in 0..32 {
assert!(m.insert(i, i * 2).is_none());
}
assert_eq!(m.len(), 32);
let mut observed: u32 = 0;
for (k, v) in &m {
assert_eq!(*v, *k * 2);
observed |= 1 << *k;
}
assert_eq!(observed, 0xFFFF_FFFF);
}
#[test]
fn test_keys() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: HashMap<_, _> = vec.into_iter().collect();
let keys: Vec<_> = map.keys().copied().collect();
assert_eq!(keys.len(), 3);
assert!(keys.contains(&1));
assert!(keys.contains(&2));
assert!(keys.contains(&3));
}
#[test]
fn test_values() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: HashMap<_, _> = vec.into_iter().collect();
let values: Vec<_> = map.values().copied().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&'a'));
assert!(values.contains(&'b'));
assert!(values.contains(&'c'));
}
#[test]
fn test_values_mut() {
let vec = vec![(1, 1), (2, 2), (3, 3)];
let mut map: HashMap<_, _> = vec.into_iter().collect();
for value in map.values_mut() {
*value *= 2;
}
let values: Vec<_> = map.values().copied().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&2));
assert!(values.contains(&4));
assert!(values.contains(&6));
}
#[test]
fn test_into_keys() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: HashMap<_, _> = vec.into_iter().collect();
let keys: Vec<_> = map.into_keys().collect();
assert_eq!(keys.len(), 3);
assert!(keys.contains(&1));
assert!(keys.contains(&2));
assert!(keys.contains(&3));
}
#[test]
fn test_into_values() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: HashMap<_, _> = vec.into_iter().collect();
let values: Vec<_> = map.into_values().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&'a'));
assert!(values.contains(&'b'));
assert!(values.contains(&'c'));
}
#[test]
fn test_find() {
let mut m = HashMap::new();
assert!(m.get(&1).is_none());
m.insert(1, 2);
match m.get(&1) {
None => panic!(),
Some(v) => assert_eq!(*v, 2),
}
}
#[test]
fn test_eq() {
let mut m1 = HashMap::new();
m1.insert(1, 2);
m1.insert(2, 3);
m1.insert(3, 4);
let mut m2 = HashMap::new();
m2.insert(1, 2);
m2.insert(2, 3);
assert!(m1 != m2);
m2.insert(3, 4);
assert_eq!(m1, m2);
}
#[test]
fn test_show() {
let mut map = HashMap::new();
let empty: HashMap<i32, i32> = HashMap::new();
map.insert(1, 2);
map.insert(3, 4);
let map_str = format!("{:?}", map);
assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
assert_eq!(format!("{:?}", empty), "{}");
}
#[test]
fn test_expand() {
let mut m = HashMap::new();
assert_eq!(m.len(), 0);
assert!(m.is_empty());
let mut i = 0;
let old_raw_cap = m.raw_capacity();
while old_raw_cap == m.raw_capacity() {
m.insert(i, i);
i += 1;
}
assert_eq!(m.len(), i);
assert!(!m.is_empty());
}
#[test]
fn test_behavior_resize_policy() {
let mut m = HashMap::new();
assert_eq!(m.len(), 0);
assert_eq!(m.raw_capacity(), 1);
assert!(m.is_empty());
m.insert(0, 0);
m.remove(&0);
assert!(m.is_empty());
let initial_raw_cap = m.raw_capacity();
m.reserve(initial_raw_cap);
let raw_cap = m.raw_capacity();
assert_eq!(raw_cap, initial_raw_cap * 2);
let mut i = 0;
for _ in 0..raw_cap * 3 / 4 {
m.insert(i, i);
i += 1;
}
assert_eq!(m.len(), i);
assert_eq!(m.raw_capacity(), raw_cap);
for _ in 0..raw_cap / 4 {
m.insert(i, i);
i += 1;
}
let new_raw_cap = m.raw_capacity();
assert_eq!(new_raw_cap, raw_cap * 2);
for _ in 0..raw_cap / 2 - 1 {
i -= 1;
m.remove(&i);
assert_eq!(m.raw_capacity(), new_raw_cap);
}
m.shrink_to_fit();
assert_eq!(m.raw_capacity(), raw_cap);
for _ in 0..raw_cap / 2 {
i -= 1;
m.remove(&i);
}
m.shrink_to_fit();
assert_eq!(m.len(), i);
assert!(!m.is_empty());
assert_eq!(m.raw_capacity(), initial_raw_cap);
}
#[test]
fn test_reserve_shrink_to_fit() {
let mut m = HashMap::new();
m.insert(0, 0);
m.remove(&0);
assert!(m.capacity() >= m.len());
for i in 0..128 {
m.insert(i, i);
}
m.reserve(256);
let usable_cap = m.capacity();
for i in 128..(128 + 256) {
m.insert(i, i);
assert_eq!(m.capacity(), usable_cap);
}
for i in 100..(128 + 256) {
assert_eq!(m.remove(&i), Some(i));
}
m.shrink_to_fit();
assert_eq!(m.len(), 100);
assert!(!m.is_empty());
assert!(m.capacity() >= m.len());
for i in 0..100 {
assert_eq!(m.remove(&i), Some(i));
}
m.shrink_to_fit();
m.insert(0, 0);
assert_eq!(m.len(), 1);
assert!(m.capacity() >= m.len());
assert_eq!(m.remove(&0), Some(0));
}
#[test]
fn test_from_iter() {
let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: HashMap<_, _> = xs.iter().copied().collect();
for &(k, v) in &xs {
assert_eq!(map.get(&k), Some(&v));
}
assert_eq!(map.iter().len(), xs.len() - 1);
}
#[test]
fn test_size_hint() {
let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: HashMap<_, _> = xs.iter().copied().collect();
let mut iter = map.iter();
for _ in iter.by_ref().take(3) {}
assert_eq!(iter.size_hint(), (3, Some(3)));
}
#[test]
fn test_iter_len() {
let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: HashMap<_, _> = xs.iter().copied().collect();
let mut iter = map.iter();
for _ in iter.by_ref().take(3) {}
assert_eq!(iter.len(), 3);
}
#[test]
fn test_mut_size_hint() {
let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let mut map: HashMap<_, _> = xs.iter().copied().collect();
let mut iter = map.iter_mut();
for _ in iter.by_ref().take(3) {}
assert_eq!(iter.size_hint(), (3, Some(3)));
}
#[test]
fn test_iter_mut_len() {
let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let mut map: HashMap<_, _> = xs.iter().copied().collect();
let mut iter = map.iter_mut();
for _ in iter.by_ref().take(3) {}
assert_eq!(iter.len(), 3);
}
#[test]
fn test_index() {
let mut map = HashMap::new();
map.insert(1, 2);
map.insert(2, 1);
map.insert(3, 4);
assert_eq!(map[&2], 1);
}
#[test]
#[should_panic]
fn test_index_nonexistent() {
let mut map = HashMap::new();
map.insert(1, 2);
map.insert(2, 1);
map.insert(3, 4);
#[allow(clippy::no_effect)] map[&4];
}
#[test]
fn test_entry() {
let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
let mut map: HashMap<_, _> = xs.iter().copied().collect();
match map.entry(1) {
Vacant(_) => unreachable!(),
Occupied(mut view) => {
assert_eq!(view.get(), &10);
assert_eq!(view.insert(100), 10);
}
}
assert_eq!(map.get(&1).unwrap(), &100);
assert_eq!(map.len(), 6);
match map.entry(2) {
Vacant(_) => unreachable!(),
Occupied(mut view) => {
let v = view.get_mut();
let new_v = (*v) * 10;
*v = new_v;
}
}
assert_eq!(map.get(&2).unwrap(), &200);
assert_eq!(map.len(), 6);
match map.entry(3) {
Vacant(_) => unreachable!(),
Occupied(view) => {
assert_eq!(view.remove(), 30);
}
}
assert_eq!(map.get(&3), None);
assert_eq!(map.len(), 5);
match map.entry(10) {
Occupied(_) => unreachable!(),
Vacant(view) => {
assert_eq!(*view.insert(1000), 1000);
}
}
assert_eq!(map.get(&10).unwrap(), &1000);
assert_eq!(map.len(), 6);
}
#[test]
fn test_entry_ref() {
let xs = [
("One".to_owned(), 10),
("Two".to_owned(), 20),
("Three".to_owned(), 30),
("Four".to_owned(), 40),
("Five".to_owned(), 50),
("Six".to_owned(), 60),
];
let mut map: HashMap<_, _> = xs.iter().cloned().collect();
match map.entry_ref("One") {
EntryRef::Vacant(_) => unreachable!(),
EntryRef::Occupied(mut view) => {
assert_eq!(view.get(), &10);
assert_eq!(view.insert(100), 10);
}
}
assert_eq!(map.get("One").unwrap(), &100);
assert_eq!(map.len(), 6);
match map.entry_ref("Two") {
EntryRef::Vacant(_) => unreachable!(),
EntryRef::Occupied(mut view) => {
let v = view.get_mut();
let new_v = (*v) * 10;
*v = new_v;
}
}
assert_eq!(map.get("Two").unwrap(), &200);
assert_eq!(map.len(), 6);
match map.entry_ref("Three") {
EntryRef::Vacant(_) => unreachable!(),
EntryRef::Occupied(view) => {
assert_eq!(view.remove(), 30);
}
}
assert_eq!(map.get("Three"), None);
assert_eq!(map.len(), 5);
match map.entry_ref("Ten") {
EntryRef::Occupied(_) => unreachable!(),
EntryRef::Vacant(view) => {
assert_eq!(*view.insert(1000), 1000);
}
}
assert_eq!(map.get("Ten").unwrap(), &1000);
assert_eq!(map.len(), 6);
}
#[test]
fn test_entry_take_doesnt_corrupt() {
#![allow(deprecated)] fn check(m: &HashMap<i32, ()>) {
for k in m.keys() {
assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
}
}
let mut m = HashMap::new();
let mut rng = {
let seed = u64::from_le_bytes(*b"testseed");
SmallRng::seed_from_u64(seed)
};
for _ in 0..50 {
let x = rng.gen_range(-10..10);
m.insert(x, ());
}
for _ in 0..1000 {
let x = rng.gen_range(-10..10);
match m.entry(x) {
Vacant(_) => {}
Occupied(e) => {
e.remove();
}
}
check(&m);
}
}
#[test]
fn test_entry_ref_take_doesnt_corrupt() {
#![allow(deprecated)] fn check(m: &HashMap<std::string::String, ()>) {
for k in m.keys() {
assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
}
}
let mut m = HashMap::new();
let mut rng = {
let seed = u64::from_le_bytes(*b"testseed");
SmallRng::seed_from_u64(seed)
};
for _ in 0..50 {
let mut x = std::string::String::with_capacity(1);
x.push(rng.gen_range('a'..='z'));
m.insert(x, ());
}
for _ in 0..1000 {
let mut x = std::string::String::with_capacity(1);
x.push(rng.gen_range('a'..='z'));
match m.entry_ref(x.as_str()) {
EntryRef::Vacant(_) => {}
EntryRef::Occupied(e) => {
e.remove();
}
}
check(&m);
}
}
#[test]
fn test_extend_ref_k_ref_v() {
let mut a = HashMap::new();
a.insert(1, "one");
let mut b = HashMap::new();
b.insert(2, "two");
b.insert(3, "three");
a.extend(&b);
assert_eq!(a.len(), 3);
assert_eq!(a[&1], "one");
assert_eq!(a[&2], "two");
assert_eq!(a[&3], "three");
}
#[test]
fn test_extend_ref_kv_tuple() {
use std::ops::AddAssign;
let mut a = HashMap::new();
a.insert(0, 0);
fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] {
let mut outs: [(T, T); N] = [(start, start); N];
let mut element = step;
outs.iter_mut().skip(1).for_each(|(k, v)| {
*k += element;
*v += element;
element += step;
});
outs
}
let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect();
let iter = for_iter.iter();
let vec: Vec<_> = (100..200).map(|i| (i, i)).collect();
a.extend(iter);
a.extend(&vec);
a.extend(create_arr::<i32, 100>(200, 1));
assert_eq!(a.len(), 300);
for item in 0..300 {
assert_eq!(a[&item], item);
}
}
#[test]
fn test_capacity_not_less_than_len() {
let mut a = HashMap::new();
let mut item = 0;
for _ in 0..116 {
a.insert(item, 0);
item += 1;
}
assert!(a.capacity() > a.len());
let free = a.capacity() - a.len();
for _ in 0..free {
a.insert(item, 0);
item += 1;
}
assert_eq!(a.len(), a.capacity());
a.insert(item, 0);
assert!(a.capacity() > a.len());
}
#[test]
fn test_occupied_entry_key() {
let mut a = HashMap::new();
let key = "hello there";
let value = "value goes here";
assert!(a.is_empty());
a.insert(key, value);
assert_eq!(a.len(), 1);
assert_eq!(a[key], value);
match a.entry(key) {
Vacant(_) => panic!(),
Occupied(e) => assert_eq!(key, *e.key()),
}
assert_eq!(a.len(), 1);
assert_eq!(a[key], value);
}
#[test]
fn test_occupied_entry_ref_key() {
let mut a = HashMap::new();
let key = "hello there";
let value = "value goes here";
assert!(a.is_empty());
a.insert(key.to_owned(), value);
assert_eq!(a.len(), 1);
assert_eq!(a[key], value);
match a.entry_ref(key) {
EntryRef::Vacant(_) => panic!(),
EntryRef::Occupied(e) => assert_eq!(key, e.key()),
}
assert_eq!(a.len(), 1);
assert_eq!(a[key], value);
}
#[test]
fn test_vacant_entry_key() {
let mut a = HashMap::new();
let key = "hello there";
let value = "value goes here";
assert!(a.is_empty());
match a.entry(key) {
Occupied(_) => panic!(),
Vacant(e) => {
assert_eq!(key, *e.key());
e.insert(value);
}
}
assert_eq!(a.len(), 1);
assert_eq!(a[key], value);
}
#[test]
fn test_vacant_entry_ref_key() {
let mut a: HashMap<std::string::String, &str> = HashMap::new();
let key = "hello there";
let value = "value goes here";
assert!(a.is_empty());
match a.entry_ref(key) {
EntryRef::Occupied(_) => panic!(),
EntryRef::Vacant(e) => {
assert_eq!(key, e.key());
e.insert(value);
}
}
assert_eq!(a.len(), 1);
assert_eq!(a[key], value);
}
#[test]
fn test_occupied_entry_replace_entry_with() {
let mut a = HashMap::new();
let key = "a key";
let value = "an initial value";
let new_value = "a new value";
let entry = a.entry(key).insert(value).replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, value);
Some(new_value)
});
match entry {
Occupied(e) => {
assert_eq!(e.key(), &key);
assert_eq!(e.get(), &new_value);
}
Vacant(_) => panic!(),
}
assert_eq!(a[key], new_value);
assert_eq!(a.len(), 1);
let entry = match a.entry(key) {
Occupied(e) => e.replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, new_value);
None
}),
Vacant(_) => panic!(),
};
match entry {
Vacant(e) => assert_eq!(e.key(), &key),
Occupied(_) => panic!(),
}
assert!(!a.contains_key(key));
assert_eq!(a.len(), 0);
}
#[test]
fn test_occupied_entry_ref_replace_entry_with() {
let mut a: HashMap<std::string::String, &str> = HashMap::new();
let key = "a key";
let value = "an initial value";
let new_value = "a new value";
let entry = a.entry_ref(key).insert(value).replace_entry_with(|k, v| {
assert_eq!(k, key);
assert_eq!(v, value);
Some(new_value)
});
match entry {
EntryRef::Occupied(e) => {
assert_eq!(e.key(), key);
assert_eq!(e.get(), &new_value);
}
EntryRef::Vacant(_) => panic!(),
}
assert_eq!(a[key], new_value);
assert_eq!(a.len(), 1);
let entry = match a.entry_ref(key) {
EntryRef::Occupied(e) => e.replace_entry_with(|k, v| {
assert_eq!(k, key);
assert_eq!(v, new_value);
None
}),
EntryRef::Vacant(_) => panic!(),
};
match entry {
EntryRef::Vacant(e) => assert_eq!(e.key(), key),
EntryRef::Occupied(_) => panic!(),
}
assert!(!a.contains_key(key));
assert_eq!(a.len(), 0);
}
#[test]
fn test_entry_and_replace_entry_with() {
let mut a = HashMap::new();
let key = "a key";
let value = "an initial value";
let new_value = "a new value";
let entry = a.entry(key).and_replace_entry_with(|_, _| panic!());
match entry {
Vacant(e) => assert_eq!(e.key(), &key),
Occupied(_) => panic!(),
}
a.insert(key, value);
let entry = a.entry(key).and_replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, value);
Some(new_value)
});
match entry {
Occupied(e) => {
assert_eq!(e.key(), &key);
assert_eq!(e.get(), &new_value);
}
Vacant(_) => panic!(),
}
assert_eq!(a[key], new_value);
assert_eq!(a.len(), 1);
let entry = a.entry(key).and_replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, new_value);
None
});
match entry {
Vacant(e) => assert_eq!(e.key(), &key),
Occupied(_) => panic!(),
}
assert!(!a.contains_key(key));
assert_eq!(a.len(), 0);
}
#[test]
fn test_entry_ref_and_replace_entry_with() {
let mut a = HashMap::new();
let key = "a key";
let value = "an initial value";
let new_value = "a new value";
let entry = a.entry_ref(key).and_replace_entry_with(|_, _| panic!());
match entry {
EntryRef::Vacant(e) => assert_eq!(e.key(), key),
EntryRef::Occupied(_) => panic!(),
}
a.insert(key.to_owned(), value);
let entry = a.entry_ref(key).and_replace_entry_with(|k, v| {
assert_eq!(k, key);
assert_eq!(v, value);
Some(new_value)
});
match entry {
EntryRef::Occupied(e) => {
assert_eq!(e.key(), key);
assert_eq!(e.get(), &new_value);
}
EntryRef::Vacant(_) => panic!(),
}
assert_eq!(a[key], new_value);
assert_eq!(a.len(), 1);
let entry = a.entry_ref(key).and_replace_entry_with(|k, v| {
assert_eq!(k, key);
assert_eq!(v, new_value);
None
});
match entry {
EntryRef::Vacant(e) => assert_eq!(e.key(), key),
EntryRef::Occupied(_) => panic!(),
}
assert!(!a.contains_key(key));
assert_eq!(a.len(), 0);
}
#[test]
fn test_raw_occupied_entry_replace_entry_with() {
let mut a = HashMap::new();
let key = "a key";
let value = "an initial value";
let new_value = "a new value";
let entry = a
.raw_entry_mut()
.from_key(&key)
.insert(key, value)
.replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, value);
Some(new_value)
});
match entry {
RawEntryMut::Occupied(e) => {
assert_eq!(e.key(), &key);
assert_eq!(e.get(), &new_value);
}
RawEntryMut::Vacant(_) => panic!(),
}
assert_eq!(a[key], new_value);
assert_eq!(a.len(), 1);
let entry = match a.raw_entry_mut().from_key(&key) {
RawEntryMut::Occupied(e) => e.replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, new_value);
None
}),
RawEntryMut::Vacant(_) => panic!(),
};
match entry {
RawEntryMut::Vacant(_) => {}
RawEntryMut::Occupied(_) => panic!(),
}
assert!(!a.contains_key(key));
assert_eq!(a.len(), 0);
}
#[test]
fn test_raw_entry_and_replace_entry_with() {
let mut a = HashMap::new();
let key = "a key";
let value = "an initial value";
let new_value = "a new value";
let entry = a
.raw_entry_mut()
.from_key(&key)
.and_replace_entry_with(|_, _| panic!());
match entry {
RawEntryMut::Vacant(_) => {}
RawEntryMut::Occupied(_) => panic!(),
}
a.insert(key, value);
let entry = a
.raw_entry_mut()
.from_key(&key)
.and_replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, value);
Some(new_value)
});
match entry {
RawEntryMut::Occupied(e) => {
assert_eq!(e.key(), &key);
assert_eq!(e.get(), &new_value);
}
RawEntryMut::Vacant(_) => panic!(),
}
assert_eq!(a[key], new_value);
assert_eq!(a.len(), 1);
let entry = a
.raw_entry_mut()
.from_key(&key)
.and_replace_entry_with(|k, v| {
assert_eq!(k, &key);
assert_eq!(v, new_value);
None
});
match entry {
RawEntryMut::Vacant(_) => {}
RawEntryMut::Occupied(_) => panic!(),
}
assert!(!a.contains_key(key));
assert_eq!(a.len(), 0);
}
#[test]
fn test_replace_entry_with_doesnt_corrupt() {
#![allow(deprecated)] fn check(m: &HashMap<i32, ()>) {
for k in m.keys() {
assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
}
}
let mut m = HashMap::new();
let mut rng = {
let seed = u64::from_le_bytes(*b"testseed");
SmallRng::seed_from_u64(seed)
};
for _ in 0..50 {
let x = rng.gen_range(-10..10);
m.insert(x, ());
}
for _ in 0..1000 {
let x = rng.gen_range(-10..10);
m.entry(x).and_replace_entry_with(|_, _| None);
check(&m);
}
}
#[test]
fn test_replace_entry_ref_with_doesnt_corrupt() {
#![allow(deprecated)] fn check(m: &HashMap<std::string::String, ()>) {
for k in m.keys() {
assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
}
}
let mut m = HashMap::new();
let mut rng = {
let seed = u64::from_le_bytes(*b"testseed");
SmallRng::seed_from_u64(seed)
};
for _ in 0..50 {
let mut x = std::string::String::with_capacity(1);
x.push(rng.gen_range('a'..='z'));
m.insert(x, ());
}
for _ in 0..1000 {
let mut x = std::string::String::with_capacity(1);
x.push(rng.gen_range('a'..='z'));
m.entry_ref(x.as_str()).and_replace_entry_with(|_, _| None);
check(&m);
}
}
#[test]
fn test_retain() {
let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
map.retain(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 50);
assert_eq!(map[&2], 20);
assert_eq!(map[&4], 40);
assert_eq!(map[&6], 60);
}
#[test]
fn test_drain_filter() {
{
let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
let drained = map.drain_filter(|&k, _| k % 2 == 0);
let mut out = drained.collect::<Vec<_>>();
out.sort_unstable();
assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out);
assert_eq!(map.len(), 4);
}
{
let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
drop(map.drain_filter(|&k, _| k % 2 == 0));
assert_eq!(map.len(), 4);
}
}
#[test]
#[cfg_attr(miri, ignore)] fn test_try_reserve() {
use crate::TryReserveError::{AllocError, CapacityOverflow};
const MAX_ISIZE: usize = isize::MAX as usize;
let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) {
} else {
panic!("usize::MAX should trigger an overflow!");
}
if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) {
} else {
panic!("isize::MAX should trigger an overflow!");
}
if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) {
} else {
let mut empty_bytes2: HashMap<u8, u8> = HashMap::new();
let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
let mut empty_bytes3: HashMap<u8, u8> = HashMap::new();
let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
let mut empty_bytes4: HashMap<u8, u8> = HashMap::new();
if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) {
} else {
panic!("isize::MAX / 5 should trigger an OOM!");
}
}
}
#[test]
fn test_raw_entry() {
use super::RawEntryMut::{Occupied, Vacant};
let xs = [(1_i32, 10_i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
let mut map: HashMap<_, _> = xs.iter().copied().collect();
let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
super::make_insert_hash::<i32, _>(map.hasher(), &k)
};
match map.raw_entry_mut().from_key(&1) {
Vacant(_) => unreachable!(),
Occupied(mut view) => {
assert_eq!(view.get(), &10);
assert_eq!(view.insert(100), 10);
}
}
let hash1 = compute_hash(&map, 1);
assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
assert_eq!(
map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(),
(&1, &100)
);
assert_eq!(
map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(),
(&1, &100)
);
assert_eq!(map.len(), 6);
match map.raw_entry_mut().from_key(&2) {
Vacant(_) => unreachable!(),
Occupied(mut view) => {
let v = view.get_mut();
let new_v = (*v) * 10;
*v = new_v;
}
}
let hash2 = compute_hash(&map, 2);
assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
assert_eq!(
map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(),
(&2, &200)
);
assert_eq!(
map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(),
(&2, &200)
);
assert_eq!(map.len(), 6);
let hash3 = compute_hash(&map, 3);
match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
Vacant(_) => unreachable!(),
Occupied(view) => {
assert_eq!(view.remove_entry(), (3, 30));
}
}
assert_eq!(map.raw_entry().from_key(&3), None);
assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
assert_eq!(map.len(), 5);
match map.raw_entry_mut().from_key(&10) {
Occupied(_) => unreachable!(),
Vacant(view) => {
assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
}
}
assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
assert_eq!(map.len(), 6);
for k in 0..12 {
let hash = compute_hash(&map, k);
let v = map.get(&k).copied();
let kv = v.as_ref().map(|v| (&k, v));
assert_eq!(map.raw_entry().from_key(&k), kv);
assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
match map.raw_entry_mut().from_key(&k) {
Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
Vacant(_) => assert_eq!(v, None),
}
match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
Vacant(_) => assert_eq!(v, None),
}
match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
Vacant(_) => assert_eq!(v, None),
}
}
}
#[test]
fn test_key_without_hash_impl() {
#[derive(Debug)]
struct IntWrapper(u64);
let mut m: HashMap<IntWrapper, (), ()> = HashMap::default();
{
assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none());
}
{
let vacant_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) {
RawEntryMut::Occupied(..) => panic!("Found entry for key 0"),
RawEntryMut::Vacant(e) => e,
};
vacant_entry.insert_with_hasher(0, IntWrapper(0), (), |k| k.0);
}
{
assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some());
assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_none());
assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
}
{
let vacant_entry = match m.raw_entry_mut().from_hash(1, |k| k.0 == 1) {
RawEntryMut::Occupied(..) => panic!("Found entry for key 1"),
RawEntryMut::Vacant(e) => e,
};
vacant_entry.insert_with_hasher(1, IntWrapper(1), (), |k| k.0);
}
{
assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some());
assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some());
assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
}
{
let occupied_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) {
RawEntryMut::Occupied(e) => e,
RawEntryMut::Vacant(..) => panic!("Couldn't find entry for key 0"),
};
occupied_entry.remove();
}
assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none());
assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some());
assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
}
#[test]
#[cfg(feature = "raw")]
fn test_into_iter_refresh() {
#[cfg(miri)]
const N: usize = 32;
#[cfg(not(miri))]
const N: usize = 128;
let mut rng = rand::thread_rng();
for n in 0..N {
let mut map = HashMap::new();
for i in 0..n {
assert!(map.insert(i, 2 * i).is_none());
}
let hash_builder = map.hasher().clone();
let mut it = unsafe { map.table.iter() };
assert_eq!(it.len(), n);
let mut i = 0;
let mut left = n;
let mut removed = Vec::new();
loop {
if i < n && rng.gen_bool(0.1) {
let hash_value = super::make_insert_hash(&hash_builder, &i);
unsafe {
let e = map.table.find(hash_value, |q| q.0.eq(&i));
if let Some(e) = e {
it.reflect_remove(&e);
let t = map.table.remove(e);
removed.push(t);
left -= 1;
} else {
assert!(removed.contains(&(i, 2 * i)), "{} not in {:?}", i, removed);
let e = map.table.insert(
hash_value,
(i, 2 * i),
super::make_hasher::<_, usize, _>(&hash_builder),
);
it.reflect_insert(&e);
if let Some(p) = removed.iter().position(|e| e == &(i, 2 * i)) {
removed.swap_remove(p);
}
left += 1;
}
}
}
let e = it.next();
if e.is_none() {
break;
}
assert!(i < n);
let t = unsafe { e.unwrap().as_ref() };
assert!(!removed.contains(t));
let (key, value) = t;
assert_eq!(*value, 2 * key);
i += 1;
}
assert!(i <= n);
assert_eq!(map.table.len(), left);
}
}
#[test]
fn test_const_with_hasher() {
use core::hash::BuildHasher;
use std::collections::hash_map::DefaultHasher;
#[derive(Clone)]
struct MyHasher;
impl BuildHasher for MyHasher {
type Hasher = DefaultHasher;
fn build_hasher(&self) -> DefaultHasher {
DefaultHasher::new()
}
}
const EMPTY_MAP: HashMap<u32, std::string::String, MyHasher> =
HashMap::with_hasher(MyHasher);
let mut map = EMPTY_MAP;
map.insert(17, "seventeen".to_owned());
assert_eq!("seventeen", map[&17]);
}
#[test]
fn test_get_each_mut() {
let mut map = HashMap::new();
map.insert("foo".to_owned(), 0);
map.insert("bar".to_owned(), 10);
map.insert("baz".to_owned(), 20);
map.insert("qux".to_owned(), 30);
let xs = map.get_many_mut(["foo", "qux"]);
assert_eq!(xs, Some([&mut 0, &mut 30]));
let xs = map.get_many_mut(["foo", "dud"]);
assert_eq!(xs, None);
let xs = map.get_many_mut(["foo", "foo"]);
assert_eq!(xs, None);
let ys = map.get_many_key_value_mut(["bar", "baz"]);
assert_eq!(
ys,
Some([(&"bar".to_owned(), &mut 10), (&"baz".to_owned(), &mut 20),]),
);
let ys = map.get_many_key_value_mut(["bar", "dip"]);
assert_eq!(ys, None);
let ys = map.get_many_key_value_mut(["baz", "baz"]);
assert_eq!(ys, None);
}
#[test]
#[should_panic = "panic in drop"]
fn test_clone_from_double_drop() {
#[derive(Clone)]
struct CheckedDrop {
panic_in_drop: bool,
dropped: bool,
}
impl Drop for CheckedDrop {
fn drop(&mut self) {
if self.panic_in_drop {
self.dropped = true;
panic!("panic in drop");
}
if self.dropped {
panic!("double drop");
}
self.dropped = true;
}
}
const DISARMED: CheckedDrop = CheckedDrop {
panic_in_drop: false,
dropped: false,
};
const ARMED: CheckedDrop = CheckedDrop {
panic_in_drop: true,
dropped: false,
};
let mut map1 = HashMap::new();
map1.insert(1, DISARMED);
map1.insert(2, DISARMED);
map1.insert(3, DISARMED);
map1.insert(4, DISARMED);
let mut map2 = HashMap::new();
map2.insert(1, DISARMED);
map2.insert(2, ARMED);
map2.insert(3, DISARMED);
map2.insert(4, DISARMED);
map2.clone_from(&map1);
}
}