1#[derive(Debug)]
4pub struct Tuning {
5 steps: [u32; 128],
6 sample_period: f32,
7}
8
9impl Tuning {
10 #[must_use]
14 #[allow(
15 clippy::cast_possible_truncation,
16 clippy::cast_sign_loss,
17 reason = "The phase increment is positive and at most 2^31. The nonzero u32 clock ratio fits in f32."
18 )]
19 pub const fn new(numerator: u32, denominator: u32) -> Option<Self> {
20 if numerator == 0 || denominator == 0 {
21 return None;
22 }
23 let mut steps = [0; 128];
24 let mut step =
26 8.175_798_915_643_707 * 4_294_967_296.0 * denominator as f64 / numerator as f64;
27 let mut note: usize = 0;
28 while note < steps.len() {
29 if step < 2_147_483_648.0 {
30 steps[note] = (step + 0.5) as u32;
31 }
32 step *= 1.059_463_094_359_295_3;
33 note = note.wrapping_add(1);
34 }
35 Some(Self {
36 steps,
37 sample_period: (denominator as f64 / numerator as f64) as f32,
38 })
39 }
40
41 #[must_use]
44 pub const fn phase_step(&self, note: u8) -> u32 {
45 if (note as usize) < self.steps.len() {
46 self.steps[note as usize]
47 } else {
48 0
49 }
50 }
51
52 #[must_use]
54 pub const fn sample_period(&self) -> f32 {
55 self.sample_period
56 }
57}