Skip to content

Commit

Permalink
refactor Dur::into_ratio
Browse files Browse the repository at this point in the history
  • Loading branch information
tsionyx committed Feb 6, 2024
1 parent f5a62d5 commit 7ce5f8f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 10 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@ repository = "https://github.com/tsionyx/musik"

[dependencies]
num-rational = "0.4"
num-integer = "0.1"
enum-map ="2.6"
enum-iterator = "1.4"
2 changes: 1 addition & 1 deletion examples/hsom-exercises/ch4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ fn child_song_6() -> Music {
+ M::B(oc4, Dur::HN),
];
let main_voice = v1.times(3) + M::line(v2);
let t = (Dur::DHN.into_rational() / Dur::QN.into_rational()) * Ratio::new(69, 120);
let t = (Dur::DHN.into_ratio() / Dur::QN.into_ratio()) * Ratio::new(69, 120);
(bass_line | main_voice)
.with_tempo(t)
.with_instrument(StandardMidiInstrument::RhodesPiano)
Expand Down
21 changes: 12 additions & 9 deletions src/music/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl PartialOrd for Dur {

impl Ord for Dur {
fn cmp(&self, other: &Self) -> Ordering {
self.into_rational().cmp(&other.into_rational())
self.into_ratio::<u8>().cmp(&other.into_ratio())
}
}

Expand All @@ -29,8 +29,11 @@ impl Dur {
Self(num, denom)
}

pub fn into_rational(self) -> Ratio<u8> {
Ratio::new(self.0, self.1)
pub fn into_ratio<T>(self) -> Ratio<T>
where
T: From<u8> + Clone + num_integer::Integer,
{
Ratio::new(T::from(self.0), T::from(self.1))
}

pub const ZERO: Self = Self::from_integer(0);
Expand Down Expand Up @@ -117,46 +120,46 @@ impl Add for Dur {
type Output = Self;

fn add(self, rhs: Self) -> Self::Output {
(self.into_rational() + rhs.into_rational()).into()
(self.into_ratio() + rhs.into_ratio()).into()
}
}

impl Sub for Dur {
type Output = Self;

fn sub(self, rhs: Self) -> Self::Output {
(self.into_rational() - rhs.into_rational()).into()
(self.into_ratio() - rhs.into_ratio()).into()
}
}

impl Mul<u8> for Dur {
type Output = Self;

fn mul(self, rhs: u8) -> Self::Output {
(self.into_rational() * rhs).into()
(self.into_ratio() * rhs).into()
}
}

impl Mul<Ratio<u8>> for Dur {
type Output = Self;

fn mul(self, rhs: Ratio<u8>) -> Self::Output {
(self.into_rational() * rhs).into()
(self.into_ratio() * rhs).into()
}
}

impl Div<u8> for Dur {
type Output = Self;

fn div(self, rhs: u8) -> Self::Output {
(self.into_rational() / rhs).into()
(self.into_ratio() / rhs).into()
}
}

impl Div<Ratio<u8>> for Dur {
type Output = Self;

fn div(self, rhs: Ratio<u8>) -> Self::Output {
(self.into_rational() / rhs).into()
(self.into_ratio() / rhs).into()
}
}

0 comments on commit 7ce5f8f

Please sign in to comment.