Skip to content

Commit

Permalink
feat: user crypto rand (#30)
Browse files Browse the repository at this point in the history
Co-authored-by: Dmitry Selivanov <[email protected]>
  • Loading branch information
dmitriyselivanov and dmitriyselivanov authored Jul 12, 2024
1 parent ab173c1 commit 40ed2d8
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions namegen/namegen.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package namegen

import (
"math/rand"
"crypto/rand"
"math/big"
"strings"
"time"
)

var r = rand.New(rand.NewSource(time.Now().UnixNano()))

// NewName generates a name that is strictly less than 25 chars
func NewName() string {
sb := strings.Builder{}
Expand All @@ -22,5 +20,15 @@ func NewName() string {

// oneOf selects a random element from a list.
func oneOf[T any](list []T) T {
return list[r.Intn(len(list))]
if len(list) <= 0 {
var zero T
return zero
}

maxVal := big.NewInt(int64(len(list)))
// don't need to check err there, it only occurs if maxVal <= 0
// but this case is handled in return above
randomBigInt, _ := rand.Int(rand.Reader, maxVal)

return list[int(randomBigInt.Int64())]
}

0 comments on commit 40ed2d8

Please sign in to comment.