Fix issue where fib function overflows

This commit is contained in:
ionutboangiu
2022-07-28 17:00:26 +03:00
committed by Dan Christian Bogos
parent c875f8b767
commit 7003a2457d
2 changed files with 18 additions and 2 deletions

View File

@@ -2784,6 +2784,15 @@ const (
HSuffix = "h"
)
// Go type limits
const (
AbsoluteMaxUint = ^uint(0)
AbsoluteMinUint = 0
AbsoluteMaxInt = int(AbsoluteMaxUint >> 1)
AbsoluteMinInt = -AbsoluteMaxInt - 1
AbsoluteMaxDuration = time.Duration(AbsoluteMaxInt)
)
func buildCacheInstRevPrefixes() {
CachePrefixToInstance = make(map[string]string)
for k, v := range CacheInstanceToPrefix {

View File

@@ -483,7 +483,9 @@ func copyFile(rc io.ReadCloser, path string, fm os.FileMode) (err error) {
func Fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
if b > 0 {
a, b = b, a+b
}
return a
}
}
@@ -493,7 +495,12 @@ func Fib() func() int {
func FibDuration(durationUnit, maxDuration time.Duration) func() time.Duration {
fib := Fib()
return func() time.Duration {
fibNrAsDuration := time.Duration(fib()) * durationUnit
fibNrAsDuration := time.Duration(fib())
if fibNrAsDuration > (AbsoluteMaxDuration / durationUnit) { // check if the current fibonacci nr. in the sequence would exceed the absolute maximum duration if multiplied by the duration unit value
fibNrAsDuration = AbsoluteMaxDuration
} else {
fibNrAsDuration *= durationUnit
}
if maxDuration > 0 && maxDuration < fibNrAsDuration {
return maxDuration
}