nuid.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. // Copyright 2016-2019 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. // A unique identifier generator that is high performance, very fast, and tries to be entropy pool friendly.
  14. package nuid
  15. import (
  16. "crypto/rand"
  17. "fmt"
  18. "math"
  19. "math/big"
  20. "sync"
  21. "time"
  22. prand "math/rand"
  23. )
  24. // NUID needs to be very fast to generate and truly unique, all while being entropy pool friendly.
  25. // We will use 12 bytes of crypto generated data (entropy draining), and 10 bytes of sequential data
  26. // that is started at a pseudo random number and increments with a pseudo-random increment.
  27. // Total is 22 bytes of base 62 ascii text :)
  28. // Version of the library
  29. const Version = "1.0.1"
  30. const (
  31. digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  32. base = 62
  33. preLen = 12
  34. seqLen = 10
  35. maxSeq = int64(839299365868340224) // base^seqLen == 62^10
  36. minInc = int64(33)
  37. maxInc = int64(333)
  38. totalLen = preLen + seqLen
  39. )
  40. type NUID struct {
  41. pre []byte
  42. seq int64
  43. inc int64
  44. }
  45. type lockedNUID struct {
  46. sync.Mutex
  47. *NUID
  48. }
  49. // Global NUID
  50. var globalNUID *lockedNUID
  51. // Seed sequential random with crypto or math/random and current time
  52. // and generate crypto prefix.
  53. func init() {
  54. r, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
  55. if err != nil {
  56. prand.Seed(time.Now().UnixNano())
  57. } else {
  58. prand.Seed(r.Int64())
  59. }
  60. globalNUID = &lockedNUID{NUID: New()}
  61. globalNUID.RandomizePrefix()
  62. }
  63. // New will generate a new NUID and properly initialize the prefix, sequential start, and sequential increment.
  64. func New() *NUID {
  65. n := &NUID{
  66. seq: prand.Int63n(maxSeq),
  67. inc: minInc + prand.Int63n(maxInc-minInc),
  68. pre: make([]byte, preLen),
  69. }
  70. n.RandomizePrefix()
  71. return n
  72. }
  73. // Generate the next NUID string from the global locked NUID instance.
  74. func Next() string {
  75. globalNUID.Lock()
  76. nuid := globalNUID.Next()
  77. globalNUID.Unlock()
  78. return nuid
  79. }
  80. // Generate the next NUID string.
  81. func (n *NUID) Next() string {
  82. // Increment and capture.
  83. n.seq += n.inc
  84. if n.seq >= maxSeq {
  85. n.RandomizePrefix()
  86. n.resetSequential()
  87. }
  88. seq := n.seq
  89. // Copy prefix
  90. var b [totalLen]byte
  91. bs := b[:preLen]
  92. copy(bs, n.pre)
  93. // copy in the seq in base62.
  94. for i, l := len(b), seq; i > preLen; l /= base {
  95. i -= 1
  96. b[i] = digits[l%base]
  97. }
  98. return string(b[:])
  99. }
  100. // Resets the sequential portion of the NUID.
  101. func (n *NUID) resetSequential() {
  102. n.seq = prand.Int63n(maxSeq)
  103. n.inc = minInc + prand.Int63n(maxInc-minInc)
  104. }
  105. // Generate a new prefix from crypto/rand.
  106. // This call *can* drain entropy and will be called automatically when we exhaust the sequential range.
  107. // Will panic if it gets an error from rand.Int()
  108. func (n *NUID) RandomizePrefix() {
  109. var cb [preLen]byte
  110. cbs := cb[:]
  111. if nb, err := rand.Read(cbs); nb != preLen || err != nil {
  112. panic(fmt.Sprintf("nuid: failed generating crypto random number: %v\n", err))
  113. }
  114. for i := 0; i < preLen; i++ {
  115. n.pre[i] = digits[int(cbs[i])%base]
  116. }
  117. }