From 06c7a16c845dc8e0bf575fafeeca0f5462f5eb4d Mon Sep 17 00:00:00 2001 From: Jaime Pillora Date: Wed, 22 Feb 2017 11:19:28 +1100 Subject: [PATCH] validate float for integer overflow (closes #11) and add missing min-bound --- backoff.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/backoff.go b/backoff.go index 9194612..a50d0e9 100644 --- a/backoff.go +++ b/backoff.go @@ -30,6 +30,8 @@ func (b *Backoff) Duration() time.Duration { return d } +const maxInt64 = float64(math.MaxInt64 - 512) + // ForAttempt returns the duration for a specific attempt. This is useful if // you have a large number of independent Backoffs, but don't want use // unnecessary memory storing the Backoff parameters per Backoff. The first @@ -51,7 +53,6 @@ func (b *Backoff) ForAttempt(attempt float64) time.Duration { // short-circuit return max } - factor := b.Factor if factor <= 0 { factor = 2 @@ -62,9 +63,15 @@ func (b *Backoff) ForAttempt(attempt float64) time.Duration { if b.Jitter { durf = rand.Float64()*(durf-minf) + minf } + //ensure float64 wont overflow int64 + if durf > maxInt64 { + return max + } dur := time.Duration(durf) - if dur > max { - //cap! + //keep within bounds + if dur < min { + return min + } else if dur > max { return max } return dur