1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00
This commit is contained in:
2022-06-07 10:56:52 +08:00
parent 2728dcafeb
commit f36b4fabd6
7 changed files with 315 additions and 100 deletions

View File

@ -3,8 +3,7 @@ package rand
import (
"crypto/rand"
"io"
"math/big"
_ "unsafe"
"github.com/charlienet/go-mixed/bytesconv"
)
@ -20,7 +19,7 @@ const (
_ = allChars + "/+"
)
var rng = NewRandGenerator()
var rng = NewFastRandGenerator() // NewRandGenerator()
type charScope struct {
bytes []byte
@ -82,7 +81,11 @@ func (scope *charScope) Generate(length int) string {
}
type scopeConstraint interface {
~int | ~int32 | ~int64
~int | ~int32 | ~int64 | ~uint32
}
func Int[T scopeConstraint]() T {
return T(rng.Int31())
}
// 生成区间 n >= 0, n < max
@ -97,18 +100,6 @@ func IntRange[T scopeConstraint](min, max T) T {
return T(n + min)
}
func CryptoRange[T scopeConstraint](min, max T) T {
n := CryptoIntn(max - min)
return min + n
}
func CryptoIntn[T ~int | ~int32 | ~int64](max T) T {
b := big.NewInt(int64(max))
n, _ := rand.Int(rand.Reader, b)
return T(n.Int64())
}
func RandBytes(len int) ([]byte, error) {
r := make([]byte, len)
_, err := io.ReadFull(rand.Reader, r)