Created
February 18, 2020 12:59
-
-
Save osmanyz/ccf07f756d2cd48101cc1a913131e837 to your computer and use it in GitHub Desktop.
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 helpers | |
| import ( | |
| "crypto/rand" | |
| "fmt" | |
| src "math/rand" | |
| "unsafe" | |
| ) | |
| const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
| 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 | |
| ) | |
| 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)) | |
| } | |
| func RandomBytes(n int) ([]byte, error) { | |
| token := make([]byte, n) | |
| _, err := rand.Read(token) | |
| if err != nil { | |
| return nil, fmt.Errorf("helpers/random: %s", err) | |
| } | |
| return token, nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment