Skip to content

Commit

Permalink
Remove go type limits constants
Browse files Browse the repository at this point in the history
They can be retrieved directly from the std math package.
Slightly optimize the Fib functions and improve comments.
  • Loading branch information
ionutboangiu authored and danbogos committed Nov 8, 2023
1 parent 9771377 commit a30e261
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 16 deletions.
9 changes: 0 additions & 9 deletions utils/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -2840,15 +2840,6 @@ 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 {
Expand Down
15 changes: 11 additions & 4 deletions utils/coreutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -484,8 +484,11 @@ func copyFile(rc io.ReadCloser, path string, fm os.FileMode) (err error) {
func Fib() func() int {
a, b := 0, 1
return func() int {
if b > 0 { // only increment Fibonacci numbers while b doesn't overflow
a, b = b, a+b
a, b = b, a+b

// Prevent int overflow by keeping b as the maximum valid Fibonacci number.
if b < a {
b = a
}
return a
}
Expand All @@ -497,11 +500,15 @@ func FibDuration(durationUnit, maxDuration time.Duration) func() time.Duration {
fib := Fib()
return func() time.Duration {
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

// Handle potential overflow when multiplying by durationUnit.
if fibNrAsDuration > (math.MaxInt / durationUnit) {
fibNrAsDuration = math.MaxInt
} else {
fibNrAsDuration *= durationUnit
}

// Cap the duration to maxDuration if specified.
if maxDuration > 0 && maxDuration < fibNrAsDuration {
return maxDuration
}
Expand Down
6 changes: 3 additions & 3 deletions utils/coreutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1872,12 +1872,12 @@ func TestCoreUtilsFibDurationSeqNrOverflow(t *testing.T) {
fib()
}
for i := 0; i < 100; i++ {
if rcv := fib(); rcv != AbsoluteMaxDuration {
t.Errorf("expected: <%+v>, \nreceived: <%+v>", AbsoluteMaxDuration, rcv)
if rcv := fib(); rcv != math.MaxInt {
t.Errorf("expected: <%+v>, \nreceived: <%+v>", math.MaxInt, rcv)
}
}
fib = FibDuration(time.Second, 6)
if rcv := fib(); rcv != 6 {
t.Errorf("expected: <%+v>, \nreceived: <%+v>", AbsoluteMaxDuration, rcv)
t.Errorf("expected: <%+v>, \nreceived: <%+v>", math.MaxInt, rcv)
}
}

0 comments on commit a30e261

Please sign in to comment.