use core::cell::Cell;
use core::fmt::Debug;
use core::num::Wrapping;
use rand_core::RngCore;
use crate::utils::sync::blocking::Mutex;
pub struct Dataver(Mutex<Cell<Wrapping<u32>>>);
impl Dataver {
pub fn new_rand<R: RngCore>(rand: &mut R) -> Self {
Self::new(rand.next_u32())
}
pub const fn new(initial: u32) -> Self {
Self(Mutex::new(Cell::new(Wrapping(initial))))
}
pub fn get(&self) -> u32 {
self.0.lock(|state| state.get().0)
}
pub fn changed(&self) -> u32 {
self.0.lock(|state| {
state.set(state.get() + Wrapping(1));
state.get().0
})
}
}
impl Clone for Dataver {
fn clone(&self) -> Self {
Self(Mutex::new(Cell::new(Wrapping(self.get()))))
}
}
impl Debug for Dataver {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.lock(|state| write!(f, "Dataver({})", state.get()))
}
}
#[cfg(feature = "defmt")]
impl defmt::Format for Dataver {
fn format(&self, fmt: defmt::Formatter) {
self.0
.lock(|state| defmt::write!(fmt, "Dataver({})", state.get().0))
}
}