Skip to content

Instantly share code, notes, and snippets.

@polypus74
Created July 3, 2018 14:38
Show Gist options
  • Save polypus74/eabc7bb00873e6b90abe230f9e632989 to your computer and use it in GitHub Desktop.
Save polypus74/eabc7bb00873e6b90abe230f9e632989 to your computer and use it in GitHub Desktop.
atomic enum in rust
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
pub enum RunFlagState {
Running = 0,
Paused = 1,
Cancelled = 2,
}
// TODO: is there some mechanism to automate this (nightly)?
impl From<usize> for RunFlagState {
fn from(val: usize) -> Self {
use self::RunFlagState::*;
match val {
0 => Running,
1 => Paused,
2 => Cancelled,
_ => unreachable!(),
}
}
}
#[derive(Clone)]
pub struct RunFlag {
flag: Arc<AtomicUsize>,
}
impl RunFlag {
pub fn new(state: RunFlagState) -> Self {
RunFlag {
flag: Arc::new(AtomicUsize::new(state as usize)),
}
}
pub fn cancel(&self) {
self.set_state(RunFlagState::Cancelled)
}
pub fn pause(&self) {
self.set_state(RunFlagState::Paused)
}
pub fn run(&self) {
self.set_state(RunFlagState::Running)
}
#[inline]
pub fn get_state(&self) -> RunFlagState {
self.flag.load(Ordering::SeqCst).into()
}
fn set_state(&self, state: RunFlagState) {
self.flag.store(state as usize, Ordering::SeqCst)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment