You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.2 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package rand
  2. import (
  3. mrand "math/rand"
  4. )
  5. const (
  6. strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters
  7. )
  8. // Str constructs a random alphanumeric string of given length
  9. // from math/rand's global default Source.
  10. func Str(length int) string { return buildString(length, mrand.Int63) }
  11. // StrFromSource produces a random string of a specified length from
  12. // the specified random source.
  13. func StrFromSource(r *mrand.Rand, length int) string { return buildString(length, r.Int63) }
  14. func buildString(length int, picker func() int64) string {
  15. if length <= 0 {
  16. return ""
  17. }
  18. chars := make([]byte, 0, length)
  19. for {
  20. val := picker()
  21. for i := 0; i < 10; i++ {
  22. v := int(val & 0x3f) // rightmost 6 bits
  23. if v >= 62 { // only 62 characters in strChars
  24. val >>= 6
  25. continue
  26. } else {
  27. chars = append(chars, strChars[v])
  28. if len(chars) == length {
  29. return string(chars)
  30. }
  31. val >>= 6
  32. }
  33. }
  34. }
  35. }
  36. // Bytes returns n random bytes generated from math/rand's global default Source.
  37. func Bytes(n int) []byte {
  38. bs := make([]byte, n)
  39. for i := 0; i < len(bs); i++ {
  40. // nolint:gosec // G404: Use of weak random number generator
  41. bs[i] = byte(mrand.Int() & 0xFF)
  42. }
  43. return bs
  44. }