start_time.rs (1501B)
1 use std::mem; 2 use std::sync::{Arc, Mutex, Once}; 3 use std::time::{Duration, Instant}; 4 5 #[derive(Clone, Debug)] 6 pub struct StartTime { 7 start: Arc<Mutex<Option<Instant>>>, 8 } 9 10 impl StartTime { 11 pub(crate) fn singleton() -> StartTime { 12 // Initialize it to a null value 13 static mut START_TIME_SINGLETON: *const StartTime = 0 as *const StartTime; 14 static START_TIME_ONCE: Once = Once::new(); 15 16 unsafe { 17 START_TIME_ONCE.call_once(|| { 18 // Make it 19 let singleton = StartTime { 20 start: Arc::new(Mutex::new(None)), 21 }; 22 23 // Put it in the heap so it can outlive this call 24 START_TIME_SINGLETON = mem::transmute(Box::new(singleton)); 25 }); 26 27 // Now we give out a copy of the data that is safe to use concurrently. 28 (*START_TIME_SINGLETON).clone() 29 } 30 } 31 32 pub fn get(&self) -> bool { 33 let running = self.start.lock().unwrap(); 34 let data = running.clone(); 35 match data { 36 None => false, 37 Some(v) => { 38 if Instant::now().duration_since(v) >= Duration::from_secs(3) { 39 true 40 } else { 41 false 42 } 43 } 44 } 45 } 46 47 pub fn set(&mut self, time: Instant) { 48 let mut state = self.start.lock().expect("Could not lock mutex"); 49 mem::replace(&mut *state, Some(time.clone())); 50 } 51 }