Last active
June 15, 2020 16:28
-
-
Save Fardinak/7a4c44cc396936026ac815d97825c172 to your computer and use it in GitHub Desktop.
Random string generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package randstr | |
import ( | |
"math/rand" | |
"time" | |
"unsafe" | |
) | |
// Randomness source | |
var src = rand.NewSource(time.Now().UnixNano()) | |
// Random string parameters | |
const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
const ( | |
letterIdxBits = 6 // 6 bits to represent a letter index | |
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits | |
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits | |
) | |
// RandomString generates a random string of size `n` | |
// Taken from https://stackoverflow.com/a/31832326/717221 | |
func RandomString(n int) string { | |
b := make([]byte, n) | |
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters! | |
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { | |
if remain == 0 { | |
cache, remain = src.Int63(), letterIdxMax | |
} | |
if idx := int(cache & letterIdxMask); idx < len(letterBytes) { | |
b[i] = letterBytes[idx] | |
i-- | |
} | |
cache >>= letterIdxBits | |
remain-- | |
} | |
return *(*string)(unsafe.Pointer(&b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment