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
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//! This is a safe Rust library providing async `sleep_for` and `sleep_until` functions.
//! These functions return futures that complete at the specified time.
//!
//! It works well with [`safina`](https://crates.io/crates/safina).
//!
//! # Features
//! - `forbid(unsafe_code)`
//! - Depends only on `std`
//! - Good test coverage (95%)
//! - Source of time is
//!   [`std::thread::park_timeout`](https://doc.rust-lang.org/std/thread/fn.park_timeout.html)
//!   via
//!   [`std::sync::mpsc::Receiver::recv_timeout`](https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.recv_timeout).
//!
//! # Limitations
//! - Requires Rust `nightly`, for [OnceCell](https://doc.rust-lang.org/std/lazy/struct.OnceCell.html)
//! - Timers complete around 2ms late, but never early
//! - Allocates memory
//!
//! # Examples
//! ```rust
//! # use std::time::Duration;
//! # async fn f() {
//! safina_timer::start_timer_thread();
//! safina_timer::sleep_for(Duration::from_secs(10)).await.unwrap();
//! # }
//! ```
//!
//! ```rust
//! # use std::time::{Duration, Instant};
//! # async fn f() {
//! safina_timer::start_timer_thread();
//! let deadline = Instant::now() + Duration::from_millis(500);
//! safina_timer::sleep_until(deadline).await.unwrap();
//! # }
//! ```
//!
//! # Documentation
//! https://docs.rs/safina-timer
//!
//! # Alternatives
//! - [futures-timer](https://crates.io/crates/futures-timer)
//!   - popular
//!   - Supports: Wasm, Linux, Windows, macOS
//!   - Contains generous amounts of `unsafe` code
//!   - Uses `std::thread::park_timeout` as its source of time
//! - [async-io](https://crates.io/crates/async-io)
//!   - popular
//!   - single and repeating timers
//!   - Supports: Linux, Windows, macOS, iOS, Android, and many others.
//!   - Uses [polling](https://crates.io/crates/polling) crate
//!     which makes unsafe calls to OS.
//! - [async-timer](https://crates.io/crates/async-timer)
//!   - Supports: Linux & Android
//!   - Makes unsafe calls to OS
//! - [tokio](https://crates.io/crates/tokio)
//!   - very popular
//!   - single and repeating timers
//!   - Supports: Linux, macOS, other unix-like OSes, Windows
//!   - Fast, internally complicated, and full of `unsafe`
//! - [embedded-async-timer](https://crates.io/crates/embedded-async-timer)
//!   - no_std
//!   - Supports: bare_metal
//! # Release Process
//! 1. Edit `Cargo.toml` and bump version number.
//! 1. Run `./release.sh`
//!
//! # Changelog
//! - v0.1.1
//!   - Use most recent waker passed to `SleepFuture::poll`, as required by the
//!     [`std::future::Future::poll`](https://doc.rust-lang.org/stable/std/future/trait.Future.html#tymethod.poll)
//!     contract.
//!   - Add [`with_deadline`](https://docs.rs/safina-timer/0.1.0/safina_timer/fn.with_deadline.html)
//!     and [`with_timeout`](https://docs.rs/safina-timer/0.1.0/safina_timer/fn.with_timeout.html)
//!     functions.
//! - v0.1.0 - First published version
//!
//! # TO DO
//! - DONE - Implement `sleep_until`
//! - DONE - Implement `sleep_for`
//! - DONE - Add tests
//! - Add docs
//! - Publish on crates.io
#![forbid(unsafe_code)]
#![feature(once_cell)]
#![feature(wake_trait)]

mod deadline_future;
pub use deadline_future::*;

mod sleep_future;
pub use sleep_future::*;

#[cfg(test)]
pub use tests::*;

use core::cmp::Reverse;
use core::fmt::{Debug, Display, Formatter};
use core::task::Waker;
use std::collections::BinaryHeap;
use std::error::Error;
use std::lazy::SyncOnceCell;
use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender};
use std::sync::{Arc, Mutex};
use std::time::Instant;

#[derive(Debug)]
pub(crate) struct ScheduledWake {
    instant: Instant,
    waker: Arc<Mutex<Option<Waker>>>,
}
impl ScheduledWake {
    pub fn wake(&self) {
        if let Some(waker) = self.waker.lock().unwrap().take() {
            waker.wake();
        }
    }
}
impl PartialEq for ScheduledWake {
    fn eq(&self, other: &Self) -> bool {
        std::cmp::PartialEq::eq(&self.instant, &other.instant)
    }
}
impl Eq for ScheduledWake {}
impl PartialOrd for ScheduledWake {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        core::cmp::PartialOrd::partial_cmp(&self.instant, &other.instant)
    }
}
impl Ord for ScheduledWake {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        std::cmp::Ord::cmp(&self.instant, &other.instant)
    }
}

static TIMER_THREAD_SENDER: SyncOnceCell<SyncSender<ScheduledWake>> = SyncOnceCell::new();

/// Starts the worker thread, if it's not already started.
/// You must call this before calling [`sleep_until`] or [`sleep_for`].
pub fn start_timer_thread() {
    TIMER_THREAD_SENDER.get_or_init(|| {
        let (sender, receiver) = std::sync::mpsc::sync_channel(0);
        std::thread::spawn(|| timer_thread(receiver));
        sender
    });
}

fn timer_thread(receiver: Receiver<ScheduledWake>) {
    let mut heap: BinaryHeap<Reverse<ScheduledWake>> = BinaryHeap::new();
    loop {
        if let Some(Reverse(peeked_wake)) = heap.peek() {
            let now = Instant::now();
            if peeked_wake.instant < now {
                heap.pop().unwrap().0.wake();
            } else {
                // We can switch to recv_deadline once it is stable:
                // https://github.com/rust-lang/rust/issues/46316
                match receiver.recv_timeout(peeked_wake.instant - now) {
                    Ok(new_wake) => {
                        heap.push(Reverse(new_wake));
                    }
                    Err(RecvTimeoutError::Timeout) => {}
                    Err(RecvTimeoutError::Disconnected) => unreachable!(),
                }
            }
        } else {
            heap.push(Reverse(receiver.recv().unwrap()));
        }
    }
}

/// Call [`start_timer_thread`] to prevent this error.
#[derive(Debug, PartialEq)]
pub struct TimerThreadNotStarted {}
impl Display for TimerThreadNotStarted {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        std::fmt::Debug::fmt(self, f)
    }
}
impl Error for TimerThreadNotStarted {}

fn schedule_wake(
    instant: Instant,
    waker: Arc<Mutex<Option<Waker>>>,
) -> Result<(), TimerThreadNotStarted> {
    let sender = TIMER_THREAD_SENDER.get().ok_or(TimerThreadNotStarted {})?;
    sender.send(ScheduledWake { instant, waker }).unwrap();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::ops::Range;
    use core::time::Duration;
    use std::sync::atomic::AtomicBool;
    use std::sync::Arc;
    use std::time::Instant;

    #[derive(Clone)]
    pub struct FakeWaker {
        called_flag: Arc<AtomicBool>,
    }
    impl FakeWaker {
        pub fn new(called_flag: &Arc<AtomicBool>) -> Self {
            Self {
                called_flag: called_flag.clone(),
            }
        }
        pub fn into_waker(self) -> Waker {
            std::task::Waker::from(Arc::new(self))
        }
    }
    impl std::task::Wake for FakeWaker {
        fn wake(self: Arc<Self>) {
            if self
                .called_flag
                .fetch_or(true, std::sync::atomic::Ordering::AcqRel)
            {
                panic!("wake already called");
            }
        }
    }

    pub fn expect_elapsed(before: Instant, range_ms: Range<u64>) {
        if range_ms.is_empty() {
            panic!("invalid range {:?}", range_ms)
        }
        let elapsed = before.elapsed();
        let duration_range =
            Duration::from_millis(range_ms.start)..Duration::from_millis(range_ms.end);
        if !duration_range.contains(&elapsed) {
            panic!("{:?} elapsed, out of range {:?}", elapsed, duration_range);
        }
    }

    fn make_scheduled_wakes() -> (ScheduledWake, ScheduledWake, ScheduledWake, ScheduledWake) {
        let now = Instant::now();
        (
            ScheduledWake {
                instant: now - Duration::from_millis(1),
                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));
    }
}