random.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package stringx
  2. import (
  3. crand "crypto/rand"
  4. "fmt"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. )
  9. const (
  10. letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  11. letterIdxBits = 6 // 6 bits to represent a letter index
  12. idLen = 8
  13. defaultRandLen = 8
  14. letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
  15. letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
  16. )
  17. var src = newLockedSource(time.Now().UnixNano())
  18. type lockedSource struct {
  19. source rand.Source
  20. lock sync.Mutex
  21. }
  22. func newLockedSource(seed int64) *lockedSource {
  23. return &lockedSource{
  24. source: rand.NewSource(seed),
  25. }
  26. }
  27. func (ls *lockedSource) Int63() int64 {
  28. ls.lock.Lock()
  29. defer ls.lock.Unlock()
  30. return ls.source.Int63()
  31. }
  32. func (ls *lockedSource) Seed(seed int64) {
  33. ls.lock.Lock()
  34. defer ls.lock.Unlock()
  35. ls.source.Seed(seed)
  36. }
  37. func Rand() string {
  38. return Randn(defaultRandLen)
  39. }
  40. func RandId() string {
  41. b := make([]byte, idLen)
  42. _, err := crand.Read(b)
  43. if err != nil {
  44. return Randn(idLen)
  45. }
  46. return fmt.Sprintf("%x%x%x%x", b[0:2], b[2:4], b[4:6], b[6:8])
  47. }
  48. func Randn(n int) string {
  49. b := make([]byte, n)
  50. // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
  51. for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
  52. if remain == 0 {
  53. cache, remain = src.Int63(), letterIdxMax
  54. }
  55. if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
  56. b[i] = letterBytes[idx]
  57. i--
  58. }
  59. cache >>= letterIdxBits
  60. remain--
  61. }
  62. return string(b)
  63. }
  64. func Seed(seed int64) {
  65. src.Seed(seed)
  66. }