From 96d57e40e2731deaf6324377234952be51514596 Mon Sep 17 00:00:00 2001 From: Saeed Rasooli Date: Wed, 7 Feb 2024 20:53:58 +0330 Subject: [PATCH] switch to math/rand/v2 --- lib/init.go | 12 ------------ lib/lex_repeat.go | 4 ++-- lib/random.go | 11 +++-------- lib/utils_test.go | 6 +++--- 4 files changed, 8 insertions(+), 25 deletions(-) diff --git a/lib/init.go b/lib/init.go index cc62ee5..c574c85 100644 --- a/lib/init.go +++ b/lib/init.go @@ -1,17 +1,5 @@ package passgen -import ( - crypto_rand "crypto/rand" - "encoding/binary" - math_rand "math/rand" -) - func init() { - var b [8]byte - _, err := crypto_rand.Read(b[:]) - if err != nil { - panic("cannot seed math/rand package with cryptographically secure random number generator") - } - math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:]))) InitRomaji() } diff --git a/lib/lex_repeat.go b/lib/lex_repeat.go index 2b7045d..174a3b3 100644 --- a/lib/lex_repeat.go +++ b/lib/lex_repeat.go @@ -1,7 +1,7 @@ package passgen import ( - math_rand "math/rand" + math_rand "math/rand/v2" "strconv" "strings" ) @@ -138,5 +138,5 @@ func parseRepeatCount(s *State, countRunes []rune) (int64, error) { if maxCount > maxRepeatCount { return 0, s.errorSyntax("count value is too large") } - return minCount + math_rand.Int63n(maxCount-minCount+1), nil + return minCount + math_rand.Int64N(maxCount-minCount+1), nil } diff --git a/lib/random.go b/lib/random.go index 88c7de9..89f340c 100644 --- a/lib/random.go +++ b/lib/random.go @@ -3,7 +3,7 @@ package passgen import ( rand "crypto/rand" "encoding/binary" - math_rand "math/rand" + math_rand "math/rand/v2" ) // CryptoRandSource is a source for math/rand that uses more secure crypto/rand @@ -14,13 +14,8 @@ func NewRandSource() *math_rand.Rand { return math_rand.New(CryptoRandSource{}) } -// Int63 ... -func (CryptoRandSource) Int63() int64 { +func (CryptoRandSource) Uint64() uint64 { var b [8]byte rand.Read(b[:]) - // mask off sign bit to ensure positive number - return int64(binary.LittleEndian.Uint64(b[:]) & (1<<63 - 1)) + return binary.LittleEndian.Uint64(b[:]) } - -// Seed ... -func (CryptoRandSource) Seed(_ int64) {} diff --git a/lib/utils_test.go b/lib/utils_test.go index 3a4900f..0632be2 100644 --- a/lib/utils_test.go +++ b/lib/utils_test.go @@ -1,7 +1,7 @@ package passgen import ( - "math/rand" + math_rand "math/rand/v2" "testing" ) @@ -41,7 +41,7 @@ func Benchmark_removeDuplicateRunes(b *testing.B) { for i := 0; i < count; i++ { list := make([]rune, listLength) for j := 0; j < listLength; j++ { - list[j] = rune(rand.Intn(256)) + list[j] = rune(math_rand.Int32N(256)) } lists[i] = list } @@ -64,7 +64,7 @@ func Benchmark_excludeCharsASCII(b *testing.B) { for i := 0; i < count; i++ { list := make([]rune, listLength) for j := 0; j < listLength; j++ { - list[j] = rune(rand.Intn(256)) + list[j] = rune(math_rand.Int32N(256)) } lists[i] = list }