diff --git a/CHANGELOG.md b/CHANGELOG.md index 322c5076..72610d28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Extend the Pwm implementation to cover the full embedded_hal::Pwm API - Add `QeiOptions` struct to configure slave mode and auto reload value of QEI interface +- Implement multiplication and division for frequency wrappers (#193) ### Changed diff --git a/src/time.rs b/src/time.rs index a1af4788..c4496e41 100644 --- a/src/time.rs +++ b/src/time.rs @@ -27,6 +27,7 @@ //! assert_eq!(freq_khz, freq_mhz); //! ``` +use core::ops; use cortex_m::peripheral::DWT; use crate::rcc::Clocks; @@ -181,6 +182,50 @@ impl Into for MicroSeconds { } } +/// Macro to implement arithmetic operations (e.g. multiplication, division) +/// for wrapper types. +macro_rules! impl_arithmetic { + ($wrapper:ty, $wrapped:ty) => { + impl ops::Mul<$wrapped> for $wrapper { + type Output = Self; + fn mul(self, rhs: $wrapped) -> Self { + Self(self.0 * rhs) + } + } + + impl ops::MulAssign<$wrapped> for $wrapper { + fn mul_assign(&mut self, rhs: $wrapped) { + self.0 *= rhs; + } + } + + impl ops::Div<$wrapped> for $wrapper { + type Output = Self; + fn div(self, rhs: $wrapped) -> Self { + Self(self.0 / rhs) + } + } + + impl ops::Div<$wrapper> for $wrapper { + type Output = $wrapped; + fn div(self, rhs: $wrapper) -> $wrapped { + self.0 / rhs.0 + } + } + + impl ops::DivAssign<$wrapped> for $wrapper { + fn div_assign(&mut self, rhs: $wrapped) { + self.0 /= rhs; + } + } + } +} + +impl_arithmetic!(Hertz, u32); +impl_arithmetic!(KiloHertz, u32); +impl_arithmetic!(MegaHertz, u32); +impl_arithmetic!(Bps, u32); + /// A monotonic non-decreasing timer #[derive(Clone, Copy)] pub struct MonoTimer {