naive-timer

A minimal naive timer for embedded platforms in Rust (no_std + alloc).
NOTE: We need to use a nightly version of Rust.
Code
The naive-timer is really naive, that it only has 30 lines of code.
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use core::time::Duration;
#[derive(Default)]
pub struct Timer {
events: BTreeMap<Duration, Callback>,
}
type Callback = Box<dyn FnOnce(Duration) + Send + Sync + 'static>;
impl Timer {
pub fn add(
&mut self,
mut deadline: Duration,
callback: impl FnOnce(Duration) + Send + Sync + 'static,
) {
while self.events.contains_key(&deadline) {
deadline += Duration::from_nanos(1);
}
self.events.insert(deadline, Box::new(callback));
}
pub fn expire(&mut self, now: Duration) {
while let Some(entry) = self.events.first_entry() {
if *entry.key() > now {
return;
}
let (_, callback) = entry.remove_entry();
callback(now);
}
}
}
That's ALL.
License
The code in this repository is licensed under the MIT License.