github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xstrings/random.go (about) 1 package xstrings 2 3 import ( 4 "crypto/rand" 5 "encoding/hex" 6 "math/big" 7 "strings" 8 ) 9 10 var randReader = rand.Reader 11 12 const RandomSet = "0123456789ABCDEF" 13 14 // Random creates new string based on strSet. It uses crypto/rand as the 15 // random number generator. error is the one returned by rand.Int 16 func Random(strSet string, length int) (string, error) { 17 if length == 0 || strSet == "" { 18 return "", nil 19 } 20 set := []rune(strSet) 21 bigLen := big.NewInt(int64(len(set))) 22 23 res := make([]rune, length) 24 for i := 0; i < length; i++ { 25 n, err := rand.Int(randReader, bigLen) 26 if err != nil { 27 return "", err 28 } 29 res[i] = set[n.Int64()] 30 } 31 32 return string(res), nil 33 } 34 35 // FastRandom creates new string with one read, this version is fast than the random version. 36 func FastRandom(n int) (string, error) { 37 i := n/2 + 1 38 buf := make([]byte, i) 39 _, err := rand.Read(buf) 40 if err != nil { 41 return "", err 42 } 43 str := hex.EncodeToString(buf) 44 if n%2 == 1 { 45 str = str[:len(str)-1] 46 } 47 return strings.ToUpper(str), nil 48 }