Skip to content

Commit 3c6529f

Browse files
committed
remove excess spaces and do one liner if
1 parent d1ead97 commit 3c6529f

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

spaceflake.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ const (
1818
MAX12BITS = 4095
1919
// MAX41BITS is the maximum value for a 41 bits number
2020
MAX41BITS = 2199023255551
21+
// CLOCK_DRIFT_TOLERANCE_MS is the tolerance for clock drift in milliseconds
22+
CLOCK_DRIFT_TOLERANCE_MS = 10
2123
)
2224

2325
// Spaceflake represents a Spaceflake
@@ -199,11 +201,12 @@ func (w *Worker) GenerateSpaceflake() (*Spaceflake, error) {
199201
milliseconds := uint64(math.Floor(microTime() * 1000))
200202
milliseconds -= w.BaseEpoch
201203

202-
if milliseconds < w.lastTimestamp {
203-
for milliseconds < w.lastTimestamp {
204-
time.Sleep(time.Millisecond)
205-
milliseconds = uint64(math.Floor(microTime()*1000)) - w.BaseEpoch
204+
if delta := w.lastTimestamp - milliseconds; milliseconds < w.lastTimestamp {
205+
if delta >= CLOCK_DRIFT_TOLERANCE_MS {
206+
return nil, fmt.Errorf("clock moved backwards by %dms", delta)
206207
}
208+
time.Sleep(time.Duration(delta+1) * time.Millisecond)
209+
milliseconds = uint64(math.Floor(microTime()*100)) - w.BaseEpoch
207210
}
208211

209212
w.lastTimestamp = milliseconds

0 commit comments

Comments
 (0)