1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.baidu.fsg.uid;
17
18 import org.apache.commons.lang.builder.ToStringBuilder;
19 import org.apache.commons.lang.builder.ToStringStyle;
20 import org.springframework.util.Assert;
21
22
23
24
25
26
27
28 public class BitsAllocator {
29
30
31
32 public static final int TOTAL_BITS = 1 << 6;
33
34
35
36
37 private int signBits = 1;
38 private final int timestampBits;
39 private final int workerIdBits;
40 private final int sequenceBits;
41
42
43
44
45 private final long maxDeltaSeconds;
46 private final long maxWorkerId;
47 private final long maxSequence;
48
49
50
51
52 private final int timestampShift;
53 private final int workerIdShift;
54
55
56
57
58
59 public BitsAllocator(int timestampBits, int workerIdBits, int sequenceBits) {
60
61 int allocateTotalBits = signBits + timestampBits + workerIdBits + sequenceBits;
62 Assert.isTrue(allocateTotalBits == TOTAL_BITS, "allocate not enough 64 bits");
63
64
65 this.timestampBits = timestampBits;
66 this.workerIdBits = workerIdBits;
67 this.sequenceBits = sequenceBits;
68
69
70 this.maxDeltaSeconds = ~(-1L << timestampBits);
71 this.maxWorkerId = ~(-1L << workerIdBits);
72 this.maxSequence = ~(-1L << sequenceBits);
73
74
75 this.timestampShift = workerIdBits + sequenceBits;
76 this.workerIdShift = sequenceBits;
77 }
78
79
80
81
82
83
84
85
86
87
88 public long allocate(long deltaSeconds, long workerId, long sequence) {
89 return (deltaSeconds << timestampShift) | (workerId << workerIdShift) | sequence;
90 }
91
92
93
94
95 public int getSignBits() {
96 return signBits;
97 }
98
99 public int getTimestampBits() {
100 return timestampBits;
101 }
102
103 public int getWorkerIdBits() {
104 return workerIdBits;
105 }
106
107 public int getSequenceBits() {
108 return sequenceBits;
109 }
110
111 public long getMaxDeltaSeconds() {
112 return maxDeltaSeconds;
113 }
114
115 public long getMaxWorkerId() {
116 return maxWorkerId;
117 }
118
119 public long getMaxSequence() {
120 return maxSequence;
121 }
122
123 public int getTimestampShift() {
124 return timestampShift;
125 }
126
127 public int getWorkerIdShift() {
128 return workerIdShift;
129 }
130
131 @Override
132 public String toString() {
133 return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
134 }
135
136 }