Remove go type limits constants

They can be retrieved directly from the std math package.
Slightly optimize the Fib functions and improve comments.
This commit is contained in:
ionutboangiu
2024-08-29 14:10:14 +03:00
committed by Dan Christian Bogos
parent e863c63db2
commit aa5069e16e
4 changed files with 20 additions and 16 deletions

View File

@@ -21,6 +21,7 @@ package analyzers
import (
"encoding/json"
"fmt"
"math"
"math/rand"
"os"
"path"
@@ -154,7 +155,7 @@ func (aS *AnalyzerS) V1StringQuery(ctx *context.Context, args *QueryArgs, reply
} else {
q = bleve.NewQueryStringQuery(args.HeaderFilters)
}
s := bleve.NewSearchRequestOptions(q, utils.AbsoluteMaxInt, 0, false)
s := bleve.NewSearchRequestOptions(q, math.MaxInt, 0, false)
s.Fields = []string{utils.Meta} // return all fields
searchResults, err := aS.db.SearchInContext(ctx, s)
if err != nil {

View File

@@ -2794,15 +2794,6 @@ const (
ToNearestTowardZero = "*toNearestTowardZero"
)
// 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

@@ -429,8 +429,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 {
a, b = b, a+b // only increment Fibonacci numbers while b doesn't overflow
a, b = b, a+b
// Prevent int overflow by keeping b as the maximum valid Fibonacci number.
if b < a {
b = a
}
return a
}
@@ -442,11 +445,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
}

View File

@@ -20,6 +20,7 @@ package utils
import (
"errors"
"fmt"
"math"
"reflect"
"sync"
"testing"
@@ -1585,10 +1586,14 @@ 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>", math.MaxInt, rcv)
}
}
func TestUnzip(t *testing.T) {