notation_core/
signature.rs1use std::fmt::Display;
2
3use serde::{Deserialize, Serialize};
4
5use crate::prelude::{Unit, Units};
6
7#[derive(Copy, Clone, PartialEq, PartialOrd, Serialize, Deserialize, Debug)]
8pub struct Beats(pub f32);
9
10#[derive(Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
11pub struct Signature {
12 pub beat_unit: Unit,
13 pub bar_beats: u8,
14}
15impl Display for Signature {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 write!(f, "{}/{}", self.bar_beats, match self.beat_unit {
18 Unit::Whole => 1,
19 Unit::Half => 2,
20 Unit::Quarter => 4,
21 Unit::Eighth => 8,
22 Unit::Sixteenth => 16,
23 Unit::ThirtySecondth => 32,
24 })
25 }
26}
27
28impl Signature {
29 pub fn new(beat_unit: Unit, bar_beats: u8) -> Self {
30 Self {
31 beat_unit,
32 bar_beats,
33 }
34 }
35}
36
37impl Signature {
38 pub const _4_4: Self = Self {
39 beat_unit: Unit::Quarter,
40 bar_beats: 4,
41 };
42 pub const _3_4: Self = Self {
43 beat_unit: Unit::Quarter,
44 bar_beats: 3,
45 };
46 pub const _2_4: Self = Self {
47 beat_unit: Unit::Quarter,
48 bar_beats: 2,
49 };
50 pub const _6_8: Self = Self {
51 beat_unit: Unit::Eighth,
52 bar_beats: 6,
53 };
54}
55
56impl From<f32> for Beats {
57 fn from(v: f32) -> Self {
58 Self(v)
59 }
60}
61
62impl From<Signature> for Units {
63 fn from(v: Signature) -> Self {
64 Self::from(Units::from(v.beat_unit).0 * (v.bar_beats as f32))
65 }
66}
67
68impl From<Signature> for Beats {
69 fn from(v: Signature) -> Self {
70 Self::from(v.bar_beats as f32)
71 }
72}
73
74impl From<(Signature, Units)> for Beats {
75 fn from((signature, units): (Signature, Units)) -> Self {
76 Self::from(units.0 / Units::from(signature.beat_unit).0)
77 }
78}