Skip to main content

blit/
timer.rs

1use crate::*;
2
3/// a timer from [`Ui::timer`] or [`Ui::interval`]
4pub struct Timer<'a> {
5    state: &'a mut TimerState,
6    now: Duration,
7}
8
9impl Timer<'_> {
10    /// whole periods since the timer started, at most one for [`Ui::timer`]
11    pub fn count(&self) -> u64 {
12        self.state.count
13    }
14
15    /// true if this frame completed a period
16    pub fn fired(&self) -> bool {
17        self.state.fired
18    }
19
20    /// counts from now
21    pub fn reset(&mut self) {
22        self.state.start = self.now;
23        self.state.count = 0;
24        self.state.fired = false;
25    }
26}
27
28//
29// internals
30//
31
32pub struct TimerState {
33    pub call: Call,
34    pub seen: bool,
35    start: Duration,
36    period: Duration,
37    repeat: bool,
38    count: u64,
39    fired: bool,
40}
41
42impl TimerState {
43    pub fn update(timers: &mut Vec<Self>, mut call: Call, period: Duration, repeat: bool, now: Duration) -> Timer<'_> {
44        // sorted by call so lookups stay logarithmic
45        let index = loop {
46            match timers.binary_search_by_key(&call, |timer| timer.call) {
47                Ok(index) if timers[index].seen => call.repeat += 1,
48                Ok(index) => break index,
49                Err(index) => {
50                    timers.insert(index, Self::new(call, period, repeat, now));
51                    break index;
52                }
53            }
54        };
55        let timer = &mut timers[index];
56        timer.seen = true;
57        // a changed period or kind starts over
58        if timer.period != period || timer.repeat != repeat {
59            *timer = Self {
60                seen: true,
61                ..Self::new(call, period, repeat, now)
62            };
63        }
64        let elapsed = now.saturating_sub(timer.start).as_nanos();
65        let count = match period.as_nanos() {
66            0 => 1,
67            period => (elapsed / period).min(u64::MAX as u128) as u64,
68        };
69        let count = if repeat { count } else { count.min(1) };
70        timer.fired = count > timer.count;
71        timer.count = count;
72        Timer { state: timer, now }
73    }
74
75    pub fn deadline(&self) -> Option<Duration> {
76        if !self.repeat && self.count != 0 {
77            return None;
78        }
79        let next = self.period.as_nanos().saturating_mul(u128::from(self.count) + 1);
80        Some(
81            self.start
82                .saturating_add(Duration::from_nanos(next.min(u64::MAX as u128) as u64)),
83        )
84    }
85}
86
87impl TimerState {
88    fn new(call: Call, period: Duration, repeat: bool, now: Duration) -> Self {
89        Self {
90            call,
91            seen: false,
92            start: now,
93            period,
94            repeat,
95            count: 0,
96            fired: false,
97        }
98    }
99}