Skip to content

Commit

Permalink
Simplify random.Int64 usage with generics
Browse files Browse the repository at this point in the history
  • Loading branch information
deluan committed May 12, 2024
1 parent 0ae2944 commit 3463d0c
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 5 deletions.
2 changes: 1 addition & 1 deletion model/share.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func (s Share) CoverArtID() ArtworkID {
case "artist":
return Artist{ID: ids[0]}.CoverArtID()
}
rnd := random.Int64(int64(len(s.Tracks)))
rnd := random.Int64(len(s.Tracks))
return s.Tracks[rnd].CoverArtID()
}

Expand Down
2 changes: 1 addition & 1 deletion server/backgrounds/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func (h *Handler) getRandomImage(ctx context.Context) (string, error) {
if len(list) == 0 {
return "", errors.New("no images available")
}
rnd := random.Int64(int64(len(list)))
rnd := random.Int64(len(list))
return list[rnd], nil
}

Expand Down
6 changes: 4 additions & 2 deletions utils/random/number.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package random
import (
"crypto/rand"
"math/big"

"golang.org/x/exp/constraints"
)

func Int64(max int64) int64 {
rnd, _ := rand.Int(rand.Reader, big.NewInt(max))
func Int64[T constraints.Integer](max T) int64 {
rnd, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
return rnd.Int64()
}
2 changes: 1 addition & 1 deletion utils/random/weighted_random_chooser.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (w *WeightedChooser) weightedChoice() (int, error) {
if w.totalWeight == 0 {
return 0, errors.New("no choices available")
}
rnd := Int64(int64(w.totalWeight))
rnd := Int64(w.totalWeight)
for i, weight := range w.weights {
rnd -= int64(weight)
if rnd < 0 {
Expand Down

0 comments on commit 3463d0c

Please sign in to comment.