Skip to content

Commit

Permalink
Impl multiplication and division for frequency wrappers (#193)
Browse files Browse the repository at this point in the history
This allows the following operations:

- T * u32 (T)
- T *= u32 (T)
- T / u32 (T)
- T /= u32 (T)
- T / T (u32)
  • Loading branch information
dbrgn authored Apr 9, 2020
1 parent 37d1a7b commit 1cb9a17
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
45 changes: 45 additions & 0 deletions src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
//! assert_eq!(freq_khz, freq_mhz);
//! ```
use core::ops;
use cortex_m::peripheral::DWT;

use crate::rcc::Clocks;
Expand Down Expand Up @@ -181,6 +182,50 @@ impl Into<Hertz> 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 {
Expand Down

0 comments on commit 1cb9a17

Please sign in to comment.