use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use tracing::debug;
pub use zaino_common::status::{Status, StatusType};
#[derive(Debug, Clone)]
pub struct AtomicStatus {
inner: Arc<AtomicUsize>,
}
impl AtomicStatus {
pub fn new(status: StatusType) -> Self {
Self {
inner: Arc::new(AtomicUsize::new(status.into())),
}
}
pub fn load(&self) -> StatusType {
StatusType::from(self.inner.load(Ordering::SeqCst))
}
pub fn store(&self, status: StatusType) {
self.inner.store(status.into(), Ordering::SeqCst);
}
}
impl Status for AtomicStatus {
fn status(&self) -> StatusType {
self.load()
}
}
#[derive(Debug, Clone)]
pub struct NamedAtomicStatus {
name: &'static str,
inner: Arc<AtomicUsize>,
}
impl NamedAtomicStatus {
pub fn new(name: &'static str, status: StatusType) -> Self {
debug!(component = name, status = %status, "[STATUS] initial");
Self {
name,
inner: Arc::new(AtomicUsize::new(status.into())),
}
}
pub fn name(&self) -> &'static str {
self.name
}
pub fn load(&self) -> StatusType {
StatusType::from(self.inner.load(Ordering::SeqCst))
}
pub fn store(&self, status: StatusType) {
let old = self.load();
if old != status {
debug!(
component = self.name,
from = %old,
to = %status,
"[STATUS] transition"
);
}
self.inner.store(status.into(), Ordering::SeqCst);
}
}
impl Status for NamedAtomicStatus {
fn status(&self) -> StatusType {
self.load()
}
}