Add function number.RandomInt64

This commit is contained in:
Deluan 2023-01-13 21:40:24 -05:00
parent 7a617d3a1d
commit 7fbcb2904a
3 changed files with 17 additions and 10 deletions

View File

@ -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) {

View File

@ -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()
}

View File

@ -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 {