Skip to content

🎧 Your Personal Streaming Service

Add function number.RandomInt64

Deluan7fbcb2904a48
diff --git a/server/backgrounds/handler.go b/server/backgrounds/handler.go
index d081a6128..5f53e281f 100644
--- a/server/backgrounds/handler.go
+++ b/server/backgrounds/handler.go
@@ -2,10 +2,8 @@ package backgrounds
import (
"context"
- "crypto/rand"
"encoding/base64"
"errors"
- "math/big"
"net/http"
"net/url"
"path"
@@ -14,6 +12,7 @@ import (
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/utils/number"
"gopkg.in/yaml.v3"
)
@@ -52,8 +51,8 @@ func (h *Handler) getRandomImage(ctx context.Context) (string, error) {
if len(list) == 0 {
return "", errors.New("no images available")
}
- rnd, _ := rand.Int(rand.Reader, big.NewInt(int64(len(list))))
- return list[rnd.Int64()], nil
+ rnd := number.RandomInt64(int64(len(list)))
+ return list[rnd], nil
}
func (h *Handler) getImageList(ctx context.Context) ([]string, error) {
diff --git a/utils/number/number.go b/utils/number/number.go
index 2a5e21224..cc8aa7112 100644
--- a/utils/number/number.go
+++ b/utils/number/number.go
@@ -1,6 +1,11 @@
package number
-import "golang.org/x/exp/constraints"
+import (
+ "crypto/rand"
+ "math/big"
+
+ "golang.org/x/exp/constraints"
+)
func Min[T constraints.Ordered](vs ...T) T {
if len(vs) == 0 {
@@ -29,3 +34,8 @@ func Max[T constraints.Ordered](vs ...T) T {
}
return max
}
+
+func RandomInt64(max int64) int64 {
+ rnd, _ := rand.Int(rand.Reader, big.NewInt(max))
+ return rnd.Int64()
+}
diff --git a/utils/weighted_random_chooser.go b/utils/weighted_random_chooser.go
index e7e26cd85..0b4ab905b 100644
--- a/utils/weighted_random_chooser.go
+++ b/utils/weighted_random_chooser.go
@@ -1,9 +1,9 @@
package utils
import (
- "crypto/rand"
"errors"
- "math/big"
+
+ "github.com/navidrome/navidrome/utils/number"
)
type WeightedChooser struct {
@@ -41,9 +41,7 @@ func (w *WeightedChooser) weightedChoice() (int, error) {
if w.totalWeight == 0 {
return 0, errors.New("no choices available")
}
- rndBig, _ := rand.Int(rand.Reader, big.NewInt(int64(w.totalWeight)))
-
- rnd := rndBig.Int64()
+ rnd := number.RandomInt64(int64(w.totalWeight))
for i, weight := range w.weights {
rnd -= int64(weight)
if rnd < 0 {