weirdnet_chart/
throttle.rs1use std::time::{Duration, Instant};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Redraw {
8 Now,
10 After(Duration),
12 Scheduled,
14}
15
16#[derive(Clone, Debug)]
23pub struct FrameThrottle {
24 interval: Duration,
25 last_frame: Option<Instant>,
26 pending: bool,
27}
28
29impl FrameThrottle {
30 pub fn new(fps: u32) -> FrameThrottle {
32 FrameThrottle::with_interval(Duration::from_secs_f64(1.0 / fps.max(1) as f64))
33 }
34
35 pub fn with_interval(interval: Duration) -> FrameThrottle {
37 FrameThrottle { interval, last_frame: None, pending: false }
38 }
39
40 pub fn interval(&self) -> Duration {
42 self.interval
43 }
44
45 pub fn is_pending(&self) -> bool {
47 self.pending
48 }
49
50 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 pub fn fire(&mut self, now: Instant) {
69 self.pending = false;
70 self.last_frame = Some(now);
71 }
72
73 pub fn frame_drawn(&mut self, now: Instant) {
75 self.last_frame = Some(now);
76 }
77
78 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 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 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}