FluenTech / embedded-time

Time(ing) library (Instant/Duration/Clock/Timer/Period/Frequency) for bare-metal embedded systems
Apache License 2.0
87 stars 17 forks source link

Calculating ratios is awkward and fragile #126

Open berkowski opened 2 years ago

berkowski commented 2 years ago

I often need to calculate the ratio of two values with the same units. For example,

let a = Kilohertz(200u32);
let b = Kilohertz(100u32);

// I'd like to do this
let ratio = a / b;

// Instead I need to do this:
let ratio = a.0 / b.0

The workaround is fragile. What happens if the code changes:

let a = Hertz(200u32);
let b = Kilohertz(100u32);

// This line is now incorrect without changing
let ratio = a.0 / b.0

Having to pull the underlying value out of the type defeats the whole purpose of having these unit types to begin with. Am I missing something? Is there a more 'correct' way to calculate the ratio?

I thought the limitation would be in the Fractional struct, but I see it's just a wrapper around num_rational::Rational. Why not just use the upstream structure instead? It supports arithmetic ops already.