1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 #![deny(missing_docs)] 6 7 //! A timer module, used to define a `Timer` type, that is controlled by script. 8 9 use time; 10 11 /// The `TimerMode` is used to determine what time should the `Timer` return. 12 #[derive(Clone, Debug)] 13 enum TimerMode { 14 /// The timer should return a fixed value. 15 Test(f64), 16 /// The timer should return the actual time. 17 Current, 18 } 19 20 /// A `Timer` struct that takes care of giving the current time for animations. 21 /// 22 /// This is needed to be allowed to hook the time in the animations' test-mode. 23 #[derive(Clone, Debug)] 24 pub struct Timer { 25 mode: TimerMode, 26 } 27 28 impl Timer { 29 /// Creates a new "normal" timer, i.e., a "Current" mode timer. 30 #[inline] new() -> Self31 pub fn new() -> Self { 32 Timer { 33 mode: TimerMode::Current, 34 } 35 } 36 37 /// Creates a new "test mode" timer, with initial time 0. 38 #[inline] test_mode() -> Self39 pub fn test_mode() -> Self { 40 Timer { 41 mode: TimerMode::Test(0.), 42 } 43 } 44 45 /// Returns the current time, at least from the caller's perspective. In 46 /// test mode returns whatever the value is. seconds(&self) -> f6447 pub fn seconds(&self) -> f64 { 48 match self.mode { 49 TimerMode::Test(test_value) => test_value, 50 TimerMode::Current => time::precise_time_s(), 51 } 52 } 53 54 /// Increments the current clock. Panics if the clock is not on test mode. increment(&mut self, by: f64)55 pub fn increment(&mut self, by: f64) { 56 match self.mode { 57 TimerMode::Test(ref mut val) 58 => *val += by, 59 TimerMode::Current 60 => panic!("Timer::increment called for a non-test mode timer. This is a bug."), 61 } 62 } 63 } 64