use alloc::sync::Arc;
use arc_swap::{ArcSwap, Guard};
use crate::raw::{
Allocator, Bucket, CowRawIntoIter, CowRawIter, CowRawTable, Global, RawDrain, RawExtractIf,
RawTableGuard,
};
use crate::{ptr_eq, DefaultHashBuilder, Equivalent, TryReserveError};
use core::borrow::Borrow;
use core::fmt::{self, Debug};
use core::hash::{BuildHasher, Hash};
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::mem;
use core::ops::{Deref, DerefMut};
pub struct CowHashMap<K: Clone, V, S = DefaultHashBuilder, A: Allocator + Clone = Global> {
pub(crate) hash_builder: S,
pub(crate) table: Arc<CowRawTable<(K, Arc<ArcSwap<V>>), A>>,
}
impl<K: Clone, V, S: Clone, A: Allocator + Clone> Clone for CowHashMap<K, V, S, A> {
fn clone(&self) -> Self {
CowHashMap {
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: Equivalent<K> + ?Sized,
{
move |x| k.equivalent(&x.0)
}
#[allow(dead_code)]
#[cfg_attr(feature = "inline-more", inline)]
fn equivalent<Q, K>(k: &Q) -> impl Fn(&K) -> bool + '_
where
Q: Equivalent<K> + ?Sized,
{
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)
}
enum CowValueGuardMode<T> {
Read(Arc<T>),
Write(Option<T>),
}
pub struct CowValueGuard<V: Clone> {
inner: Arc<ArcSwap<V>>,
mode: CowValueGuardMode<V>,
}
impl<V: Clone> CowValueGuard<V> {
pub fn new(inner: Arc<ArcSwap<V>>) -> Self {
Self {
mode: CowValueGuardMode::Read(inner.load_full()),
inner,
}
}
pub fn freeze(&mut self) -> Arc<V> {
match &mut self.mode {
CowValueGuardMode::Read(inner) => inner.clone(),
CowValueGuardMode::Write(inner) => {
if let Some(inner) = inner.take() {
self.inner.store(Arc::new(inner));
}
let ret = self.inner.load_full();
self.mode = CowValueGuardMode::Read(ret.clone());
ret
},
}
}
}
impl<V: Clone> PartialEq<V> for CowValueGuard<V>
where
V: PartialEq<V>,
{
fn eq(&self, other: &V) -> bool {
match (self, other) {
(
CowValueGuard {
mode: CowValueGuardMode::Read(inner),
..
},
other,
) => inner.as_ref() == other,
(
CowValueGuard {
mode: CowValueGuardMode::Write(inner),
..
},
other,
) => inner.as_ref() == Some(other),
}
}
}
impl<V: Clone> PartialEq for CowValueGuard<V>
where
V: PartialEq<V>,
{
fn eq(&self, other: &CowValueGuard<V>) -> bool {
match (self, other) {
(
CowValueGuard {
mode: CowValueGuardMode::Read(inner),
..
},
other,
) => inner.as_ref() == other.deref(),
(
CowValueGuard {
mode: CowValueGuardMode::Write(inner),
..
},
other,
) => inner.as_ref() == Some(other.deref()),
}
}
}
impl<V: Clone> Debug for CowValueGuard<V>
where
V: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.mode {
CowValueGuardMode::Read(inner) => inner.as_ref().fmt(f),
CowValueGuardMode::Write(inner) => inner.as_ref().fmt(f),
}
}
}
impl<V: Clone> Eq for CowValueGuard<V> where V: Eq {}
impl<V: Clone> Deref for CowValueGuard<V> {
type Target = V;
fn deref(&self) -> &V {
match &self.mode {
CowValueGuardMode::Read(inner) => inner.as_ref(),
CowValueGuardMode::Write(inner) => inner.as_ref().unwrap(),
}
}
}
impl<V: Clone> DerefMut for CowValueGuard<V> {
fn deref_mut(&mut self) -> &mut V {
match &mut self.mode {
CowValueGuardMode::Read(inner) => {
let inner = inner.as_ref().clone();
self.mode = CowValueGuardMode::Write(Some(inner));
}
CowValueGuardMode::Write(_) => {}
}
match &mut self.mode {
CowValueGuardMode::Read(_) => unreachable!(),
CowValueGuardMode::Write(inner) => inner.as_mut().unwrap(),
}
}
}
impl<V: Clone> Drop for CowValueGuard<V> {
fn drop(&mut self) {
match &mut self.mode {
CowValueGuardMode::Read(_) => {}
CowValueGuardMode::Write(inner) => {
if let Some(inner) = inner.take() {
self.inner.store(Arc::new(inner));
}
}
}
}
}
#[cfg(feature = "default-hasher")]
impl<K: Clone, V> CowHashMap<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 = "default-hasher")]
impl<K: Clone, V, A: Allocator + Clone> CowHashMap<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: Clone, V, S> CowHashMap<K, V, S> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_hasher(hash_builder: S) -> Self {
Self {
hash_builder,
table: Arc::new(CowRawTable::new()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
Self {
hash_builder,
table: Arc::new(CowRawTable::with_capacity(capacity)),
}
}
}
impl<K: Clone, V, S, A: Allocator + Clone> CowHashMap<K, V, S, A> {
#[inline]
pub fn allocator(&self) -> A {
self.table.map(|t| t.allocator().clone())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self {
Self {
hash_builder,
table: Arc::new(CowRawTable::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: Arc::new(CowRawTable::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.map(|t| t.capacity())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn keys(&self) -> Keys<K, V, A> {
Keys { inner: self.iter() }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn values(&self) -> Values<K, V, A> {
Values { inner: self.iter() }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn values_mut(&self) -> ValuesMut<K, V, A> {
ValuesMut {
inner: self.iter_mut(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter(&self) -> Iter<K, V, A> {
unsafe {
Iter {
inner: self.table.iter(),
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter_mut(&self) -> IterMut<K, V, A> {
unsafe {
IterMut {
inner: self.table.iter(),
}
}
}
#[cfg(test)]
#[cfg_attr(feature = "inline-more", inline)]
fn raw_capacity(&self) -> usize {
self.table.map(|t| t.buckets())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn len(&self) -> usize {
self.table.map(|t| t.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(&self) -> Iter<K, V, A> {
self.table
.rcu(|t| {
let ret = self.iter();
t.clear();
ret
})
.inner
}
pub fn retain<F>(&self, mut f: F)
where
F: FnMut(&K, &V) -> bool,
V: Clone,
{
unsafe {
self.table.rcu(|t| {
for item in t.iter() {
let &(ref key, ref value) = item.as_ref();
let value = value.load();
let retain = f(key, &value);
if !retain {
t.erase(item);
}
}
});
}
}
pub fn retain_mut<F>(&self, mut f: F)
where
F: FnMut(&K, &mut V) -> bool,
V: Clone,
{
unsafe {
self.table.rcu(|t| {
for item in t.iter() {
let &mut (ref key, ref mut value) = item.as_mut();
let mut retain = false;
value.rcu(|v| {
let mut value = v.deref().clone();
retain = f(key, &mut value);
value
});
if !retain {
t.erase(item);
}
}
});
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn extract_if<F>(&self, f: F) -> ExtractIf<'_, K, V, F, A>
where
F: FnMut(&K, &mut V) -> bool,
{
ExtractIf {
f,
inner: RawExtractIf {
iter: unsafe { self.table.iter() },
table: &self.table,
},
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn clear(&self) {
self.table.rcu(|t| t.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: Clone, V, S, A> CowHashMap<K, V, S, A>
where
K: Eq + Hash,
S: BuildHasher,
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
pub fn reserve(&self, additional: usize) {
self.table.rcu(|t| {
t.reserve(
additional,
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder),
)
});
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn try_reserve(&self, additional: usize) -> Result<(), TryReserveError> {
self.table
.rcu(|t| {
t.try_reserve(
additional,
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder),
)
})
.inner
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn shrink_to_fit(&self) {
self.table
.rcu(|t| t.shrink_to(0, make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder)));
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn shrink_to(&self, min_capacity: usize) {
self.table.rcu(|t| {
t.shrink_to(
min_capacity,
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder),
)
});
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn entry(&self, key: K) -> Entry<K, V, S, A>
where
S: Clone,
{
let hash = make_hash::<K, S>(&self.hash_builder, &key);
let table = self.table.inner.load().clone();
let lookup = table.find(hash, equivalent_key(&key));
if let Some(elem) = lookup {
Entry::Occupied(OccupiedEntry {
hash,
key: Some(key),
elem: RawTableGuard {
guard: table,
inner: elem,
},
table: self.clone(),
})
} else {
Entry::Vacant(VacantEntry {
hash,
key,
table: self.clone(),
})
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn entry_ref<'a, 'b, 'c, Q>(&'a self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A>
where
Q: Hash + Equivalent<K> + ?Sized,
{
let hash = make_hash::<Q, S>(&self.hash_builder, key);
let table = self.table.inner.load().clone();
let lookup = table.find(hash, equivalent_key(key));
if let Some(elem) = lookup {
EntryRef::Occupied(OccupiedEntryRef {
hash,
key: Some(KeyOrRef::Borrowed(key)),
elem: RawTableGuard {
guard: table,
inner: elem,
},
table: self,
})
} else {
EntryRef::Vacant(VacantEntryRef {
hash,
key: KeyOrRef::Borrowed(key),
table: self,
})
}
}
#[inline]
pub fn get<Q>(&self, k: &Q) -> Option<Arc<V>>
where
Q: Hash + Equivalent<K> + ?Sized,
{
self.table.map(|t| {
if t.is_empty() {
None
} else {
let hash = make_hash::<Q, S>(&self.hash_builder, k);
let r = t.get(hash, equivalent_key(k))?;
Some(r.1.load_full())
}
})
}
#[inline]
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(K, Arc<V>)>
where
Q: Hash + Equivalent<K> + ?Sized,
{
self.table.map(|t| {
if t.is_empty() {
None
} else {
let hash = make_hash::<Q, S>(&self.hash_builder, k);
let r = t.get(hash, equivalent_key(k))?;
Some((r.0.clone(), r.1.load_full()))
}
})
}
#[inline]
pub fn get_key_value_mut<Q>(&self, k: &Q) -> Option<(K, CowValueGuard<V>)>
where
Q: Hash + Equivalent<K> + ?Sized,
V: Clone,
{
self.table.map(|t| {
if t.is_empty() {
None
} else {
let hash = make_hash::<Q, S>(&self.hash_builder, k);
let r = t.get(hash, equivalent_key(k))?;
Some((r.0.clone(), CowValueGuard::new(r.1.clone())))
}
})
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn contains_key<Q>(&self, k: &Q) -> bool
where
Q: Hash + Equivalent<K> + ?Sized,
{
self.table.map(|t| {
if t.is_empty() {
false
} else {
let hash = make_hash::<Q, S>(&self.hash_builder, k);
t.get(hash, equivalent_key(k)).is_some()
}
})
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut<Q>(&self, k: &Q) -> Option<CowValueGuard<V>>
where
Q: Hash + Equivalent<K> + ?Sized,
V: Clone,
{
self.table.map(|t| {
if t.is_empty() {
None
} else {
let hash = make_hash::<Q, S>(&self.hash_builder, k);
let r = t.get(hash, equivalent_key(k))?;
Some(CowValueGuard::new(r.1.clone()))
}
})
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&self, k: K, v: V) -> Option<Arc<V>> {
let hash = make_hash::<K, S>(&self.hash_builder, &k);
let v = Arc::new(ArcSwap::new(Arc::new(v)));
let ret = self
.table
.rcu(|t| {
let v = v.clone();
let hasher = make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder);
match t.find_or_find_insert_slot(hash, equivalent_key(&k), hasher) {
Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
Err(slot) => {
unsafe {
t.insert_in_slot(hash, slot, (k.clone(), v));
}
None
}
}
})
.inner;
ret.map(|r| r.load_full())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_fast(&mut self, k: K, v: V) -> Option<Arc<V>> {
let hash = make_hash::<K, S>(&self.hash_builder, &k);
let v = Arc::new(ArcSwap::new(Arc::new(v)));
let ret = self.table.rcu_fast(|t| {
let v = v.clone();
let hasher = make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder);
match t.find_or_find_insert_slot(hash, equivalent_key(&k), hasher) {
Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
Err(slot) => {
unsafe {
t.insert_in_slot(hash, slot, (k.clone(), v));
}
None
}
}
})?;
Some(ret.load_full())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_mut(&self, k: K, v: V) -> Option<CowValueGuard<V>>
where
V: Clone,
{
let hash = make_hash::<K, S>(&self.hash_builder, &k);
let v = Arc::new(ArcSwap::new(Arc::new(v)));
let ret = self
.table
.rcu(|t| {
let v = v.clone();
let hasher = make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder);
match t.find_or_find_insert_slot(hash, equivalent_key(&k), hasher) {
Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
Err(slot) => {
unsafe {
t.insert_in_slot(hash, slot, (k.clone(), v));
}
None
}
}
})
.inner;
ret.map(|r| CowValueGuard::new(r))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_mut_fast(&mut self, k: K, v: V) -> Option<CowValueGuard<V>>
where
V: Clone,
{
let hash = make_hash::<K, S>(&self.hash_builder, &k);
let v = Arc::new(ArcSwap::new(Arc::new(v)));
let ret = self.table.rcu_fast(|t| {
let v = v.clone();
let hasher = make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder);
match t.find_or_find_insert_slot(hash, equivalent_key(&k), hasher) {
Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
Err(slot) => {
unsafe {
t.insert_in_slot(hash, slot, (k.clone(), v));
}
None
}
}
});
ret.map(|r| CowValueGuard::new(r))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_unique_unchecked(&self, k: K, v: V) -> (&K, Arc<V>) {
let hash = make_hash::<K, S>(&self.hash_builder, &k);
let v = Arc::new(ArcSwap::new(Arc::new(v)));
let bucket = self.table.rcu(|t| {
t.insert(
hash,
(k.clone(), v.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder),
)
});
let (k_ref, v_ref) = unsafe { bucket.as_ref() };
(k_ref, v_ref.load_full())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_unique_unchecked_mut(&self, k: K, v: V) -> (&K, CowValueGuard<V>)
where
V: Clone,
{
let hash = make_hash::<K, S>(&self.hash_builder, &k);
let v = Arc::new(ArcSwap::new(Arc::new(v)));
let bucket = self.table.rcu(|t| {
t.insert(
hash,
(k.clone(), v.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.hash_builder),
)
});
let (k_ref, v_ref) = unsafe { bucket.as_ref() };
(k_ref, CowValueGuard::new(v_ref.clone()))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn try_insert(&self, key: K, value: V) -> Result<Arc<V>, OccupiedError<K, V, S, A>>
where
S: Clone,
{
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 try_insert_mut(
&self,
key: K,
value: V,
) -> Result<CowValueGuard<V>, OccupiedError<K, V, S, A>>
where
S: Clone,
V: Clone,
{
match self.entry(key) {
Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
Entry::Vacant(entry) => Ok(entry.insert_mut(value)),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove<Q>(&self, k: &Q) -> Option<Arc<V>>
where
Q: Hash + Equivalent<K> + ?Sized,
{
match self.remove_entry(k) {
Some((_, v)) => Some(v),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_fast<Q>(&mut self, k: &Q) -> Option<Arc<V>>
where
Q: Hash + Equivalent<K> + ?Sized,
{
match self.remove_entry_fast(k) {
Some((_, v)) => Some(v),
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry<Q>(&self, k: &Q) -> Option<(K, Arc<V>)>
where
Q: Hash + Equivalent<K> + ?Sized,
{
let hash = make_hash::<Q, S>(&self.hash_builder, k);
let ret = self
.table
.rcu(|t| t.remove_entry(hash, equivalent_key(k)))
.inner?;
Some((ret.0, ret.1.load_full()))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry_fast<Q>(&mut self, k: &Q) -> Option<(K, Arc<V>)>
where
Q: Hash + Equivalent<K> + ?Sized,
{
let hash = make_hash::<Q, S>(&self.hash_builder, k);
let ret = self
.table
.rcu_fast(|t| t.remove_entry(hash, equivalent_key(k)))?;
Some((ret.0, ret.1.load_full()))
}
}
impl<K: Clone, V, S, A: Allocator + Clone> CowHashMap<K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_entry_mut(&self) -> RawEntryBuilderMut<'_, K, V, S, A> {
RawEntryBuilderMut { map: self }
}
#[cfg(feature = "raw")]
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_table(&self) -> &RawTable<(K, V), A> {
&self.table
}
#[cfg(feature = "raw")]
#[cfg_attr(feature = "inline-more", inline)]
pub fn raw_table_mut(&mut self) -> &mut RawTable<(K, V), A> {
&mut self.table
}
}
impl<K: Clone, V, S, A> Debug for CowHashMap<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: Clone, V, S, A> Default for CowHashMap<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())
}
}
#[cfg(feature = "default-hasher")]
impl<K: Clone, V, A, const N: usize> From<[(K, V); N]> for CowHashMap<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<K, V, A: Allocator + Clone = Global> {
inner: CowRawIter<(K, Arc<ArcSwap<V>>), A>,
}
impl<K, V, A> Clone for Iter<K, V, A>
where
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Iter {
inner: self.inner.clone(),
}
}
}
pub struct IterMut<K, V, A: Allocator + Clone = Global> {
inner: CowRawIter<(K, Arc<ArcSwap<V>>), A>,
}
unsafe impl<K: Send, V: Send, A> Send for IterMut<K, V, A> where A: Allocator + Clone {}
impl<K, V, A> IterMut<K, V, A>
where
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter(&self) -> Iter<K, V, A> {
Iter {
inner: self.inner.clone(),
}
}
}
pub struct IntoIter<K, V, A: Allocator + Clone = Global> {
inner: CowRawIntoIter<(K, Arc<ArcSwap<V>>), A>,
}
impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter(&self) -> Iter<K, V, A> {
Iter {
inner: self.inner.iter(),
}
}
}
pub struct IntoKeys<K: Clone, V, A: Allocator + Clone = Global> {
inner: IntoIter<K, V, A>,
}
impl<K: Clone, 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()
}
#[inline]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.inner.fold(init, |acc, (k, _)| f(acc, k))
}
}
impl<K: Clone, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
#[inline]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K: Clone, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
pub struct IntoValues<K: Clone, V, A: Allocator + Clone = Global> {
inner: IntoIter<K, V, A>,
}
impl<K: Clone, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
type Item = Arc<V>;
#[inline]
fn next(&mut self) -> Option<Arc<V>> {
self.inner.next().map(|(_, v)| v)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.inner.fold(init, |acc, (_, v)| f(acc, v))
}
}
impl<K: Clone, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
#[inline]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K: Clone, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
pub struct Keys<K: Clone, V, A: Allocator + Clone = Global> {
inner: Iter<K, V, A>,
}
impl<K: Clone, V, A: Allocator + Clone> Clone for Keys<K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Keys {
inner: self.inner.clone(),
}
}
}
impl<K: Debug + Clone, V, A: Allocator + Clone> fmt::Debug for Keys<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub struct Values<K: Clone, V, A: Allocator + Clone = Global> {
inner: Iter<K, V, A>,
}
impl<K: Clone, V, A: Allocator + Clone> Clone for Values<K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Values {
inner: self.inner.clone(),
}
}
}
impl<K: Clone, V: Debug + Clone, A: Allocator + Clone> fmt::Debug for Values<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub struct Drain<'a, K: Clone, V, A: Allocator + Clone = Global> {
inner: RawTableGuard<(K, Arc<ArcSwap<V>>), A, RawDrain<'a, (K, Arc<ArcSwap<V>>), A>>,
}
impl<K: Clone, V, A: Allocator + Clone> Drain<'_, K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn iter(&self) -> Iter<K, V, A> {
Iter {
inner: CowRawIter {
inner: self.inner.iter(),
guard: Guard::from_inner(self.inner.guard.clone()),
},
}
}
}
#[must_use = "Iterators are lazy unless consumed"]
pub struct ExtractIf<'a, K: Clone, V, F, A: Allocator + Clone = Global>
where
F: FnMut(&K, &mut V) -> bool,
{
f: F,
inner: RawExtractIf<'a, (K, Arc<ArcSwap<V>>), A>,
}
impl<K: Clone, V, F, A> Iterator for ExtractIf<'_, K, V, F, A>
where
F: FnMut(&K, &mut V) -> bool,
A: Allocator + Clone,
V: Clone,
{
type Item = (K, Arc<V>);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next(|&mut (ref k, ref mut v)| {
let mut ret = false;
v.rcu(|v| {
let mut v = v.deref().clone();
ret = (self.f)(k, &mut v);
v
});
ret
})
.map(|(k, v)| (k, v.deref().load_full()))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.inner.iter.size_hint().1)
}
}
impl<K: Clone, V: Clone, F, A: Allocator + Clone> FusedIterator for ExtractIf<'_, K, V, F, A> where
F: FnMut(&K, &mut V) -> bool
{
}
pub struct ValuesMut<K: Clone, V, A: Allocator + Clone = Global> {
inner: IterMut<K, V, A>,
}
pub struct RawEntryBuilderMut<'a, K: Clone, V, S, A: Allocator + Clone = Global> {
#[allow(dead_code)]
map: &'a CowHashMap<K, V, S, A>,
}
pub enum RawEntryMut<'a, K: Clone, 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: Clone, V, S, A: Allocator + Clone = Global> {
hash: u64,
elem: Bucket<(K, Arc<ArcSwap<V>>)>,
table: &'a mut CowRawTable<(K, Arc<ArcSwap<V>>), A>,
hash_builder: &'a S,
}
unsafe impl<K: Clone, V, S, A> Send for RawOccupiedEntryMut<'_, K, V, S, A>
where
K: Send,
V: Send,
S: Send,
A: Send + Allocator + Clone,
{
}
unsafe impl<K: Clone, 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: Clone, V, S, A: Allocator + Clone = Global> {
table: &'a mut CowRawTable<(K, Arc<ArcSwap<V>>), A>,
hash_builder: &'a S,
}
impl<'a, K: Clone, 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(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) -> (K, Arc<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_mut(self, default_key: K, default_val: V) -> (K, CowValueGuard<V>)
where
K: Hash,
S: BuildHasher,
V: Clone,
{
match self {
RawEntryMut::Occupied(entry) => entry.into_key_value_mut(),
RawEntryMut::Vacant(entry) => entry.insert_mut(default_key, default_val),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with<F>(self, default: F) -> (K, Arc<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 or_insert_with_mut<F>(self, default: F) -> (K, CowValueGuard<V>)
where
F: FnOnce() -> (K, V),
K: Hash,
S: BuildHasher,
V: Clone,
{
match self {
RawEntryMut::Occupied(entry) => entry.into_key_value_mut(),
RawEntryMut::Vacant(entry) => {
let (k, v) = default();
entry.insert_mut(k, v)
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(K, Arc<V>),
{
match self {
RawEntryMut::Occupied(entry) => {
{
let (k, v) = entry.get_key_value();
f(k, v);
}
RawEntryMut::Occupied(entry)
}
RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_modify_mut<F>(self, f: F) -> Self
where
F: FnOnce(K, CowValueGuard<V>),
V: Clone,
{
match self {
RawEntryMut::Occupied(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: Fn(&K, &V) -> Option<V>,
K: Equivalent<K>,
V: Clone,
{
match self {
RawEntryMut::Occupied(entry) => entry.replace_entry_with(f),
RawEntryMut::Vacant(_) => self,
}
}
}
impl<'a, K: Clone, 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 get(&self) -> Arc<V> {
unsafe { &self.elem.as_ref().1 }.load_full()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_mut(self) -> CowValueGuard<V>
where
V: Clone,
{
CowValueGuard::new(unsafe { &self.elem.as_mut().1 }.clone())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut(&self) -> CowValueGuard<V>
where
V: Clone,
{
CowValueGuard::new(unsafe { &self.elem.as_mut().1 }.clone())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_key_value(&self) -> (K, Arc<V>) {
unsafe {
let (key, value) = self.elem.as_ref();
(key.clone(), value.load_full())
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_key_value_mut(&self) -> (K, CowValueGuard<V>)
where
V: Clone,
{
unsafe {
let &(ref key, ref value) = self.elem.as_ref();
(key.clone(), CowValueGuard::new(value.clone()))
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_key_value(self) -> (K, Arc<V>) {
unsafe {
let &mut (ref mut key, ref mut value) = self.elem.as_mut();
(key.clone(), value.load_full())
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_key_value_mut(self) -> (K, CowValueGuard<V>)
where
V: Clone,
{
unsafe {
let &mut (ref mut key, ref mut value) = self.elem.as_mut();
(key.clone(), CowValueGuard::new(value.clone()))
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&self, value: V) -> Arc<V> {
let new_value = Arc::new(value);
let elem = unsafe { &self.elem.as_ref().1 };
let mut ret = elem.load_full();
elem.rcu(|v| {
ret = v.clone();
new_value.clone()
});
ret
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove(self) -> Arc<V>
where
K: Equivalent<K>,
{
self.remove_entry().1
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry(self) -> (K, Arc<V>)
where
K: Equivalent<K>,
{
let ret = self
.table
.rcu(|t| unsafe {
let elem = t.find(self.hash, equivalent_key(self.key()));
if let Some(elem) = elem {
t.remove(elem);
}
self.elem.as_ref()
})
.inner;
(ret.0.clone(), ret.1.load_full())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry_with<F>(self, f: F) -> RawEntryMut<'a, K, V, S, A>
where
F: Fn(&K, &V) -> Option<V>,
K: Equivalent<K>,
V: Clone,
{
let elem = unsafe { self.elem.as_ref() };
let key = &elem.0;
let value = elem.1.load_full();
loop {
match f(key, &value) {
Some(new) => {
let prev = elem.1.compare_and_swap(&value, Arc::new(new));
let swapped = ptr_eq(&value, &*prev);
if swapped {
return RawEntryMut::Occupied(self);
}
}
None => {
self.table.rcu(|t| unsafe {
let elem = t.find(self.hash, equivalent_key(self.key()));
if let Some(elem) = elem {
t.remove(elem);
}
});
return RawEntryMut::Vacant(RawVacantEntryMut {
hash_builder: self.hash_builder,
table: self.table,
});
}
}
}
}
}
impl<'a, K: Clone, 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) -> (K, Arc<V>)
where
K: Hash,
S: BuildHasher,
{
let hash = make_hash::<K, S>(self.hash_builder, &key);
self.insert_hashed_nocheck(hash, key, Arc::new(ArcSwap::new(Arc::new(value))))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_mut(self, key: K, value: V) -> (K, CowValueGuard<V>)
where
K: Hash,
S: BuildHasher,
V: Clone,
{
let hash = make_hash::<K, S>(self.hash_builder, &key);
self.insert_hashed_nocheck_mut(hash, key, Arc::new(ArcSwap::new(Arc::new(value))))
}
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::shadow_unrelated)]
pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: Arc<ArcSwap<V>>) -> (K, Arc<V>)
where
K: Hash,
S: BuildHasher,
{
self.table.rcu(|t| {
t.insert_entry(
hash,
(key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(self.hash_builder),
);
});
(key, value.load_full())
}
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::shadow_unrelated)]
pub fn insert_hashed_nocheck_mut(
self,
hash: u64,
key: K,
value: Arc<ArcSwap<V>>,
) -> (K, CowValueGuard<V>)
where
K: Hash,
S: BuildHasher,
V: Clone,
{
self.table.rcu(|t| {
t.insert_entry(
hash,
(key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(self.hash_builder),
);
});
(key, CowValueGuard::new(value))
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_with_hasher<H>(self, hash: u64, key: K, value: V, hasher: H) -> (K, Arc<V>)
where
H: Fn(&K) -> u64,
{
let value = Arc::new(ArcSwap::new(Arc::new(value)));
self.table
.rcu(|t| {
let r = t.insert_entry(hash, (key.clone(), value.clone()), |x| hasher(&x.0));
(r.0.clone(), r.1.load_full())
})
.inner
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_with_hasher_mut<H>(
self,
hash: u64,
key: K,
value: V,
hasher: H,
) -> (K, CowValueGuard<V>)
where
H: Fn(&K) -> u64,
V: Clone,
{
let value = Arc::new(ArcSwap::new(Arc::new(value)));
self.table
.rcu(|t| {
let r = t.insert_entry(hash, (key.clone(), value.clone()), |x| hasher(&x.0));
(r.0.clone(), CowValueGuard::new(r.1.clone()))
})
.inner
}
#[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_hash::<K, S>(self.hash_builder, &key);
let value = Arc::new(ArcSwap::new(Arc::new(value)));
let elem = self
.table
.rcu(|t| {
t.insert(
hash,
(key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(self.hash_builder),
)
})
.inner;
RawOccupiedEntryMut {
hash,
elem,
table: self.table,
hash_builder: self.hash_builder,
}
}
}
impl<K: Clone, 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 + Clone, V: Debug + Clone, 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 + Clone, V: Debug + Clone, 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: Clone, 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()
}
}
pub enum Entry<K: Clone, V, S, A = Global>
where
A: Allocator + Clone,
{
Occupied(OccupiedEntry<K, V, S, A>),
Vacant(VacantEntry<K, V, S, A>),
}
pub struct OccupiedEntry<K: Clone, V, S = DefaultHashBuilder, A: Allocator + Clone = Global> {
hash: u64,
key: Option<K>,
elem: RawTableGuard<(K, Arc<ArcSwap<V>>), A, Bucket<(K, Arc<ArcSwap<V>>)>>,
table: CowHashMap<K, V, S, A>,
}
unsafe impl<K: Clone, V, S, A> Send for OccupiedEntry<K, V, S, A>
where
K: Send,
V: Send,
S: Send,
A: Send + Allocator + Clone,
{
}
unsafe impl<K: Clone, V, S, A> Sync for OccupiedEntry<K, V, S, A>
where
K: Sync,
V: Sync,
S: Sync,
A: Sync + Allocator + Clone,
{
}
pub struct VacantEntry<K: Clone, V, S = DefaultHashBuilder, A: Allocator + Clone = Global> {
hash: u64,
key: K,
table: CowHashMap<K, V, S, A>,
}
impl<K: Debug + Clone, 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: Clone, 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: Clone, Q, V, S, A> Debug for EntryRef<'_, '_, K, Q, V, S, A>
where
K: Borrow<Q>,
Q: Debug + ?Sized,
V: Debug,
A: Allocator + Clone,
{
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: Clone, Q: ?Sized, V, S, A: Allocator + Clone = Global> {
hash: u64,
key: Option<KeyOrRef<'b, K, Q>>,
elem: RawTableGuard<(K, Arc<ArcSwap<V>>), A, Bucket<(K, Arc<ArcSwap<V>>)>>,
table: &'a CowHashMap<K, V, S, A>,
}
unsafe impl<'a, 'b, 'c, K: Clone, 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, 'c, K: Clone, 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: Clone, Q, V, S, A> Debug for OccupiedEntryRef<'_, '_, K, Q, V, S, A>
where
K: Borrow<Q>,
Q: Debug + ?Sized,
V: Debug,
A: Allocator + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedEntryRef")
.field("key", &self.key().borrow())
.field("value", &self.get())
.finish()
}
}
pub struct VacantEntryRef<'a, 'b, K: Clone, Q: ?Sized, V, S, A: Allocator + Clone = Global> {
hash: u64,
key: KeyOrRef<'b, K, Q>,
table: &'a CowHashMap<K, V, S, A>,
}
impl<K: Clone, Q, V, S, A> Debug for VacantEntryRef<'_, '_, K, Q, V, S, A>
where
K: Borrow<Q>,
Q: Debug + ?Sized,
A: Allocator + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
}
}
pub struct OccupiedError<K: Clone, V, S, A: Allocator + Clone = Global> {
pub entry: OccupiedEntry<K, V, S, A>,
pub value: V,
}
impl<K: Clone, V, S, A: Allocator + Clone> IntoIterator for &CowHashMap<K, V, S, A> {
type Item = (K, Arc<V>);
type IntoIter = Iter<K, V, A>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> Iter<K, V, A> {
self.iter()
}
}
impl<K: Clone, V, S, A: Allocator + Clone> IntoIterator for &mut CowHashMap<K, V, S, A>
where
V: Clone,
{
type Item = (K, CowValueGuard<V>);
type IntoIter = IterMut<K, V, A>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> IterMut<K, V, A> {
self.iter_mut()
}
}
impl<K: Clone, V, S, A: Allocator + Clone> IntoIterator for CowHashMap<K, V, S, A> {
type Item = (K, Arc<V>);
type IntoIter = IntoIter<K, V, A>;
#[cfg_attr(feature = "inline-more", inline)]
fn into_iter(self) -> IntoIter<K, V, A> {
IntoIter {
inner: CowRawIntoIter {
iter: unsafe { self.table.iter() },
marker: PhantomData,
},
}
}
}
impl<K: Clone, V, A> Iterator for Iter<K, V, A>
where
A: Allocator + Clone,
{
type Item = (K, Arc<V>);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(K, Arc<V>)> {
match self.inner.next() {
Some(x) => unsafe {
let r = x.as_ref();
Some((r.0.clone(), r.1.load_full()))
},
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K: Clone, V, A> ExactSizeIterator for Iter<K, V, A>
where
A: Allocator + Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K: Clone, V, A: Allocator + Clone> FusedIterator for Iter<K, V, A> {}
impl<'a, K: Clone, V, A> Iterator for IterMut<K, V, A>
where
A: Allocator + Clone,
V: Clone,
{
type Item = (K, CowValueGuard<V>);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(K, CowValueGuard<V>)> {
match self.inner.next() {
Some(x) => unsafe {
let r = x.as_mut();
Some((r.0.clone(), CowValueGuard::new(r.1.clone())))
},
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K: Clone, V, A> ExactSizeIterator for IterMut<K, V, A>
where
A: Allocator + Clone,
V: Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K: Clone, V, A> FusedIterator for IterMut<K, V, A>
where
A: Allocator + Clone,
V: Clone,
{
}
impl<K, V, A> fmt::Debug for IterMut<K, V, A>
where
K: fmt::Debug + Clone,
V: fmt::Debug + Clone,
A: Allocator + Clone,
V: Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<K: Clone, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
type Item = (K, Arc<V>);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(K, Arc<V>)> {
match self.inner.next() {
Some(x) => unsafe {
let r = x.as_mut();
Some((r.0.clone(), r.1.load_full()))
},
None => None,
}
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K: Clone, 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: Clone, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
impl<K: Debug + Clone, V: Debug + Clone, 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: Clone, V, A: Allocator + Clone> Iterator for Keys<K, V, A> {
type Item = K;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<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()
}
#[cfg_attr(feature = "inline-more", inline)]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.inner.fold(init, |acc, (k, _)| f(acc, k))
}
}
impl<K: Clone, V, A: Allocator + Clone> ExactSizeIterator for Keys<K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K: Clone, V, A: Allocator + Clone> FusedIterator for Keys<K, V, A> {}
impl<K: Clone, V, A: Allocator + Clone> Iterator for Values<K, V, A> {
type Item = Arc<V>;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<Arc<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: Clone, V, A: Allocator + Clone> ExactSizeIterator for Values<K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K: Clone, V, A: Allocator + Clone> FusedIterator for Values<K, V, A> {}
impl<K: Clone, V, A: Allocator + Clone> Iterator for ValuesMut<K, V, A>
where
V: Clone,
{
type Item = CowValueGuard<V>;
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<CowValueGuard<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: Clone, V, A: Allocator + Clone> ExactSizeIterator for ValuesMut<K, V, A>
where
V: Clone,
{
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K: Clone, V, A: Allocator + Clone> FusedIterator for ValuesMut<K, V, A> where V: Clone {}
impl<K: Clone, V: Debug + Clone, A: Allocator + Clone> fmt::Debug for ValuesMut<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.inner.iter().map(|(_, val)| val))
.finish()
}
}
impl<'a, K: Clone, V, A: Allocator + Clone> Iterator for Drain<'a, K, V, A> {
type Item = (K, Arc<V>);
#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<(K, Arc<V>)> {
self.inner.inner.next().map(|(k, v)| (k, v.load_full()))
}
#[cfg_attr(feature = "inline-more", inline)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, K: Clone, V, A: Allocator + Clone> ExactSizeIterator for Drain<'a, K, V, A> {
#[cfg_attr(feature = "inline-more", inline)]
fn len(&self) -> usize {
self.inner.len()
}
}
impl<'a, K: Clone, V, A: Allocator + Clone> FusedIterator for Drain<'a, K, V, A> {}
impl<'a, K: Clone, V, A> fmt::Debug for Drain<'a, 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: Clone, V, S, A: Allocator + Clone> Entry<K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(self, value: V) -> OccupiedEntry<K, V, S, A>
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(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) -> Arc<V>
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
Entry::Vacant(entry) => entry.insert(default),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_mut(self, default: V) -> CowValueGuard<V>
where
K: Hash,
S: BuildHasher,
V: Clone,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert_mut(default),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> Arc<V>
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
Entry::Vacant(entry) => entry.insert(default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_mut<F: FnOnce() -> V>(self, default: F) -> CowValueGuard<V>
where
K: Hash,
S: BuildHasher,
V: Clone,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert_mut(default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> Arc<V>
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
Entry::Vacant(entry) => {
let value = default(entry.key());
entry.insert(value)
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_key_mut<F: FnOnce(&K) -> V>(self, default: F) -> CowValueGuard<V>
where
K: Hash,
S: BuildHasher,
V: Clone,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let value = default(entry.key());
entry.insert_mut(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: Fn(&mut V),
V: Clone,
{
match self {
Entry::Occupied(entry) => {
let v = unsafe { &entry.elem.as_ref().1.clone() };
v.rcu(|v| {
let mut v = v.deref().clone();
f(&mut v);
v
});
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: Fn(&K, &V) -> Option<V>,
K: Equivalent<K>,
{
match self {
Entry::Occupied(entry) => entry.replace_entry_with(f),
Entry::Vacant(_) => self,
}
}
}
impl<'a, K: Clone, V: Default + Clone, S, A: Allocator + Clone> Entry<K, V, S, A> {
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_default(self) -> Arc<V>
where
K: Hash,
S: BuildHasher,
{
match self {
Entry::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
Entry::Vacant(entry) => entry.insert(Default::default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_default_mut(self) -> CowValueGuard<V>
where
K: Hash,
S: BuildHasher,
V: Clone,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert_mut(Default::default()),
}
}
}
impl<'a, 'b, K: Clone, V, S, A: Allocator + Clone> OccupiedEntry<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, Arc<V>)
where
K: Equivalent<K>,
{
self.table
.table
.rcu(|t| unsafe {
let what = self.elem.as_ref();
let elem = t.find(self.hash, equivalent_key(&what.0));
if let Some(elem) = elem {
t.remove(elem);
}
(what.0.clone(), what.1.load_full())
})
.inner
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> Arc<V> {
let ret = unsafe { &self.elem.as_ref().1 };
ret.load_full()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut(&self) -> CowValueGuard<V>
where
V: Clone,
{
let ret = unsafe { &self.elem.as_mut().1 };
CowValueGuard::new(ret.clone())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_mut(self) -> CowValueGuard<V>
where
V: Clone,
{
let ret = unsafe { &self.elem.as_ref().1 };
CowValueGuard::new(ret.clone())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&self, value: V) -> Arc<V> {
unsafe {
let mut ret = self.elem.inner.as_ref().1.load_full();
let value = Arc::new(value);
self.elem.as_ref().1.rcu(|v| {
ret = v.clone();
value.clone()
});
ret
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove(self) -> Arc<V>
where
K: Equivalent<K>,
{
self.remove_entry().1
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry(self, value: V) -> (K, Arc<V>) {
let entry = unsafe { self.elem.as_mut() };
let value = Arc::new(ArcSwap::new(Arc::new(value)));
let old_key = mem::replace(&mut entry.0, self.key.unwrap());
let old_value = mem::replace(&mut entry.1, value);
(old_key, old_value.load_full())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry_mut(self, value: V) -> (K, CowValueGuard<V>)
where
V: Clone,
{
let entry = unsafe { self.elem.as_mut() };
let value = Arc::new(ArcSwap::new(Arc::new(value)));
let old_key = mem::replace(&mut entry.0, self.key.unwrap());
let old_value = mem::replace(&mut entry.1, value);
(old_key, CowValueGuard::new(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<K, V, S, A>
where
F: Fn(&K, &V) -> Option<V>,
K: Equivalent<K>,
{
let elem = unsafe { self.elem.inner.as_ref() };
let key = &elem.0;
let value = elem.1.load_full();
loop {
match f(&key, &value) {
Some(new) => {
let prev = elem.1.compare_and_swap(&value, Arc::new(new));
let swapped = ptr_eq(&value, &*prev);
if swapped {
return Entry::Occupied(self);
}
}
None => {
self.table.table.rcu(|t| unsafe {
let key = key.clone();
let elem = t.find(self.hash, equivalent_key(&key));
if let Some(elem) = elem {
t.remove(elem);
}
});
return Entry::Vacant(VacantEntry {
hash: self.hash,
key: key.clone(),
table: self.table,
});
}
}
}
}
}
impl<'a, K: Clone, V, S, A: Allocator + Clone> VacantEntry<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) -> Arc<V>
where
K: Hash,
S: BuildHasher,
{
let value = Arc::new(ArcSwap::new(Arc::new(value)));
self.table
.table
.rcu(|t| {
let r = t.insert_entry(
self.hash,
(self.key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.table.hash_builder),
);
r.1.load_full()
})
.inner
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_mut(self, value: V) -> CowValueGuard<V>
where
K: Hash,
S: BuildHasher,
V: Clone,
{
let value = Arc::new(ArcSwap::new(Arc::new(value)));
self.table
.table
.rcu(|t| {
let r = t.insert_entry(
self.hash,
(self.key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.table.hash_builder),
);
CowValueGuard::new(r.1.clone())
})
.inner
}
#[cfg_attr(feature = "inline-more", inline)]
pub(crate) fn insert_entry(self, value: V) -> OccupiedEntry<K, V, S, A>
where
K: Hash,
S: BuildHasher,
{
let value = Arc::new(ArcSwap::new(Arc::new(value)));
let elem = self.table.table.rcu(|t| {
t.insert(
self.hash,
(self.key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.table.hash_builder),
)
});
OccupiedEntry {
hash: self.hash,
key: None,
elem,
table: self.table,
}
}
}
impl<'a, 'b, K: Clone, 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(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) -> Arc<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
EntryRef::Vacant(entry) => entry.insert(default),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_mut(self, default: V) -> CowValueGuard<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
V: Clone,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => entry.insert_mut(default),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> Arc<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
EntryRef::Vacant(entry) => entry.insert(default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_mut<F: FnOnce() -> V>(self, default: F) -> CowValueGuard<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
V: Clone,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => entry.insert_mut(default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> Arc<V>
where
K: Hash + Borrow<Q> + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
EntryRef::Vacant(entry) => {
let value = default(entry.key.as_ref());
entry.insert(value)
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_insert_with_key_mut<F: FnOnce(&Q) -> V>(self, default: F) -> CowValueGuard<V>
where
K: Hash + Borrow<Q> + From<&'b Q>,
S: BuildHasher,
V: Clone,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => {
let value = default(entry.key.as_ref());
entry.insert_mut(value)
}
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn key(&self) -> &Q
where
K: Borrow<Q>,
{
match *self {
EntryRef::Occupied(ref entry) => entry.key().borrow(),
EntryRef::Vacant(ref entry) => entry.key(),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn and_modify<F>(self, f: F) -> Self
where
F: Fn(&mut V),
V: Clone,
{
match self {
EntryRef::Occupied(entry) => {
let v = unsafe { &entry.elem.as_ref().1 };
v.rcu(|v| {
let mut v = v.deref().clone();
f(&mut v);
v
});
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: Fn(&K, &V) -> Option<V>,
K: Equivalent<K>,
{
match self {
EntryRef::Occupied(entry) => entry.replace_entry_with(f),
EntryRef::Vacant(_) => self,
}
}
}
impl<'a, 'b, K: Clone, Q: ?Sized, V: Default + Clone, S, A: Allocator + Clone>
EntryRef<'a, 'b, K, Q, V, S, A>
{
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_default(self) -> Arc<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
match self {
EntryRef::Occupied(entry) => unsafe { entry.elem.as_ref() }.1.load_full(),
EntryRef::Vacant(entry) => entry.insert(Default::default()),
}
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn or_default_mut(self) -> CowValueGuard<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
V: Clone,
{
match self {
EntryRef::Occupied(entry) => entry.into_mut(),
EntryRef::Vacant(entry) => entry.insert_mut(Default::default()),
}
}
}
impl<'a, 'b, K: Clone, 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) -> &K {
unsafe { &self.elem.as_ref().0 }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove_entry(self) -> (K, Arc<V>)
where
K: Equivalent<K>,
{
let ret = self.table.table.rcu(|t| unsafe {
let elem = t.find(self.hash, equivalent_key(self.key()));
if let Some(elem) = elem {
t.remove(elem);
}
self.elem.as_ref()
});
(ret.inner.0.clone(), ret.inner.1.load_full())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get(&self) -> Arc<V> {
let ret = unsafe { &self.elem.as_ref().1 };
ret.load_full()
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn get_mut(&self) -> CowValueGuard<V>
where
V: Clone,
{
let ret = unsafe { &self.elem.as_ref().1 };
CowValueGuard::new(ret.clone())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn into_mut(self) -> CowValueGuard<V>
where
V: Clone,
{
let ret = unsafe { &self.elem.as_ref().1 };
CowValueGuard::new(ret.clone())
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert(&self, value: V) -> Arc<V> {
unsafe { self.elem.inner.as_ref().1.swap(Arc::new(value)) }
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn remove(self) -> Arc<V>
where
K: Equivalent<K>,
{
self.remove_entry().1
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn replace_entry(self, value: V) -> (K, Arc<V>)
where
K: From<&'b Q>,
{
let val = unsafe {
let mut ret = self.elem.inner.as_ref().1.load_full();
let value = Arc::new(value);
self.elem.as_ref().1.rcu(|v| {
ret = v.clone();
value.clone()
});
ret
};
(self.key.unwrap().into_owned(), val)
}
#[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: Fn(&K, &V) -> Option<V>,
K: Equivalent<K>,
{
let elem = unsafe { self.elem.as_ref() };
let key = &elem.0;
let value = elem.1.load_full();
loop {
match f(&key, &value) {
Some(new) => {
let prev = elem.1.compare_and_swap(&value, Arc::new(new));
let swapped = ptr_eq(&value, &*prev);
if swapped {
return EntryRef::Occupied(self);
}
}
None => {
self.table.table.rcu(|t| {
let elem = t.find(self.hash, equivalent_key(self.key()));
if let Some(elem) = elem {
unsafe {
t.remove(elem);
}
}
});
return EntryRef::Vacant(VacantEntryRef {
hash: self.hash,
key: KeyOrRef::Owned(key.clone()),
table: self.table,
});
}
}
}
}
}
impl<'a, 'b, K: Clone, 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) -> Arc<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
{
let table = &self.table.table;
let key = self.key.into_owned();
let value = Arc::new(ArcSwap::new(Arc::new(value)));
table
.rcu(|t| {
let r = t.insert_entry(
self.hash,
(key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.table.hash_builder),
);
r.1.load_full()
})
.inner
}
#[cfg_attr(feature = "inline-more", inline)]
pub fn insert_mut(self, value: V) -> CowValueGuard<V>
where
K: Hash + From<&'b Q>,
S: BuildHasher,
V: Clone,
{
let table = &self.table.table;
let key = self.key.into_owned();
let value = Arc::new(ArcSwap::new(Arc::new(value)));
table
.rcu(|t| {
let r = t.insert_entry(
self.hash,
(key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.table.hash_builder),
);
CowValueGuard::new(r.1.clone())
})
.inner
}
#[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 key = self.key.into_owned();
let value = Arc::new(ArcSwap::new(Arc::new(value)));
let elem = self.table.table.rcu(|t| {
t.insert(
self.hash,
(key.clone(), value.clone()),
make_hasher::<_, Arc<ArcSwap<V>>, S>(&self.table.hash_builder),
)
});
OccupiedEntryRef {
hash: self.hash,
key: None,
elem,
table: self.table,
}
}
}
impl<K: Clone, V, S, A> FromIterator<(K, V)> for CowHashMap<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 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: Clone, V, S, A> Extend<(K, V)> for CowHashMap<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: Clone, V, S, A> Extend<(&'a K, &'a V)> for CowHashMap<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: Clone, V, S, A> Extend<&'a (K, V)> for CowHashMap<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);
}
}
#[cfg(test)]
mod test_map {
use super::CowHashMap;
use super::DefaultHashBuilder;
use super::Entry::{Occupied, Vacant};
use super::EntryRef;
use alloc::string::ToString;
use alloc::sync::Arc;
use allocator_api2::alloc::{AllocError, Allocator, Global};
use core::alloc::Layout;
use core::ptr::NonNull;
use core::sync::atomic::{AtomicI8, Ordering};
use rand::{rngs::SmallRng, Rng, SeedableRng};
use std::borrow::ToOwned;
use std::cell::RefCell;
use std::vec::Vec;
#[test]
fn test_zero_capacities() {
type HM = CowHashMap<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 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 m = HM::new();
m.reserve(0);
assert_eq!(m.capacity(), 0);
}
#[test]
fn test_create_capacity_zero() {
let m = CowHashMap::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 m = CowHashMap::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 m = CowHashMap::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 m = CowHashMap::new();
let mut m2 = CowHashMap::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>> = const { 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 m = CowHashMap::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 hm = CowHashMap::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());
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 1);
}
});
{
let mut half = hm.into_iter().take(50);
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 1);
}
});
for _ in half.by_ref() {}
};
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 0);
}
});
}
#[test]
fn test_map_drop() {
DROP_VECTOR.with(|v| {
*v.borrow_mut() = vec![0; 200];
});
let hm = {
let hm = CowHashMap::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());
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 1);
}
});
for _ in hm.iter() {}
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 1);
}
});
drop(hm);
DROP_VECTOR.with(|v| {
for i in 0..200 {
assert_eq!(v.borrow()[i], 0);
}
});
}
#[test]
fn test_empty_remove() {
let m: CowHashMap<i32, bool> = CowHashMap::new();
assert_eq!(m.remove(&0), None);
}
#[test]
fn test_empty_entry() {
let m: CowHashMap<i32, bool> = CowHashMap::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 m: CowHashMap<std::string::String, bool> = CowHashMap::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 m: CowHashMap<i32, bool> = CowHashMap::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 = CowHashMap::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);
let j = Arc::new(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_fast(&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_fast(i, i).is_none());
}
for i in (1..1001).rev() {
assert!(m.remove_fast(&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 m = CowHashMap::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(mut x) => *x = new,
}
assert_eq!(m.get(&5), Some(Arc::new(new)));
}
#[test]
fn test_insert_overwrite() {
let m = CowHashMap::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 m = CowHashMap::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 m = CowHashMap::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 map = CowHashMap::new();
let (k1, v1) = map.insert_unique_unchecked(10, 11);
assert_eq!((10, 11), (*k1, *v1));
let (k2, v2) = map.insert_unique_unchecked(20, 21);
assert_eq!((20, 21), (*k2, *v2));
assert_eq!(Some(Arc::new(11)), map.get(&10));
assert_eq!(Some(Arc::new(21)), map.get(&20));
assert_eq!(None, map.get(&30));
}
#[test]
fn test_is_empty() {
let m = CowHashMap::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 m = CowHashMap::new();
m.insert(1, 2);
assert_eq!(m.remove(&1), Some(Arc::new(2)));
assert_eq!(m.remove(&1), None);
}
#[test]
fn test_remove_entry() {
let m = CowHashMap::new();
m.insert(1, 2);
assert_eq!(m.remove_entry(&1), Some((1, Arc::new(2))));
assert_eq!(m.remove(&1), None);
}
#[test]
fn test_iterate() {
let m = CowHashMap::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: CowHashMap<_, _> = vec.into_iter().collect();
let keys: Vec<_> = map.keys().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: CowHashMap<_, _> = vec.into_iter().collect();
let values: Vec<_> = map.values().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&Arc::new('a')));
assert!(values.contains(&Arc::new('b')));
assert!(values.contains(&Arc::new('c')));
}
#[test]
fn test_values_mut() {
let vec = vec![(1, 1), (2, 2), (3, 3)];
let map: CowHashMap<_, _> = vec.into_iter().collect();
for mut value in map.values_mut() {
*value *= 2;
}
let values: Vec<_> = map.values().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&Arc::new(2)));
assert!(values.contains(&Arc::new(4)));
assert!(values.contains(&Arc::new(6)));
}
#[test]
fn test_into_keys() {
let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let map: CowHashMap<_, _> = 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: CowHashMap<_, _> = vec.into_iter().collect();
let values: Vec<_> = map.into_values().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&Arc::new('a')));
assert!(values.contains(&Arc::new('b')));
assert!(values.contains(&Arc::new('c')));
}
#[test]
fn test_find() {
let m = CowHashMap::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_show() {
let map = CowHashMap::new();
let empty: CowHashMap<i32, i32> = CowHashMap::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 m = CowHashMap::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 m = CowHashMap::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 m = CowHashMap::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(Arc::new(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(Arc::new(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(Arc::new(0)));
}
#[test]
fn test_from_iter() {
let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: CowHashMap<_, _> = xs.iter().copied().collect();
for &(k, v) in &xs {
assert_eq!(map.get(&k), Some(Arc::new(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: CowHashMap<_, _> = 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: CowHashMap<_, _> = 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 map: CowHashMap<_, _> = 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 map: CowHashMap<_, _> = 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_entry() {
let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
let map: CowHashMap<_, _> = xs.iter().copied().collect();
match map.entry(1) {
Vacant(_) => unreachable!(),
Occupied(view) => {
assert_eq!(*view.get(), 10);
assert_eq!(view.insert(100), Arc::new(10));
}
}
assert_eq!(map.get(&1).unwrap(), Arc::new(100));
assert_eq!(map.len(), 6);
match map.entry(2) {
Vacant(_) => unreachable!(),
Occupied(view) => {
let mut v = view.get_mut();
let new_v = (*v) * 10;
*v = new_v;
}
}
assert_eq!(map.get(&2).unwrap(), Arc::new(200));
assert_eq!(map.len(), 6);
match map.entry(3) {
Vacant(_) => unreachable!(),
Occupied(view) => {
assert_eq!(view.remove(), Arc::new(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(), Arc::new(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 map: CowHashMap<_, _> = xs.iter().cloned().collect();
match map.entry_ref("One") {
EntryRef::Vacant(_) => unreachable!(),
EntryRef::Occupied(view) => {
assert_eq!(view.get(), Arc::new(10));
assert_eq!(view.insert(100), Arc::new(10));
}
}
assert_eq!(map.get("One").unwrap(), Arc::new(100));
assert_eq!(map.len(), 6);
match map.entry_ref("Two") {
EntryRef::Vacant(_) => unreachable!(),
EntryRef::Occupied(view) => {
let mut v = view.get_mut();
let new_v = (*v) * 10;
*v = new_v;
}
}
assert_eq!(map.get("Two").unwrap(), Arc::new(200));
assert_eq!(map.len(), 6);
match map.entry_ref("Three") {
EntryRef::Vacant(_) => unreachable!(),
EntryRef::Occupied(view) => {
assert_eq!(view.remove(), Arc::new(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(), Arc::new(1000));
assert_eq!(map.len(), 6);
}
#[test]
fn test_entry_take_doesnt_corrupt() {
#![allow(deprecated)] fn check(m: &CowHashMap<i32, ()>) {
for k in m.keys() {
assert!(m.contains_key(&k), "{k} is in keys() but not in the map?");
}
}
let m = CowHashMap::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: &CowHashMap<std::string::String, ()>) {
for k in m.keys() {
assert!(m.contains_key(&k), "{k} is in keys() but not in the map?");
}
}
let m = CowHashMap::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]
#[allow(clippy::needless_borrow)]
fn test_extend_ref_kv_tuple() {
use std::ops::AddAssign;
let mut a = CowHashMap::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.get(&item).unwrap(), Arc::new(item));
}
}
#[test]
fn test_capacity_not_less_than_len() {
let a = CowHashMap::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 a = CowHashMap::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.get(key).unwrap(), Arc::new(value));
match a.entry(key) {
Vacant(_) => panic!(),
Occupied(e) => assert_eq!(key, *e.key()),
}
assert_eq!(a.len(), 1);
assert_eq!(a.get(key).unwrap(), Arc::new(value));
}
#[test]
fn test_occupied_entry_ref_key() {
let a = CowHashMap::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.get(key).unwrap(), Arc::new(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.get(key).unwrap(), Arc::new(value));
}
#[test]
fn test_vacant_entry_key() {
let a = CowHashMap::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.get(key).unwrap(), Arc::new(value));
}
#[test]
fn test_vacant_entry_ref_key() {
let a: CowHashMap<std::string::String, &str> = CowHashMap::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.get(key).unwrap(), Arc::new(value));
}
#[test]
fn test_occupied_entry_replace_entry_with() {
let a = CowHashMap::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(), Arc::new(new_value));
}
Vacant(_) => panic!(),
}
assert_eq!(a.get(key).unwrap(), Arc::new(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 a: CowHashMap<std::string::String, &str> = CowHashMap::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(), Arc::new(new_value));
}
EntryRef::Vacant(_) => panic!(),
}
assert_eq!(a.get(key).unwrap(), Arc::new(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 a = CowHashMap::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(), Arc::new(new_value));
}
Vacant(_) => panic!(),
}
assert_eq!(a.get(key).unwrap(), Arc::new(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 a = CowHashMap::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(), Arc::new(new_value));
}
EntryRef::Vacant(_) => panic!(),
}
assert_eq!(a.get(key).unwrap(), Arc::new(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_replace_entry_with_doesnt_corrupt() {
#![allow(deprecated)] fn check(m: &CowHashMap<i32, ()>) {
for k in m.keys() {
assert!(m.contains_key(&k), "{k} is in keys() but not in the map?");
}
}
let m = CowHashMap::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: &CowHashMap<std::string::String, ()>) {
for k in m.keys() {
assert!(m.contains_key(&k), "{k} is in keys() but not in the map?");
}
}
let m = CowHashMap::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 map: CowHashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
map.retain(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 50);
assert_eq!(map.get(&2).unwrap(), Arc::new(20));
assert_eq!(map.get(&4).unwrap(), Arc::new(40));
assert_eq!(map.get(&6).unwrap(), Arc::new(60));
}
#[test]
#[cfg_attr(miri, ignore)] fn test_try_reserve() {
use crate::TryReserveError::{AllocError, CapacityOverflow};
const MAX_ISIZE: usize = isize::MAX as usize;
let empty_bytes: CowHashMap<u8, u8> = CowHashMap::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 empty_bytes2: CowHashMap<u8, u8> = CowHashMap::new();
let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
let empty_bytes3: CowHashMap<u8, u8> = CowHashMap::new();
let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
}
}
#[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 = CowHashMap::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_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).0;
removed.push(t);
left -= 1;
} else {
assert!(removed.contains(&(i, 2 * i)), "{i} not in {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]
#[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 map1 = CowHashMap::new();
map1.insert(1, DISARMED);
map1.insert(2, DISARMED);
map1.insert(3, DISARMED);
map1.insert(4, DISARMED);
let mut map2 = CowHashMap::new();
map2.insert(1, DISARMED);
map2.insert(2, ARMED);
map2.insert(3, DISARMED);
map2.insert(4, DISARMED);
map2.clone_from(&map1);
}
struct MyAllocInner {
drop_count: Arc<AtomicI8>,
}
#[derive(Clone)]
struct MyAlloc {
_inner: Arc<MyAllocInner>,
}
impl MyAlloc {
fn new(drop_count: Arc<AtomicI8>) -> Self {
MyAlloc {
_inner: Arc::new(MyAllocInner { drop_count }),
}
}
}
impl Drop for MyAllocInner {
fn drop(&mut self) {
println!("MyAlloc freed.");
self.drop_count.fetch_sub(1, Ordering::SeqCst);
}
}
unsafe impl Allocator for MyAlloc {
fn allocate(&self, layout: Layout) -> std::result::Result<NonNull<[u8]>, AllocError> {
let g = Global;
g.allocate(layout)
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
let g = Global;
g.deallocate(ptr, layout)
}
}
#[test]
fn test_hashmap_into_iter_bug() {
let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
{
let map = CowHashMap::with_capacity_in(10, MyAlloc::new(dropped.clone()));
for i in 0..10 {
map.entry(i).or_insert_with(|| "i".to_string());
}
for (k, v) in map {
println!("{}, {}", k, v);
}
}
assert_eq!(dropped.load(Ordering::SeqCst), 0);
}
#[allow(dead_code)]
#[derive(Debug)]
struct CheckedCloneDrop<T> {
panic_in_clone: bool,
panic_in_drop: bool,
dropped: bool,
data: T,
}
impl<T> CheckedCloneDrop<T> {
#[allow(dead_code)]
fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self {
CheckedCloneDrop {
panic_in_clone,
panic_in_drop,
dropped: false,
data,
}
}
}
impl<T: Clone> Clone for CheckedCloneDrop<T> {
fn clone(&self) -> Self {
if self.panic_in_clone {
panic!("panic in clone")
}
Self {
panic_in_clone: self.panic_in_clone,
panic_in_drop: self.panic_in_drop,
dropped: self.dropped,
data: self.data.clone(),
}
}
}
impl<T> Drop for CheckedCloneDrop<T> {
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;
}
}
}