Closed dtolnay closed 5 years ago
I ended up the basic implementation of this : https://github.com/taiki-e/easytime
(I would like to confirm that there is not much difference from what this issue aims.)
Nice, looks good to me. I will close out this issue once your crate is published.
I filed https://github.com/taiki-e/easytime/issues/1 to consider adding example code.
Thanks, done: https://crates.io/crates/easytime
Excellent. I added a link to your crate from the readme.
The
std::time::Instant
andstd::time::Duration
types are quite tricky to use correctly for arithmetic because their arithmetic operators panic on overflow and their non-panicking methods are unergonomic.Consider a use case drawn from TURN_Hammer in which we receive untrusted input representing seconds and subsec-nanoseconds elapsed since some prearranged base instant, and we need to compute a value
rtt4
which is the duration elapsed since the untrusted moment. Naively the code would be:The problem is all three of the last three lines can panic in the face of untrusted input.
let since_base
panics if s + ns / 1e9 > u64::max_value();let remote_instant
panics on overflow;let rtt4
panics if remote_instant > now.The checked version of the same logic is harder to write and much less readable.
I would like a library that provides wrapper types for safely performing panic-free checked arithmetic on instants and durations such that the naive readable code is also secure: