55 "fmt"
66 "math"
77 "math/big"
8+ randv2 "math/rand/v2"
89 "strings"
910)
1011
@@ -16,7 +17,19 @@ const (
1617 DefaultLength = 10
1718)
1819
19- func Number () (int64 , error ) {
20+ // Int returns a pseudo-random integer
21+ func Int () int {
22+ return randv2 .Int ()
23+ }
24+
25+ // Int64 returns a pseudo-random 63-bit integer
26+ func Int64 () int64 {
27+ return randv2 .Int64 ()
28+ }
29+
30+ // SecureNumber returns a cryptographically secure random number.
31+ // Note: This function is significantly slower than Int() and Int64() due to the use of crypto/rand.
32+ func SecureNumber () (int64 , error ) {
2033 n , err := rand .Int (rand .Reader , big .NewInt (math .MaxInt64 ))
2134 if err != nil {
2235 return 0 , fmt .Errorf ("failed to generate random number: %w" , err )
@@ -25,7 +38,7 @@ func Number() (int64, error) {
2538 return n .Int64 (), nil
2639}
2740
28- // NumberInRange generates a random number between min and max
41+ // NumberInRange generates a pseudo- random number between min and max
2942func NumberInRange (min , max int64 ) (int64 , error ) {
3043 if min > max {
3144 return 0 , fmt .Errorf ("min (%d) cannot be greater than max (%d)" , min , max )
@@ -41,13 +54,10 @@ func NumberInRange(min, max int64) (int64, error) {
4154 limit := math .MaxInt64 - (math .MaxInt64 % rangeSize )
4255
4356 for {
44- n , err := rand .Int (rand .Reader , big .NewInt (math .MaxInt64 ))
45- if err != nil {
46- return 0 , fmt .Errorf ("failed to generate random number in range: %w" , err )
47- }
57+ n := randv2 .Int64N (math .MaxInt64 )
4858
49- if n . Int64 () < limit {
50- return min + (n . Int64 () % rangeSize ), nil
59+ if n < limit {
60+ return min + (n % rangeSize ), nil
5161 }
5262 // If we're above the limit, try again to ensure uniform distribution
5363 }
@@ -107,14 +117,10 @@ func StringWithCharset(length int, charset string) (string, error) {
107117 }
108118
109119 result := make ([]byte , length )
110- charsetLength := big .NewInt (int64 (len (trimmedCharset )))
111120
112- for i := 0 ; i < length ; i ++ {
113- n , err := rand .Int (rand .Reader , charsetLength )
114- if err != nil {
115- return "" , fmt .Errorf ("failed to generate random string: %w" , err )
116- }
117- result [i ] = trimmedCharset [n .Int64 ()]
121+ for i := range length {
122+ n := randv2 .Int64N (int64 (len (trimmedCharset )))
123+ result [i ] = trimmedCharset [n ]
118124 }
119125
120126 return string (result ), nil
0 commit comments