Skip to content

🎧 Your Personal Streaming Service

Simplify random.Int64 usage with generics

Deluan3463d0c208e7
diff --git a/model/share.go b/model/share.go
index d1415a585..3a18bed11 100644
--- a/model/share.go
+++ b/model/share.go
@@ -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()
}
diff --git a/server/backgrounds/handler.go b/server/backgrounds/handler.go
index 2d5af0bbb..76297f2ee 100644
--- a/server/backgrounds/handler.go
+++ b/server/backgrounds/handler.go
@@ -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
}
diff --git a/utils/random/number.go b/utils/random/number.go
index 68b04da79..5ecb816e2 100644
--- a/utils/random/number.go
+++ b/utils/random/number.go
@@ -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()
}
diff --git a/utils/random/weighted_random_chooser.go b/utils/random/weighted_random_chooser.go
index f5f1a3117..ca6dbeadb 100644
--- a/utils/random/weighted_random_chooser.go
+++ b/utils/random/weighted_random_chooser.go
@@ -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 {