use std::fmt;
use std::hash::Hash;
use std::sync::Arc;
use ahash::AHashMap;
use arc_swap::ArcSwap;
pub struct AtomicMap<K, V>(ArcSwap<AHashMap<K, V>>);
impl<K, V> AtomicMap<K, V> {
pub fn new() -> Self {
Self(ArcSwap::new(Arc::new(AHashMap::new())))
}
#[inline]
pub fn load(&self) -> arc_swap::Guard<Arc<AHashMap<K, V>>> {
self.0.load()
}
pub fn store(&self, map: AHashMap<K, V>) {
self.0.store(Arc::new(map));
}
}
impl<K, V> AtomicMap<K, V>
where
K: Eq + Hash + Clone,
V: Clone,
{
pub fn rcu<F>(&self, mut f: F)
where
F: FnMut(&mut AHashMap<K, V>),
{
self.0.rcu(|m| {
let mut m = (**m).clone();
f(&mut m);
m
});
}
#[inline]
pub fn contains_key(&self, key: &K) -> bool {
self.0.load().contains_key(key)
}
#[inline]
pub fn get_cloned(&self, key: &K) -> Option<V> {
self.0.load().get(key).cloned()
}
pub fn insert(&self, key: K, value: V) {
self.rcu(|m| {
m.insert(key.clone(), value.clone());
});
}
pub fn remove(&self, key: &K) {
self.rcu(|m| {
m.remove(key);
});
}
#[inline]
pub fn len(&self) -> usize {
self.0.load().len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.0.load().is_empty()
}
}
impl<K, V> Default for AtomicMap<K, V> {
fn default() -> Self {
Self::new()
}
}
impl<K, V> fmt::Debug for AtomicMap<K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let len = self.0.load().len();
f.debug_struct("AtomicMap").field("len", &len).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn insert_get_remove() {
let map: AtomicMap<String, u32> = AtomicMap::new();
assert!(map.is_empty());
map.insert("a".into(), 1);
map.insert("b".into(), 2);
assert_eq!(map.len(), 2);
assert_eq!(map.get_cloned(&"a".to_string()), Some(1));
assert!(map.contains_key(&"b".to_string()));
map.remove(&"a".to_string());
assert_eq!(map.get_cloned(&"a".to_string()), None);
assert_eq!(map.len(), 1);
}
#[test]
fn rcu_concurrent_writers_no_lost_update() {
let map: Arc<AtomicMap<u32, u32>> = Arc::new(AtomicMap::new());
let mut handles = Vec::new();
for w in 0..8u32 {
let map = Arc::clone(&map);
handles.push(std::thread::spawn(move || {
for i in 0..100u32 {
let v = w * 100 + i;
map.insert(v, v);
}
}));
}
for h in handles {
h.join().unwrap();
}
assert_eq!(map.len(), 800);
}
#[test]
fn store_replaces_snapshot() {
let map: AtomicMap<u32, u32> = AtomicMap::new();
map.insert(1, 1);
let mut fresh = AHashMap::new();
fresh.insert(9, 9);
map.store(fresh);
assert_eq!(map.len(), 1);
assert_eq!(map.get_cloned(&9), Some(9));
assert_eq!(map.get_cloned(&1), None);
}
#[test]
fn debug_shows_len() {
let map: AtomicMap<u32, u32> = AtomicMap::new();
assert_eq!(format!("{map:?}"), "AtomicMap { len: 0 }");
}
}