babalcore 0.5.1

Babal core logic library, low-level things which are game-engine agnostic.
Documentation
// Used to keep track of time.
#[derive(Debug, Default, Clone, Copy)]
pub struct TimeTracker {
    now_sec_f64: f64,
}

/// Maximum number of seconds we can track. This is related
/// to the limit of a mantissa in 64-bit IEEE numbers, which
/// is about 10^15. Since we count in msec, we have to divide
/// to take away 3 digits. This is still several centuries.
pub const TIME_TRACKER_MAX_SEC: f64 = 1e12;

impl TimeTracker {
    /// Create a time tracker.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let _tt = TimeTracker::new();
    /// ```
    pub fn new() -> TimeTracker {
        TimeTracker::default()
    }

    /// Add time to the time tracker. This is typically something
    /// you'd call each time there's a process(delta).
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let mut tt = TimeTracker::new();
    /// tt.add(0.01);
    /// assert_eq!(0.01, tt.now_sec());
    /// ```
    pub fn add(&mut self, delta: f64) {
        self.now_sec_f64 += delta;
        if self.now_sec_f64 < 0.0 || self.now_sec_f64 >= TIME_TRACKER_MAX_SEC {
            self.now_sec_f64 = 0.0;
        }
    }

    /// Get the number of seconds since start of time.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let mut tt = TimeTracker::new();
    /// assert_eq!(0.0, tt.now_sec());
    /// tt.add(0.003);
    /// assert_eq!(0.003, tt.now_sec());
    /// ```
    pub fn now_sec(&self) -> f64 {
        self.now_sec_f64
    }

    /// Get the number of milliseconds since start of time.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let mut tt = TimeTracker::new();
    /// assert_eq!(0, tt.now_msec());
    /// tt.add(0.003);
    /// assert_eq!(3, tt.now_msec());
    /// ```
    pub fn now_msec(&self) -> i64 {
        (self.now_sec_f64 * 1000.0) as i64
    }
}

impl std::fmt::Display for TimeTracker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let now_msec = self.now_msec();
        write!(f, "{}.{:03}", now_msec / 1000, now_msec % 1000)
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn test_fmt() {
        let mut tt = TimeTracker::new();
        tt.add(2.0);
        tt.add(0.05);
        assert_eq!("2.050", format!("{}", tt));
    }
}