ada

git clone git://archive.git.mtrnord.blog/MTRNord/ada.git
Log | Files | Refs

analyzer_state.rs (1241B)


      1 use std::mem;
      2 use std::sync::{Arc, Mutex, Once};
      3 
      4 #[derive(Clone, Debug)]
      5 pub struct AnalyzerState {
      6     running: Arc<Mutex<bool>>,
      7 }
      8 
      9 impl AnalyzerState {
     10     pub(crate) fn singleton() -> Self {
     11         // Initialize it to a null value
     12         static mut ANALYZER_STATE_SINGLETON: *const AnalyzerState = 0 as *const AnalyzerState;
     13         static ANALYZER_STATE_ONCE: Once = Once::new();
     14 
     15         unsafe {
     16             ANALYZER_STATE_ONCE.call_once(|| {
     17                 // Make it
     18                 let singleton = AnalyzerState {
     19                     running: Arc::new(Mutex::new(false)),
     20                 };
     21 
     22                 // Put it in the heap so it can outlive this call
     23                 ANALYZER_STATE_SINGLETON = mem::transmute(Box::new(singleton));
     24             });
     25 
     26             // Now we give out a copy of the data that is safe to use concurrently.
     27             (*ANALYZER_STATE_SINGLETON).clone()
     28         }
     29     }
     30 
     31     pub fn get(&self) -> bool {
     32         let running = self.running.lock().unwrap();
     33         let data = running.clone();
     34         data
     35     }
     36 
     37     pub fn set(&mut self, new_value: bool) {
     38         let mut state = self.running.lock().expect("Could not lock mutex");
     39         mem::replace(&mut *state, new_value.clone());
     40     }
     41 }