mirror of
https://github.com/rclone/rclone.git
synced 2025-08-09 21:57:59 +02:00
random: speed up String function for generating larger blocks
This commit is contained in:
@ -4,28 +4,35 @@ package random
|
||||
import (
|
||||
cryptorand "crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
mathrand "math/rand"
|
||||
"io"
|
||||
)
|
||||
|
||||
// StringFn create a random string for test purposes using the random
|
||||
// number generator function passed in.
|
||||
//
|
||||
// Do not use these for passwords.
|
||||
func StringFn(n int, randIntn func(n int) int) string {
|
||||
func StringFn(n int, randReader io.Reader) string {
|
||||
const (
|
||||
vowel = "aeiou"
|
||||
consonant = "bcdfghjklmnpqrstvwxyz"
|
||||
digit = "0123456789"
|
||||
)
|
||||
pattern := []string{consonant, vowel, consonant, vowel, consonant, vowel, consonant, digit}
|
||||
out := make([]byte, n)
|
||||
p := 0
|
||||
var (
|
||||
pattern = []string{consonant, vowel, consonant, vowel, consonant, vowel, consonant, digit}
|
||||
out = make([]byte, n)
|
||||
p = 0
|
||||
)
|
||||
_, err := io.ReadFull(randReader, out)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("internal error: failed to read from random reader: %v", err))
|
||||
}
|
||||
for i := range out {
|
||||
source := pattern[p]
|
||||
p = (p + 1) % len(pattern)
|
||||
out[i] = source[randIntn(len(source))]
|
||||
// this generation method means the distribution is slightly biased. However these
|
||||
// strings are not for passwords so this is deemed OK.
|
||||
out[i] = source[out[i]%byte(len(source))]
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
@ -34,7 +41,7 @@ func StringFn(n int, randIntn func(n int) int) string {
|
||||
//
|
||||
// Do not use these for passwords.
|
||||
func String(n int) string {
|
||||
return StringFn(n, mathrand.Intn)
|
||||
return StringFn(n, cryptorand.Reader)
|
||||
}
|
||||
|
||||
// Password creates a crypto strong password which is just about
|
||||
|
Reference in New Issue
Block a user