Skip to content

Commit 1cb9a17

Browse files
authored
Impl multiplication and division for frequency wrappers (#193)
This allows the following operations: - T * u32 (T) - T *= u32 (T) - T / u32 (T) - T /= u32 (T) - T / T (u32)
1 parent 37d1a7b commit 1cb9a17

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1616

1717
- Extend the Pwm implementation to cover the full embedded_hal::Pwm API
1818
- Add `QeiOptions` struct to configure slave mode and auto reload value of QEI interface
19+
- Implement multiplication and division for frequency wrappers (#193)
1920

2021
### Changed
2122

src/time.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
//! assert_eq!(freq_khz, freq_mhz);
2828
//! ```
2929
30+
use core::ops;
3031
use cortex_m::peripheral::DWT;
3132

3233
use crate::rcc::Clocks;
@@ -181,6 +182,50 @@ impl Into<Hertz> for MicroSeconds {
181182
}
182183
}
183184

185+
/// Macro to implement arithmetic operations (e.g. multiplication, division)
186+
/// for wrapper types.
187+
macro_rules! impl_arithmetic {
188+
($wrapper:ty, $wrapped:ty) => {
189+
impl ops::Mul<$wrapped> for $wrapper {
190+
type Output = Self;
191+
fn mul(self, rhs: $wrapped) -> Self {
192+
Self(self.0 * rhs)
193+
}
194+
}
195+
196+
impl ops::MulAssign<$wrapped> for $wrapper {
197+
fn mul_assign(&mut self, rhs: $wrapped) {
198+
self.0 *= rhs;
199+
}
200+
}
201+
202+
impl ops::Div<$wrapped> for $wrapper {
203+
type Output = Self;
204+
fn div(self, rhs: $wrapped) -> Self {
205+
Self(self.0 / rhs)
206+
}
207+
}
208+
209+
impl ops::Div<$wrapper> for $wrapper {
210+
type Output = $wrapped;
211+
fn div(self, rhs: $wrapper) -> $wrapped {
212+
self.0 / rhs.0
213+
}
214+
}
215+
216+
impl ops::DivAssign<$wrapped> for $wrapper {
217+
fn div_assign(&mut self, rhs: $wrapped) {
218+
self.0 /= rhs;
219+
}
220+
}
221+
}
222+
}
223+
224+
impl_arithmetic!(Hertz, u32);
225+
impl_arithmetic!(KiloHertz, u32);
226+
impl_arithmetic!(MegaHertz, u32);
227+
impl_arithmetic!(Bps, u32);
228+
184229
/// A monotonic non-decreasing timer
185230
#[derive(Clone, Copy)]
186231
pub struct MonoTimer {

0 commit comments

Comments
 (0)