Skip to content

Commit

Permalink
use math/rand/v2 for simpler random ints
Browse files Browse the repository at this point in the history
  • Loading branch information
majst01 committed Feb 15, 2024
1 parent 789c06c commit fe83e47
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 17 deletions.
9 changes: 2 additions & 7 deletions cmd/metal-api/internal/datastore/machine.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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 {
Expand Down
13 changes: 3 additions & 10 deletions cmd/metal-api/internal/grpc/boot-service-wait_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ package grpc

import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"math/big"
"math/rand/v2"
"strconv"
"sync"
"testing"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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())
}

0 comments on commit fe83e47

Please sign in to comment.