validate float for integer overflow (closes #11) and add missing min-bound

This commit is contained in:
Jaime Pillora 2017-02-22 11:19:28 +11:00
parent 72aa2af4f9
commit 06c7a16c84
1 changed files with 10 additions and 3 deletions

View File

@ -30,6 +30,8 @@ func (b *Backoff) Duration() time.Duration {
return d return d
} }
const maxInt64 = float64(math.MaxInt64 - 512)
// ForAttempt returns the duration for a specific attempt. This is useful if // 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 // you have a large number of independent Backoffs, but don't want use
// unnecessary memory storing the Backoff parameters per Backoff. The first // unnecessary memory storing the Backoff parameters per Backoff. The first
@ -51,7 +53,6 @@ func (b *Backoff) ForAttempt(attempt float64) time.Duration {
// short-circuit // short-circuit
return max return max
} }
factor := b.Factor factor := b.Factor
if factor <= 0 { if factor <= 0 {
factor = 2 factor = 2
@ -62,9 +63,15 @@ func (b *Backoff) ForAttempt(attempt float64) time.Duration {
if b.Jitter { if b.Jitter {
durf = rand.Float64()*(durf-minf) + minf durf = rand.Float64()*(durf-minf) + minf
} }
//ensure float64 wont overflow int64
if durf > maxInt64 {
return max
}
dur := time.Duration(durf) dur := time.Duration(durf)
if dur > max { //keep within bounds
//cap! if dur < min {
return min
} else if dur > max {
return max return max
} }
return dur return dur