id.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2015 The etcd Authors
  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 implements utility functions for generating unique,
  15. // randomized ids.
  16. package idutil
  17. import (
  18. "math"
  19. "sync/atomic"
  20. "time"
  21. )
  22. const (
  23. tsLen = 5 * 8
  24. cntLen = 8
  25. suffixLen = tsLen + cntLen
  26. )
  27. // Generator generates unique identifiers based on counters, timestamps, and
  28. // a node member ID.
  29. //
  30. // The initial id is in this format:
  31. // High order 2 bytes are from memberID, next 5 bytes are from timestamp,
  32. // and low order one byte is a counter.
  33. // | prefix | suffix |
  34. // | 2 bytes | 5 bytes | 1 byte |
  35. // | memberID | timestamp | cnt |
  36. //
  37. // The timestamp 5 bytes is different when the machine is restart
  38. // after 1 ms and before 35 years.
  39. //
  40. // It increases suffix to generate the next id.
  41. // The count field may overflow to timestamp field, which is intentional.
  42. // It helps to extend the event window to 2^56. This doesn't break that
  43. // id generated after restart is unique because etcd throughput is <<
  44. // 256req/ms(250k reqs/second).
  45. type Generator struct {
  46. // high order 2 bytes
  47. prefix uint64
  48. // low order 6 bytes
  49. suffix uint64
  50. }
  51. func NewGenerator(memberID uint16, now time.Time) *Generator {
  52. prefix := uint64(memberID) << suffixLen
  53. unixMilli := uint64(now.UnixNano()) / uint64(time.Millisecond/time.Nanosecond)
  54. suffix := lowbit(unixMilli, tsLen) << cntLen
  55. return &Generator{
  56. prefix: prefix,
  57. suffix: suffix,
  58. }
  59. }
  60. // Next generates a id that is unique.
  61. func (g *Generator) Next() uint64 {
  62. suffix := atomic.AddUint64(&g.suffix, 1)
  63. id := g.prefix | lowbit(suffix, suffixLen)
  64. return id
  65. }
  66. func lowbit(x uint64, n uint) uint64 {
  67. return x & (math.MaxUint64 >> (64 - n))
  68. }