use super::node::StmNode;
use kovan::Atomic;
use std::sync::Arc;
use std::sync::atomic::Ordering;
#[cfg(feature = "shuttle")]
use shuttle::sync::atomic::AtomicU64;
#[cfg(not(feature = "shuttle"))]
use std::sync::atomic::AtomicU64;
pub(crate) struct TVarInner<T: Send + Sync + 'static> {
pub(crate) version_lock: AtomicU64,
pub(crate) data: Atomic<StmNode<T>>,
}
impl<T: Send + Sync + 'static> TVarInner<T> {
fn new(val: T) -> Arc<Self> {
Arc::new(Self {
version_lock: AtomicU64::new(0),
data: Atomic::new(kovan::alloc_node(StmNode::new(val))),
})
}
#[inline]
pub(crate) fn load_version_lock(&self) -> (bool, u64) {
let val = self.version_lock.load(Ordering::Acquire);
(val & 1 == 1, val & !1)
}
}
impl<T: Send + Sync + 'static> Drop for TVarInner<T> {
fn drop(&mut self) {
let guard = kovan::pin();
let node = self.data.load(Ordering::Acquire, &guard);
if !node.is_null() {
unsafe { kovan::retire_node(node.as_raw()) };
}
}
}
pub struct TVar<T: Send + Sync + 'static>(pub(crate) Arc<TVarInner<T>>);
impl<T: Send + Sync + 'static> TVar<T> {
pub fn new(val: T) -> Self {
TVar(TVarInner::new(val))
}
}
unsafe impl<T: Send + Sync> Send for TVar<T> {}
unsafe impl<T: Send + Sync> Sync for TVar<T> {}