You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool/nrandom/string.go

51 lines
1.2 KiB
Go

1 year ago
package nrandom
import (
"math/rand"
"time"
"unsafe"
)
// Random generate a random string based on given string range.
func Random(letters string, length int) string {
b := make([]byte, length)
r := rand.NewSource(time.Now().UnixNano())
for i, cache, remain := length-1, r.Int63(), letterIdMax; i >= 0; {
if remain == 0 {
cache, remain = r.Int63(), letterIdMax
}
if idx := int(cache & letterIdMask); idx < len(letters) {
b[i] = letters[idx]
i--
}
cache >>= letterIdBits
remain--
}
return *(*string)(unsafe.Pointer(&b))
}
// RandString generate random string of specified length.
func RandString(length int) string {
return Random(Letters, length)
}
// RandStrUpper generate a random upper case string.
func RandStrUpper(length int) string {
return Random(UpperLetters, length)
}
// RandStrLower generate a random lower case string.
func RandStrLower(length int) string {
return Random(LowerLetters, length)
}
// RandNumeralStr generate a random numeral string of specified length.
func RandNumeralStr(length int) string {
return Random(Numeral, length)
}
// RandNumeralOrLetter generate a random numeral or letter string.
func RandNumeralOrLetter(length int) string {
return Random(Numeral+Letters, length)
}