use core::time::Duration; use safina::timer::{timer_thread, ScheduledWake, TimerThreadNotStarted}; use std::sync::{Arc, Mutex}; use std::time::Instant; fn make_scheduled_wakes() -> (ScheduledWake, ScheduledWake, ScheduledWake, ScheduledWake) { let now = Instant::now(); ( ScheduledWake { instant: now.checked_sub(Duration::from_millis(1)).unwrap(), waker: Arc::new(Mutex::new(None)), }, ScheduledWake { instant: now, waker: Arc::new(Mutex::new(None)), }, ScheduledWake { instant: now + Duration::from_millis(1), waker: Arc::new(Mutex::new(None)), }, ScheduledWake { instant: now + Duration::from_millis(1), waker: Arc::new(Mutex::new(None)), }, ) } #[test] fn test_scheduled() { use core::cmp::Ordering; let (sw1, sw2, sw3, sw3b) = make_scheduled_wakes(); assert!(format!("{sw1:?}").starts_with("ScheduledWake {")); assert_eq!(sw3, sw3b); assert_ne!(sw3, sw2); assert_eq!(Some(Ordering::Less), PartialOrd::partial_cmp(&sw1, &sw2)); assert_eq!(Some(Ordering::Equal), PartialOrd::partial_cmp(&sw1, &sw1)); assert_eq!(Some(Ordering::Greater), PartialOrd::partial_cmp(&sw2, &sw1)); assert_eq!(Ordering::Less, Ord::cmp(&sw1, &sw2)); assert_eq!(Ordering::Equal, Ord::cmp(&sw1, &sw1)); assert_eq!(Ordering::Greater, Ord::cmp(&sw2, &sw1)); } #[test] fn test_error() { let e1 = TimerThreadNotStarted {}; let e2 = TimerThreadNotStarted {}; assert_eq!("TimerThreadNotStarted", format!("{e1:?}")); assert_eq!(e1, e2); assert_eq!("TimerThreadNotStarted", format!("{e1}")); } #[test] #[should_panic(expected = "entered unreachable code")] fn test_disconnected() { let (sender, receiver) = std::sync::mpsc::sync_channel(1); sender .send(ScheduledWake { instant: Instant::now() + Duration::from_secs(1), waker: Arc::new(Mutex::new(None)), }) .unwrap(); drop(sender); timer_thread(receiver); }