mirror of
https://github.com/fluencelabs/tendermint
synced 2025-06-03 16:41:19 +00:00
RandStr() is base62
This commit is contained in:
parent
92ea6c626f
commit
ca159b2726
@ -1,12 +1,33 @@
|
|||||||
package common
|
package common
|
||||||
|
|
||||||
import "crypto/rand"
|
import (
|
||||||
|
"math/rand"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters
|
||||||
|
)
|
||||||
|
|
||||||
|
// Construts an alphanumeric string of given length.
|
||||||
func RandStr(length int) string {
|
func RandStr(length int) string {
|
||||||
b := make([]byte, length)
|
chars := []byte{}
|
||||||
_, err := rand.Read(b)
|
MAIN_LOOP:
|
||||||
if err != nil {
|
for {
|
||||||
return ""
|
val := rand.Int63()
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
v := int(val & 0x3f) // rightmost 6 bits
|
||||||
|
if v >= 62 { // only 62 characters in strChars
|
||||||
|
val >>= 6
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
chars = append(chars, strChars[v])
|
||||||
|
if len(chars) == length {
|
||||||
|
break MAIN_LOOP
|
||||||
|
}
|
||||||
|
val >>= 6
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return string(b)
|
|
||||||
|
return string(chars)
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user