1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use super::message::*;
use crate::error::RuntimeError;

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct AliveFlag {
    flag: Arc<AtomicBool>,
}

impl AliveFlag {
    #[inline]
    pub fn new(alive: bool) -> Self {
        Self {
            flag: AtomicBool::new(alive).into(),
        }
    }

    #[inline]
    pub fn start(&self) -> Result<(), RuntimeError> {
        match self.flag.swap(true, Ordering::Relaxed) {
            true => RuntimeError::expect(ERR_STARTED),
            false => Ok(()),
        }
    }

    #[inline]
    pub fn stop(&self) -> Result<(), RuntimeError> {
        match self.flag.swap(false, Ordering::Relaxed) {
            false => RuntimeError::expect(ERR_STOPPED),
            true => Ok(()),
        }
    }

    #[inline]
    pub fn is_running(&self) -> bool {
        self.flag.load(Ordering::Relaxed)
    }

    #[inline]
    pub fn assert_running(&self) -> Result<(), RuntimeError> {
        match self.is_running() {
            true => Ok(()),
            false => RuntimeError::expect(ERR_NOT_STARTED),
        }
    }
}