Skip to main content

firefly_rust/audio/
time.rs

1use super::*;
2
3#[derive(Clone, Copy)]
4pub struct Time(pub(super) u32);
5
6impl Time {
7    pub const ZERO: Self = Self(0);
8    pub const SECOND: Self = Self(SAMPLE_RATE);
9
10    #[must_use]
11    pub fn from_samples(s: u32) -> Self {
12        Self(s)
13    }
14
15    #[must_use]
16    pub fn from_seconds(s: u32) -> Self {
17        Self(s * SAMPLE_RATE)
18    }
19
20    #[must_use]
21    pub fn from_ms(s: u32) -> Self {
22        Self(s * SAMPLE_RATE / 1000)
23    }
24
25    #[must_use]
26    pub fn duration(s: core::time::Duration) -> Self {
27        let s = s.as_secs_f32() * 44_100.;
28        #[expect(clippy::cast_sign_loss)]
29        let s = s as u32;
30        Self(s)
31    }
32}
33
34/// Alias for [`Time::from_samples`].
35#[must_use]
36pub fn samples(s: u32) -> Time {
37    Time::from_samples(s)
38}
39
40/// Alias for [`Time::from_seconds`].
41#[must_use]
42pub fn seconds(s: u32) -> Time {
43    Time::from_seconds(s)
44}
45
46/// Alias for [`Time::from_ms`].
47#[must_use]
48pub fn ms(s: u32) -> Time {
49    Time::from_ms(s)
50}
51
52impl core::ops::Add for Time {
53    type Output = Self;
54
55    fn add(self, rhs: Self) -> Self::Output {
56        Self(self.0 + rhs.0)
57    }
58}
59
60impl core::ops::Sub for Time {
61    type Output = Self;
62
63    fn sub(self, rhs: Self) -> Self::Output {
64        Self(self.0 - rhs.0)
65    }
66}
67
68impl core::ops::Div<u32> for Time {
69    type Output = Time;
70
71    fn div(self, rhs: u32) -> Self::Output {
72        Self(self.0 / rhs)
73    }
74}
75
76impl core::ops::Mul<u32> for Time {
77    type Output = Time;
78
79    fn mul(self, rhs: u32) -> Self::Output {
80        Self(self.0 * rhs)
81    }
82}