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

Comparing durations -- operations not symmetric #82

Closed korken89 closed 3 years ago

korken89 commented 3 years ago

Hi!

I have been trying to port to this library but I seem to get into some unergonomic issues that I feel like should be straight forward. I think I am doing something wrong, and what I am doing is eg:

let last_now = some_clock.try_now().unwrap();
// Some time passes...
let now = some_clock.try_now().unwrap();

if matches!(now.checked_duration_since(&last_now), Some(d) if d > Seconds(5)) {
    // Do something...
}

I have issues with finding a way to get these kinds of conversions to pass. How would one do this?

korken89 commented 3 years ago

Now after experimenting I am still not able to compare durations, but I found other "paper cuts" that I think is good feed back for the future development of this library. It's a great start, however I think the ease-of-use can have some improvements. :)

I'd expect to have 2 extension traits on top of Clock:

  1. InfiniteClock, which is a trait that for all intensive purposes are infinite (like extending a timer to 64 bits which makes them overflow in like 400 years). Here I'd expect a nicer duration calculation interface, or simple Sub to work with panicing semantics on top of the checked_duration_since.
  2. InfallibleClock, which would add a now API that is infallible.

These would combine into the following maximum ease of use API, which if misused would panic on first use:

if my_clock.now() - last_time > 3.seconds() {
    // ...
}

Ping me if you want to have some discussion! :)

korken89 commented 3 years ago

More experimentation, it seems that the functionality is here, just asymmetrically implemented?

I found that the following works:

now > last_now + 3.seconds() // OK

However none of the following works:

now >  3.seconds() + last_now // FAIL 1
now - last_now >  3.seconds() // FAIL 2
now - 3.seconds() > last_now  // FAIL 3

All which are just symmetric transforms of OK

PTaylor-us commented 3 years ago

Thank you for finding the root issue. That rings a bell that I didn't figure out how to make some of the operations symmetric. I will definitely dig into that when I have a chance.

korken89 commented 3 years ago

I'll also have a look at it, seems like it should be straight forward for me to expand this.

korken89 commented 3 years ago

PR with fix is up