1use std::time::Duration;
2
3#[derive(Debug, Clone)]
4pub struct FixedStepClock {
5 timestep: Duration,
6 accumulator: Duration,
7}
8
9impl FixedStepClock {
10 pub fn new(timestep: Duration) -> Self {
12 Self {
13 timestep,
14 accumulator: Duration::ZERO,
15 }
16 }
17
18 pub fn timestep(&self) -> Duration {
20 self.timestep
21 }
22
23 pub fn accumulator(&self) -> Duration {
25 self.accumulator
26 }
27
28 pub fn push_elapsed(&mut self, elapsed: Duration) -> usize {
30 self.accumulator += elapsed;
31 let mut ticks = 0usize;
32
33 while self.accumulator >= self.timestep {
34 self.accumulator -= self.timestep;
35 ticks += 1;
36 }
37
38 ticks
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::FixedStepClock;
45 use std::time::Duration;
46
47 #[test]
48 fn advances_only_on_full_ticks() {
49 let mut clock = FixedStepClock::new(Duration::from_millis(16));
50 assert_eq!(clock.push_elapsed(Duration::from_millis(10)), 0);
51 assert_eq!(clock.push_elapsed(Duration::from_millis(10)), 1);
52 assert_eq!(clock.accumulator(), Duration::from_millis(4));
53 }
54}