wsio_core/atomic/
status.rs1use std::{
2 marker::PhantomData,
3 sync::atomic::{
4 AtomicU8,
5 Ordering,
6 },
7};
8
9use anyhow::{
10 Result,
11 anyhow,
12};
13
14pub struct AtomicStatus<T: Into<u8> + TryFrom<u8>> {
15 _marker: PhantomData<T>,
16 inner: AtomicU8,
17}
18
19impl<T: Into<u8> + TryFrom<u8>> AtomicStatus<T> {
20 pub fn new(status: T) -> Self {
21 Self {
22 _marker: PhantomData,
23 inner: AtomicU8::new(status.into()),
24 }
25 }
26
27 #[inline]
30 pub fn get(&self) -> T {
31 T::try_from(self.inner.load(Ordering::SeqCst)).ok().unwrap()
32 }
33
34 #[inline]
35 pub fn is(&self, status: T) -> bool {
36 self.inner.load(Ordering::SeqCst) == status.into()
37 }
38
39 #[inline]
40 pub fn store(&self, status: T) {
41 self.inner.store(status.into(), Ordering::SeqCst);
42 }
43
44 #[inline]
45 pub fn try_transition(&self, from: T, to: T) -> Result<()> {
46 self.inner
47 .compare_exchange(from.into(), to.into(), Ordering::SeqCst, Ordering::SeqCst)
48 .map(|_| ())
49 .map_err(|_| anyhow!("Failed to transition status"))
50 }
51}