quintodrome/utils/random/number.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

25 lines
674 B
Go
Raw Permalink Normal View History

2024-05-11 16:04:21 -08:00
package random
import (
"crypto/rand"
2024-05-19 17:55:19 -08:00
"encoding/binary"
2024-05-11 16:04:21 -08:00
"math/big"
"github.com/navidrome/navidrome/utils/number"
2024-05-11 16:04:21 -08:00
)
2024-05-19 17:55:19 -08:00
// Int64N returns a random int64 between 0 and max.
// This is a reimplementation of math/rand/v2.Int64N using a cryptographically secure random number generator.
func Int64N[T number.Integer](max T) int64 {
rnd, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
2024-05-11 16:04:21 -08:00
return rnd.Int64()
}
2024-05-19 17:55:19 -08:00
// Uint64 returns a random uint64.
// This is a reimplementation of math/rand/v2.Uint64 using a cryptographically secure random number generator.
func Uint64() uint64 {
buffer := make([]byte, 8)
_, _ = rand.Read(buffer)
return binary.BigEndian.Uint64(buffer)
}