gilrs/ff/
time.rs

1// Copyright 2016-2018 Mateusz Sieczko and other GilRs Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use std::ops::{Add, AddAssign, Mul, MulAssign, Rem, Sub, SubAssign};
9use std::time::Duration;
10
11use crate::utils;
12
13pub(crate) const TICK_DURATION: u32 = 50;
14
15/// Represents duration.
16///
17/// This type is only useful as input parameter for other functions in force feedback module. To
18/// create it, use `from_ms()` method. Keep in mind that `Ticks` **is not precise** representation
19/// of time.
20///
21/// # Example
22///
23/// ```rust
24/// use gilrs::ff::Ticks;
25/// use std::time::Duration;
26///
27/// let t1 = Ticks::from_ms(110);
28/// let t2 = Ticks::from(Duration::from_millis(130));
29///
30/// /// `Ticks` is not precise.
31/// assert_eq!(t1, t2);
32/// ```
33#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
34pub struct Ticks(pub(super) u32);
35
36impl Ticks {
37    pub fn from_ms(dur: u32) -> Self {
38        Ticks(utils::ceil_div(dur, TICK_DURATION))
39    }
40
41    pub(super) fn inc(&mut self) {
42        self.0 += 1
43    }
44
45    pub(super) fn checked_sub(self, rhs: Ticks) -> Option<Ticks> {
46        self.0.checked_sub(rhs.0).map(Ticks)
47    }
48}
49
50impl From<Duration> for Ticks {
51    fn from(dur: Duration) -> Self {
52        Ticks::from_ms(dur.as_secs() as u32 * 1000 + dur.subsec_millis())
53    }
54}
55
56impl Add for Ticks {
57    type Output = Ticks;
58
59    fn add(self, rhs: Ticks) -> Self::Output {
60        Ticks(self.0 + rhs.0)
61    }
62}
63
64impl AddAssign for Ticks {
65    fn add_assign(&mut self, rhs: Ticks) {
66        self.0 += rhs.0
67    }
68}
69
70impl Sub for Ticks {
71    type Output = Ticks;
72
73    fn sub(self, rhs: Ticks) -> Self::Output {
74        Ticks(self.0 - rhs.0)
75    }
76}
77
78impl SubAssign for Ticks {
79    fn sub_assign(&mut self, rhs: Ticks) {
80        self.0 -= rhs.0
81    }
82}
83
84impl Mul<u32> for Ticks {
85    type Output = Ticks;
86
87    fn mul(self, rhs: u32) -> Self::Output {
88        Ticks(self.0 * rhs)
89    }
90}
91
92impl MulAssign<u32> for Ticks {
93    fn mul_assign(&mut self, rhs: u32) {
94        self.0 *= rhs;
95    }
96}
97
98impl Rem for Ticks {
99    type Output = Ticks;
100
101    fn rem(self, rhs: Ticks) -> Self::Output {
102        Ticks(self.0 % rhs.0)
103    }
104}
105
106/// Describes how long effect should be played.
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
108pub enum Repeat {
109    /// Play effect until stop() is called.
110    #[default]
111    Infinitely,
112    /// Play effect for specified time.
113    For(Ticks),
114}