From fe83e474436bcd237084996fd01541fb2b1b5f78 Mon Sep 17 00:00:00 2001 From: Stefan Majer Date: Thu, 15 Feb 2024 11:22:50 +0100 Subject: [PATCH] use math/rand/v2 for simpler random ints --- cmd/metal-api/internal/datastore/machine.go | 9 ++------- .../grpc/boot-service-wait_integration_test.go | 13 +++---------- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/cmd/metal-api/internal/datastore/machine.go b/cmd/metal-api/internal/datastore/machine.go index 4975ad037..1b8af67b1 100644 --- a/cmd/metal-api/internal/datastore/machine.go +++ b/cmd/metal-api/internal/datastore/machine.go @@ -1,11 +1,10 @@ package datastore import ( - "crypto/rand" "errors" "fmt" "math" - "math/big" + "math/rand/v2" "github.com/metal-stack/metal-api/cmd/metal-api/internal/metal" "golang.org/x/exp/slices" @@ -636,11 +635,7 @@ func randomIndex(max int) int { if max <= 0 { return 0 } - - b, _ := rand.Int(rand.Reader, big.NewInt(int64(max))) - idx := int(b.Uint64()) - - return idx + return rand.N(max) } func intersect[T comparable](a, b []T) []T { diff --git a/cmd/metal-api/internal/grpc/boot-service-wait_integration_test.go b/cmd/metal-api/internal/grpc/boot-service-wait_integration_test.go index 3a306e11f..1ac45ed12 100644 --- a/cmd/metal-api/internal/grpc/boot-service-wait_integration_test.go +++ b/cmd/metal-api/internal/grpc/boot-service-wait_integration_test.go @@ -5,11 +5,10 @@ package grpc import ( "context" - "crypto/rand" "errors" "fmt" "io" - "math/big" + "math/rand/v2" "strconv" "sync" "testing" @@ -254,7 +253,7 @@ func (t *test) startMachineInstances() { } for i := range t.numberMachineInstances { machineID := strconv.Itoa(i) - port := 50005 + t.randNumber(t.numberApiInstances) + port := 50005 + rand.N(t.numberApiInstances) ctx, cancel := context.WithCancel(context.Background()) conn, err := grpc.DialContext(ctx, fmt.Sprintf("localhost:%d", port), opts...) require.NoError(t, err) @@ -328,7 +327,7 @@ func (t *test) allocateMachines() { } func (t *test) selectMachine(except []string) string { - machineID := strconv.Itoa(t.randNumber(t.numberMachineInstances)) + machineID := strconv.Itoa(rand.N(t.numberMachineInstances)) for _, id := range except { if id == machineID { return t.selectMachine(except) @@ -342,9 +341,3 @@ func (t *test) simulateNsqNotifyAllocated(machineID string) { s.allocate <- machineID } } - -func (t *test) randNumber(n int) int { - nBig, err := rand.Int(rand.Reader, big.NewInt(int64(n))) - require.NoError(t, err) - return int(nBig.Int64()) -}