use crate::lock::{SyncLock, SyncLockGuard};
use indexmap::map::{
IndexMap as Map, IntoIter as MapIntoIter, Iter as MapIter, IterMut as MapIterMut,
};
use serde::{Deserializer, Serialize, Serializer};
use std::borrow::Borrow;
use std::cell::UnsafeCell;
use std::fmt::{Debug, Display, Formatter};
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use super::entry::{Entry, Retired};
use super::snapshot::AtomicSnapshot;
pub struct SyncIndexMap<K: Eq + Hash, V> {
dirty: UnsafeCell<Map<K, Arc<Entry<V>>>>,
lock: SyncLock,
amended: AtomicBool,
read: AtomicSnapshot<Map<K, Arc<Entry<V>>>>,
retired: Retired<V>,
}
unsafe impl<K: Eq + Hash, V> Send for SyncIndexMap<K, V> {}
unsafe impl<K: Eq + Hash, V> Sync for SyncIndexMap<K, V> {}
impl<K, V> std::ops::Index<&K> for SyncIndexMap<K, V>
where
K: Eq + Hash + Clone,
{
type Output = V;
fn index(&self, index: &K) -> &Self::Output {
self.get(index).expect("key not found")
}
}
impl<K, V> SyncIndexMap<K, V>
where
K: Eq + Hash,
{
pub fn new_arc() -> Arc<Self> {
Arc::new(Self::new())
}
pub fn new() -> Self {
Self {
dirty: UnsafeCell::new(Map::new()),
lock: Default::default(),
amended: AtomicBool::new(false),
read: AtomicSnapshot::new(Map::new()),
retired: Retired::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
dirty: UnsafeCell::new(Map::with_capacity(capacity)),
lock: Default::default(),
amended: AtomicBool::new(false),
read: AtomicSnapshot::new(Map::with_capacity(capacity)),
retired: Retired::new(),
}
}
pub fn with_map(map: Map<K, V>) -> Self {
let dirty = map
.into_iter()
.map(|(k, v)| (k, Arc::new(Entry::new(v))))
.collect();
Self {
read: AtomicSnapshot::new(Map::new()),
dirty: UnsafeCell::new(dirty),
lock: Default::default(),
amended: AtomicBool::new(true),
retired: Retired::new(),
}
}
fn promote(&self)
where
K: Clone,
{
let dirty = unsafe { &*self.dirty.get() };
self.read.publish(dirty.clone());
self.amended.store(false, Ordering::Release);
}
pub fn insert(&self, k: K, v: V) -> Option<V>
where
K: Clone,
V: Clone,
{
let g = self.lock.lock();
let m = unsafe { &mut *self.dirty.get() };
if let Some(entry) = m.get(&k) {
let old = entry.swap(v);
let old_value = unsafe { (*old).clone() };
self.retired.push(old);
drop(g);
return Some(old_value);
}
m.insert(k, Arc::new(Entry::new(v)));
self.amended.store(true, Ordering::Release);
drop(g);
None
}
pub fn insert_mut(&mut self, k: K, v: V) -> Option<V>
where
K: Clone,
V: Clone,
{
self.insert(k, v)
}
pub fn remove(&self, k: &K) -> Option<V>
where
K: Clone,
V: Clone,
{
let g = self.lock.lock();
let m = unsafe { &mut *self.dirty.get() };
if let Some(entry) = m.swap_remove(k) {
let v = entry.load().clone();
self.promote();
drop(g);
return Some(v);
}
drop(g);
None
}
pub fn remove_mut(&mut self, k: &K) -> Option<V>
where
K: Clone,
V: Clone,
{
self.remove(k)
}
pub fn len(&self) -> usize {
if !self.amended.load(Ordering::Acquire) {
return self.read.load().len();
}
let g = self.lock.lock();
let r = unsafe { (&*self.dirty.get()).len() };
drop(g);
r
}
pub fn is_empty(&self) -> bool {
if !self.amended.load(Ordering::Acquire) {
return self.read.load().is_empty();
}
let g = self.lock.lock();
let r = unsafe { (&*self.dirty.get()).is_empty() };
drop(g);
r
}
pub fn clear(&self)
where
K: Clone,
{
let g = self.lock.lock();
unsafe { (&mut *self.dirty.get()).clear() };
self.promote();
drop(g);
}
pub fn clear_mut(&mut self)
where
K: Clone,
{
self.clear()
}
pub fn shrink_to_fit(&self) {
let g = self.lock.lock();
unsafe { (&mut *self.dirty.get()).shrink_to_fit() };
drop(g);
}
pub fn shrink_to_fit_mut(&mut self) {
unsafe { (&mut *self.dirty.get()).shrink_to_fit() }
}
pub fn from(map: Map<K, V>) -> Self
where
K: Eq + Hash,
{
let s = Self::with_map(map);
s
}
#[inline]
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
where
K: Borrow<Q> + Clone,
Q: Hash + Eq,
{
if let Some(entry) = self.read.load().get(k) {
return Some(entry.load());
}
if !self.amended.load(Ordering::Acquire) {
return None;
}
let g = self.lock.lock();
let found = unsafe { (&*self.dirty.get()).contains_key(k) };
if found {
self.promote();
}
drop(g);
if found {
self.read.load().get(k).map(|e| e.load())
} else {
None
}
}
#[inline]
pub fn get_mut(&self, k: &K) -> Option<HashMapRefMut<'_, K, V>>
where
K: Hash + Eq + Clone,
V: Clone,
{
let g = self.lock.lock();
let dirty = unsafe { &*self.dirty.get() };
let value = dirty.get(k)?.load().clone();
drop(g);
Some(HashMapRefMut {
k: k.clone(),
m: self,
value: Some(value),
})
}
#[inline]
pub fn contains_key(&self, x: &K) -> bool
where
K: PartialEq,
{
if self.read.load().contains_key(x) {
return true;
}
if !self.amended.load(Ordering::Acquire) {
return false;
}
let g = self.lock.lock();
let r = unsafe { (&*self.dirty.get()).contains_key(x) };
drop(g);
r
}
pub fn iter(&self) -> Iter<'_, K, V>
where
K: Clone,
{
let g = self.lock.lock();
self.promote();
drop(g);
Iter {
inner: self.read.load().iter(),
}
}
pub fn iter_mut(&self) -> IterMut<'_, K, V>
where
K: Clone,
V: Clone,
{
let m = unsafe { &mut *self.dirty.get() };
IterMut {
m: self,
_g: self.lock.lock(),
inner: Some(m.iter_mut()),
}
}
pub fn into_iter(self) -> MapIntoIter<K, V> {
self.into_inner().into_iter()
}
pub fn into_inner(self) -> Map<K, V> {
let dirty = self.dirty.into_inner();
dirty
.into_iter()
.map(|(k, entry)| (k, entry.take()))
.collect()
}
}
pub struct Iter<'a, K, V> {
inner: MapIter<'a, K, Arc<Entry<V>>>,
}
impl<'a, K, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(k, e)| (k, e.load()))
}
}
impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
fn len(&self) -> usize {
self.inner.len()
}
}
pub struct IterMut<'a, K: Eq + Hash + Clone, V: Clone> {
m: &'a SyncIndexMap<K, V>,
_g: SyncLockGuard<'a>,
inner: Option<MapIterMut<'a, K, Arc<Entry<V>>>>,
}
impl<'a, K: Eq + Hash + Clone, V: Clone> Drop for IterMut<'a, K, V> {
fn drop(&mut self) {
self.inner.take();
self.m.promote();
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<Self::Item> {
let (k, entry) = self.inner.as_mut().unwrap().next()?;
if Arc::get_mut(entry).is_none() {
let current = entry.load().clone();
*entry = Arc::new(Entry::new(current));
}
Some((k, Arc::get_mut(entry).unwrap().get_mut()))
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> ExactSizeIterator for IterMut<'a, K, V> {
fn len(&self) -> usize {
self.inner.as_ref().unwrap().len()
}
}
pub struct HashMapRefMut<'a, K: Eq + Hash + Clone, V: Clone> {
k: K,
m: &'a SyncIndexMap<K, V>,
value: Option<V>,
}
impl<'a, K: Eq + Hash + Clone, V: Clone> Drop for HashMapRefMut<'a, K, V> {
fn drop(&mut self) {
if let Some(v) = self.value.take() {
let g = self.m.lock.lock();
let dirty = unsafe { &mut *self.m.dirty.get() };
match dirty.get_mut(&self.k) {
Some(entry) => {
let old = entry.swap(v);
self.m.retired.push(old);
}
None => {
dirty.insert(self.k.clone(), Arc::new(Entry::new(v)));
self.m.amended.store(true, Ordering::Release);
}
}
drop(g);
}
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> Deref for HashMapRefMut<'_, K, V> {
type Target = V;
fn deref(&self) -> &Self::Target {
self.value.as_ref().unwrap()
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> DerefMut for HashMapRefMut<'_, K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.value.as_mut().unwrap()
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> Debug for HashMapRefMut<'_, K, V>
where
V: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.value.as_ref().unwrap().fmt(f)
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> Display for HashMapRefMut<'_, K, V>
where
V: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.value.as_ref().unwrap().fmt(f)
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> PartialEq<Self> for HashMapRefMut<'_, K, V>
where
V: Eq,
{
fn eq(&self, other: &Self) -> bool {
self.value
.as_ref()
.unwrap()
.eq(&other.value.as_ref().unwrap())
}
}
impl<'a, K: Eq + Hash + Clone, V: Clone> Eq for HashMapRefMut<'_, K, V> where V: Eq {}
impl<'a, K: Clone, V> IntoIterator for &'a SyncIndexMap<K, V>
where
K: Eq + Hash,
{
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<K, V> IntoIterator for SyncIndexMap<K, V>
where
K: Eq + Hash,
{
type Item = (K, V);
type IntoIter = MapIntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
self.into_iter()
}
}
impl<K: Eq + Hash, V> From<Map<K, V>> for SyncIndexMap<K, V> {
fn from(arg: Map<K, V>) -> Self {
Self::from(arg)
}
}
impl<K, V> serde::Serialize for SyncIndexMap<K, V>
where
K: Eq + Hash + Serialize,
V: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeMap;
let g = self.lock.lock();
let dirty = unsafe { &*self.dirty.get() };
let mut m = serializer.serialize_map(Some(dirty.len()))?;
for (k, e) in dirty.iter() {
m.serialize_entry(k, e.load())?;
}
drop(g);
m.end()
}
}
impl<'de, K, V> serde::Deserialize<'de> for SyncIndexMap<K, V>
where
K: Eq + Hash + serde::Deserialize<'de>,
V: serde::Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let m = Map::deserialize(deserializer)?;
Ok(Self::from(m))
}
}
impl<K, V> Debug for SyncIndexMap<K, V>
where
K: Eq + Hash + Debug,
V: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let g = self.lock.lock();
let r = unsafe { (&*self.dirty.get()).fmt(f) };
drop(g);
r
}
}
impl<K, V> Display for SyncIndexMap<K, V>
where
K: Eq + Hash + Display,
V: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
use std::fmt::Pointer;
let g = self.lock.lock();
let r = unsafe { (&*self.dirty.get()).fmt(f) };
drop(g);
r
}
}
impl<K: Clone + Eq + Hash, V: Clone> Clone for SyncIndexMap<K, V> {
fn clone(&self) -> Self {
let g = self.lock.lock();
let dirty = unsafe { &*self.dirty.get() };
let m = dirty
.iter()
.map(|(k, e)| (k.clone(), e.load().clone()))
.collect();
drop(g);
SyncIndexMap::from(m)
}
}
impl<K: Eq + Hash, V> Default for SyncIndexMap<K, V> {
fn default() -> Self {
SyncIndexMap::new()
}
}