use std::{
sync::atomic::{AtomicUsize, Ordering},
time::Duration,
};
use dashmap::DashSet;
use tokio::task::JoinHandle;
struct SendPtr<T>(*const T);
unsafe impl<T> Send for SendPtr<T> {}
unsafe impl<T> Sync for SendPtr<T> {}
impl<T> SendPtr<T> {
fn new(ptr: *const T) -> Self {
SendPtr(ptr)
}
fn get(&self) -> *const T {
self.0
}
}
pub struct ExpireSet<K> {
pub n: *const AtomicUsize,
pub cache: *const [DashSet<K>; 2],
pub timer: JoinHandle<()>,
}
unsafe impl<K: Send> Send for ExpireSet<K> {}
unsafe impl<K: Sync> Sync for ExpireSet<K> {}
impl<K: std::hash::Hash + Eq + Clone + Send + Sync + 'static> ExpireSet<K> {
pub fn new(expire: u64) -> Self {
let cache: *const [DashSet<K>; 2] = Box::leak(Box::new([DashSet::new(), DashSet::new()]));
let n: *const AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
let cache_ptr = SendPtr::new(cache);
let n_ptr = SendPtr::new(n);
let timer = tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(expire)).await;
unsafe {
let n = n_ptr.get();
let cache = cache_ptr.get();
let current = (*n).load(Ordering::Relaxed);
let next = (current + 1) % 2;
(*n).store(next, Ordering::Relaxed);
(*cache)[next].clear();
}
}
});
Self { n, cache, timer }
}
pub fn insert(&self, key: K) {
unsafe {
let idx = (*self.n).load(Ordering::Relaxed);
(*self.cache)[idx].insert(key);
}
}
pub fn contains(&self, key: &K) -> bool {
unsafe {
for set in (*self.cache).iter() {
if set.contains(key) {
return true;
}
}
}
false
}
}
impl<K> Drop for ExpireSet<K> {
fn drop(&mut self) {
self.timer.abort();
unsafe {
let _ = Box::from_raw(self.n as *mut AtomicUsize);
let _ = Box::from_raw(self.cache as *mut [DashSet<K>; 2]);
}
}
}