About std Instant saturating operations

In the docs about std Instant it says the following about monotonicity and the current saturating behavior:

This workaround obscures programming errors where earlier and later instants are accidentally swapped. For this reason future rust versions may reintroduce panics.

What would be the mechanism through which the panics are reintroduced? I've written some code that was depending on this saturating behavior and I only recently realized this warning existed. I could go back and try to remove all assumptions of saturating behavior but I expect this to be very error prone since I'd have no evidence of having done so correctly.

It seems this change was introduced fairly recently in rust 1.60.

That would be the correct way to do it.

Yeah, you would have to have manual tests verifying the same.

Would a search-and-replace of some_instant.duration_since() with saturating_duration_since() like they suggest be enough? Or is this one of those things where your codebase is littered with instance_a - instance_b and you've got essentially no way of tracking them all down?

It is indeed the subtractions (which are not very grepable) that scare me the most. But, to be honest, it's doable in my case.

Truth is I was a bit in disbelief. If the contract is to not use the operations as if they saturate then the current state of Instant is asking for silent bugs to be written. The longer this stays as saturating, the more incorrect code will be written. I hope that if it's ever going to be switched back to panic it will happen soon.

To add to the confusion, Tokio Instant also switched to saturating operations, there's no warning on their documentation about the possibility of it switching back to non saturating.

1 Like

A Clippy lint should be able to catch those, right? (Not that I'm volunteering to write one :slight_smile:)

Yep.

There's a similar lint called manual_instant_elapsed which tells people to prefer other_instant.elapsed() over Instant::now() - other_instant.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.