id.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package idutil
  15. import (
  16. "math"
  17. "sync"
  18. "time"
  19. )
  20. const (
  21. tsLen = 5 * 8
  22. cntLen = 2 * 8
  23. suffixLen = tsLen + cntLen
  24. )
  25. // The initial id is in this format:
  26. // High order byte is memberID, next 5 bytes are from timestamp,
  27. // and low order 2 bytes are 0s.
  28. // | prefix | suffix |
  29. // | 1 byte | 5 bytes | 2 bytes |
  30. // | memberID | timestamp | cnt |
  31. //
  32. // The timestamp 5 bytes is different when the machine is restart
  33. // after 1 ms and before 35 years.
  34. //
  35. // It increases suffix to generate the next id.
  36. // The count field may overflow to timestamp field, which is intentional.
  37. // It helps to extend the event window to 2^56. This doesn't break that
  38. // id generated after restart is unique because etcd throughput is <<
  39. // 65536req/ms.
  40. type Generator struct {
  41. mu sync.Mutex
  42. // high order byte
  43. prefix uint64
  44. // low order 7 bytes
  45. suffix uint64
  46. }
  47. func NewGenerator(memberID uint8, now time.Time) *Generator {
  48. prefix := uint64(memberID) << suffixLen
  49. unixMilli := uint64(now.UnixNano()) / uint64(time.Millisecond/time.Nanosecond)
  50. suffix := lowbit(unixMilli, tsLen) << cntLen
  51. return &Generator{
  52. prefix: prefix,
  53. suffix: suffix,
  54. }
  55. }
  56. // Next generates a id that is unique.
  57. func (g *Generator) Next() uint64 {
  58. g.mu.Lock()
  59. defer g.mu.Unlock()
  60. g.suffix++
  61. id := g.prefix | lowbit(g.suffix, suffixLen)
  62. return id
  63. }
  64. func lowbit(x uint64, n uint) uint64 {
  65. return x & (math.MaxUint64 >> (64 - n))
  66. }