314. Duration::mul_f64 — timeout * 1.5 Doesn't Compile, So You Round-Tripped Through Floats
Duration * 2 compiles, Duration * 1.5 doesn’t — and the usual workaround tears the duration apart into an f64 just to build it back up again.
Duration implements Mul<u32>, so doubling a timeout is easy. But backoff factors are rarely whole numbers — the classic multiplier is 1.5 or 2.0-with-jitter, and that’s where the type checker stops you:
| |
The workaround everyone reaches for is the float round-trip:
| |
It works, but it’s noisy, and it funnels a perfectly good Duration through a lossy f64 in both directions.
Multiply the duration directly
mul_f64 (and div_f64) have been on Duration since Rust 1.38 — they do the scaling in one call and keep nanosecond precision:
| |
Which makes an exponential backoff loop read exactly like the algorithm:
| |
One caveat carried over from float land: mul_f64 panics if the factor produces a negative, non-finite, or overflowing result — the same failure mode as from_secs_f64 in bite 311. If your factor comes from untrusted math (jitter that can dip negative), clamp it first or go through Duration::try_from_secs_f64.
That closes out the week’s Duration tour: 311 built one from a float safely, 312 subtracted without panicking, 313 divided two of them — and today’s bite scales one without leaving the type.