-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhlc.go
71 lines (57 loc) · 1.32 KB
/
hlc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package hlc
import (
"fmt"
"time"
)
type TimeSupplier func() time.Time
type HLCTime struct {
wallTime time.Time
logicalTime int16
}
type HLCClock struct {
t HLCTime
timeSupplier TimeSupplier // Wall time supplier
}
func NewHLCTime(wallTime time.Time, logical int16) HLCTime {
return HLCTime{
wallTime: wallTime,
logicalTime: logical,
}
}
func NewHLCClock(timeSupplier TimeSupplier) *HLCClock {
return &HLCClock{
t: NewHLCTime(time.Unix(0, 0), 0),
timeSupplier: timeSupplier,
}
}
func (t HLCTime) String() string {
return fmt.Sprintf("%d+%d", t.wallTime.UnixNano(), t.logicalTime)
}
func (c *HLCClock) GetTime() HLCTime {
wallTime := c.timeSupplier()
if c.t.wallTime.Before(wallTime) {
c.t.wallTime = wallTime
c.t.logicalTime = 0
} else {
c.t.logicalTime++
}
return c.t
}
func (c *HLCClock) UpdateTime(event HLCTime) HLCTime {
wallTime := c.timeSupplier()
if wallTime.After(event.wallTime) && wallTime.After(c.t.wallTime) {
c.t.wallTime = wallTime
c.t.logicalTime = 0
} else if event.wallTime.After(c.t.wallTime) {
c.t.wallTime = event.wallTime
c.t.logicalTime++
} else if c.t.wallTime.After(event.wallTime) {
c.t.logicalTime++
} else {
if event.logicalTime > c.t.logicalTime {
c.t.logicalTime = event.logicalTime
}
c.t.logicalTime += 1
}
return c.t
}