Skip to content

Instantly share code, notes, and snippets.

@bagasdisini
Last active June 7, 2024 06:31
Show Gist options
  • Save bagasdisini/eb0b67352b93cb739795101a08926bf0 to your computer and use it in GitHub Desktop.
Save bagasdisini/eb0b67352b93cb739795101a08926bf0 to your computer and use it in GitHub Desktop.
Randomize string with the most efficient way
func RandomString(n int) string {
src := rand.NewSource(time.Now().UnixNano())
const str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var letterIdxBits int64 = 6
var letterIdxMask int64 = 1<<letterIdxBits - 1
letterIdxMax := 63 / letterIdxBits
b := make([]byte, n)
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(str) {
b[i] = str[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return *(*string)(unsafe.Pointer(&b))
}
@bagasdisini
Copy link
Author

Source : stackoverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment