id.go 2.1 KB

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