1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use num::{FromPrimitive, ToPrimitive};
use std::ops::{Add, Sub, Mul, Div, Rem, Neg};
use super::calc;
use super::{
Bpm,
Division,
DivType,
Measure,
Ms,
NumDiv,
Ppqn,
SampleHz,
Samples,
Ticks,
TimeSig,
beat_in_ms,
samples_from_ms,
};
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Beats(pub NumDiv);
impl Beats {
#[inline]
pub fn beats(&self) -> NumDiv { let Beats(num) = *self; num }
#[inline]
pub fn bars(&self, ts: TimeSig) -> f64 { Division::Beat.bars(ts) }
#[inline]
pub fn measure(&self) -> Measure { Measure(self.beats(), Division::Beat, DivType::Whole) }
#[inline]
pub fn ms(&self, bpm: Bpm) -> calc::Ms {
self.beats() as calc::Ms * beat_in_ms(bpm)
}
#[inline]
pub fn to_ms(&self, bpm: Bpm) -> Ms {
Ms(self.ms(bpm))
}
#[inline]
pub fn samples(&self, bpm: Bpm, sample_hz: SampleHz) -> calc::Samples {
samples_from_ms(self.ms(bpm), sample_hz)
}
#[inline]
pub fn to_samples(&self, bpm: Bpm, sample_hz: SampleHz) -> Samples {
Samples(self.samples(bpm, sample_hz))
}
#[inline]
pub fn ticks(&self, ppqn: Ppqn) -> calc::Ticks {
self.beats() as calc::Ticks * ppqn as calc::Ticks
}
#[inline]
pub fn to_ticks(&self, ppqn: Ppqn) -> Ticks {
Ticks(self.ticks(ppqn))
}
}
impl From<NumDiv> for Beats {
fn from(n: NumDiv) -> Self {
Beats(n)
}
}
impl Add for Beats {
type Output = Beats;
#[inline]
fn add(self, rhs: Beats) -> Beats {
Beats(self.beats() + rhs.beats())
}
}
impl Sub for Beats {
type Output = Beats;
#[inline]
fn sub(self, rhs: Beats) -> Beats {
Beats(self.beats() - rhs.beats())
}
}
impl Mul for Beats {
type Output = Beats;
#[inline]
fn mul(self, rhs: Beats) -> Beats {
Beats(self.beats() * rhs.beats())
}
}
impl Div for Beats {
type Output = Beats;
#[inline]
fn div(self, rhs: Beats) -> Beats {
Beats(self.beats() / rhs.beats())
}
}
impl Rem for Beats {
type Output = Beats;
#[inline]
fn rem(self, rhs: Beats) -> Beats {
Beats(self.beats() % rhs.beats())
}
}
impl Neg for Beats {
type Output = Beats;
#[inline]
fn neg(self) -> Beats {
Beats(-self.beats())
}
}
impl ToPrimitive for Beats {
fn to_u64(&self) -> Option<u64> {
self.beats().to_u64()
}
fn to_i64(&self) -> Option<i64> {
self.beats().to_i64()
}
}
impl FromPrimitive for Beats {
fn from_u64(n: u64) -> Option<Beats> {
Some(Beats(n as NumDiv))
}
fn from_i64(n: i64) -> Option<Beats> {
Some(Beats(n as NumDiv))
}
}