use std::{
hash::{Hash, Hasher},
mem,
sync::{
atomic::{AtomicU64, Ordering},
RwLock,
},
task::Waker,
};
#[derive(Debug)]
pub struct ObservableState<T> {
value: T,
version: AtomicU64,
wakers: RwLock<Vec<Waker>>,
}
impl<T> ObservableState<T> {
pub(crate) fn new(value: T) -> Self {
Self { value, version: AtomicU64::new(1), wakers: Default::default() }
}
pub(crate) fn get(&self) -> &T {
&self.value
}
pub(crate) fn version(&self) -> u64 {
self.version.load(Ordering::Acquire)
}
pub(crate) fn add_waker(&self, waker: Waker) {
self.wakers.write().unwrap().push(waker);
}
pub(crate) fn set(&mut self, value: T) -> T {
let result = mem::replace(&mut self.value, value);
self.incr_version_and_wake();
result
}
pub(crate) fn set_if_not_eq(&mut self, value: T) -> Option<T>
where
T: PartialEq,
{
if self.value != value {
Some(self.set(value))
} else {
None
}
}
pub(crate) fn set_if_hash_not_eq(&mut self, value: T) -> Option<T>
where
T: Hash,
{
if hash(&self.value) != hash(&value) {
Some(self.set(value))
} else {
None
}
}
pub(crate) fn update(&mut self, f: impl FnOnce(&mut T)) {
f(&mut self.value);
self.incr_version_and_wake();
}
pub(crate) fn update_if(&mut self, f: impl FnOnce(&mut T) -> bool) {
if f(&mut self.value) {
self.incr_version_and_wake();
}
}
pub(crate) fn close(&self) {
self.version.store(0, Ordering::Release);
wake(mem::take(&mut *self.wakers.write().unwrap()));
}
fn incr_version_and_wake(&mut self) {
self.version.fetch_add(1, Ordering::Release);
wake(self.wakers.get_mut().unwrap().drain(..));
}
}
fn hash<T: Hash>(value: &T) -> u64 {
use std::collections::hash_map::DefaultHasher;
let mut hasher = DefaultHasher::new();
value.hash(&mut hasher);
hasher.finish()
}
fn wake<I>(wakers: I)
where
I: IntoIterator<Item = Waker>,
I::IntoIter: ExactSizeIterator,
{
let iter = wakers.into_iter();
#[cfg(feature = "tracing")]
{
let num_wakers = iter.len();
if num_wakers > 0 {
tracing::debug!("Waking up {num_wakers} waiting subscribers");
} else {
tracing::debug!("No wakers");
}
}
for waker in iter {
waker.wake();
}
}