Skip to main content

weirdnet_chart/
throttle.rs

1//! Frame-rate throttling for live redraws.
2
3use std::time::{Duration, Instant};
4
5/// What to do after [`FrameThrottle::request`].
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Redraw {
8    /// Draw now; the frame has been counted.
9    Now,
10    /// Draw after this delay, then call [`FrameThrottle::fire`].
11    After(Duration),
12    /// A delayed redraw is already scheduled; nothing to do.
13    Scheduled,
14}
15
16/// Coalesces redraw requests to at most one frame per interval.
17///
18/// Feed it every data update with [`request`](Self::request). Bursts of updates (say a
19/// hundred trades in a millisecond) turn into one immediate frame and at most one delayed
20/// frame, so the last update is always drawn. Loops that poll instead of scheduling a timer
21/// use [`poll`](Self::poll) and [`timeout`](Self::timeout).
22#[derive(Clone, Debug)]
23pub struct FrameThrottle {
24    interval: Duration,
25    last_frame: Option<Instant>,
26    pending: bool,
27}
28
29impl FrameThrottle {
30    /// At most `fps` frames per second (at least 1).
31    pub fn new(fps: u32) -> FrameThrottle {
32        FrameThrottle::with_interval(Duration::from_secs_f64(1.0 / fps.max(1) as f64))
33    }
34
35    /// At most one frame per `interval`.
36    pub fn with_interval(interval: Duration) -> FrameThrottle {
37        FrameThrottle { interval, last_frame: None, pending: false }
38    }
39
40    /// The minimum time between frames.
41    pub fn interval(&self) -> Duration {
42        self.interval
43    }
44
45    /// Whether a delayed redraw is waiting.
46    pub fn is_pending(&self) -> bool {
47        self.pending
48    }
49
50    /// Asks for a redraw at `now`.
51    pub fn request(&mut self, now: Instant) -> Redraw {
52        if self.pending {
53            return Redraw::Scheduled;
54        }
55        match self.last_frame {
56            Some(last) if now.saturating_duration_since(last) < self.interval => {
57                self.pending = true;
58                Redraw::After(self.interval - now.saturating_duration_since(last))
59            }
60            _ => {
61                self.last_frame = Some(now);
62                Redraw::Now
63            }
64        }
65    }
66
67    /// Records that the delayed redraw ran at `now`.
68    pub fn fire(&mut self, now: Instant) {
69        self.pending = false;
70        self.last_frame = Some(now);
71    }
72
73    /// Records a frame drawn for another reason (a resize, say) at `now`.
74    pub fn frame_drawn(&mut self, now: Instant) {
75        self.last_frame = Some(now);
76    }
77
78    /// For polling loops: true (and the frame is counted) when a pending redraw is due.
79    pub fn poll(&mut self, now: Instant) -> bool {
80        if self.pending && self.timeout(now) == Some(Duration::ZERO) {
81            self.fire(now);
82            true
83        } else {
84            false
85        }
86    }
87
88    /// How long until a pending redraw is due, or `None` if nothing is pending.
89    pub fn timeout(&self, now: Instant) -> Option<Duration> {
90        if !self.pending {
91            return None;
92        }
93        let elapsed = self.last_frame.map_or(self.interval, |l| now.saturating_duration_since(l));
94        Some(self.interval.saturating_sub(elapsed))
95    }
96}
97
98impl Default for FrameThrottle {
99    /// 60 frames per second.
100    fn default() -> Self {
101        FrameThrottle::new(60)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn coalesces_bursts() {
111        let t0 = Instant::now();
112        let ms = Duration::from_millis;
113        let mut th = FrameThrottle::with_interval(ms(16));
114        assert_eq!(th.request(t0), Redraw::Now);
115        assert_eq!(th.request(t0 + ms(4)), Redraw::After(ms(12)));
116        for i in 5..15 {
117            assert_eq!(th.request(t0 + ms(i)), Redraw::Scheduled);
118        }
119        assert_eq!(th.timeout(t0 + ms(10)), Some(ms(6)));
120        assert!(!th.poll(t0 + ms(10)));
121        assert!(th.poll(t0 + ms(16)));
122        assert!(!th.is_pending());
123        assert_eq!(th.request(t0 + ms(40)), Redraw::Now);
124    }
125
126    #[test]
127    fn fps_interval() {
128        assert_eq!(FrameThrottle::new(50).interval(), Duration::from_millis(20));
129        assert_eq!(FrameThrottle::new(0).interval(), Duration::from_secs(1));
130    }
131}