SHARE
TWEET

Untitled

a guest Jul 17th, 2017 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456"
  2. const (
  3.     letterIdxBits = 6                    // 6 bits to represent a letter index
  4.     letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
  5.     letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
  6. )
  7.  
  8. var src = rand.NewSource(time.Now().UnixNano())
  9.  
  10. func random(n int) string {
  11.     b := make([]byte, n)
  12.     // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
  13.     for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
  14.         if remain == 0 {
  15.             cache, remain = src.Int63(), letterIdxMax
  16.         }
  17.         if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
  18.             b[i] = letterBytes[idx]
  19.             i--
  20.         }
  21.         cache >>= letterIdxBits
  22.         remain--
  23.     }
  24.  
  25.     return string(b)
  26. }
RAW Paste Data
Top