naive-timer 0.1.0

A minimal naive timer for embedded (no_std) platforms.
Documentation

naive-timer

Crate Docs Actions Status Coverage Status

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;

/// A naive timer.
#[derive(Default)]
pub struct Timer {
    events: BTreeMap<Duration, Callback>,
}

/// The type of callback function.
type Callback = Box<dyn FnOnce(Duration) + Send + Sync + 'static>;

impl Timer {
    /// Add a timer.
    ///
    /// The `callback` will be called on timer expired after `deadline`.
    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));
    }

    /// Expire timers.
    ///
    /// Given the current time `now`, trigger and remove all expired timers.
    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.