Skip to content

Commit

Permalink
Correct bitwise arthimetic
Browse files Browse the repository at this point in the history
  • Loading branch information
torcolvin committed Dec 19, 2023
1 parent d3ad563 commit d368d58
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
4 changes: 2 additions & 2 deletions hlc.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ func NewHybridLogicalClock(lastTime timestamp) *hybridLogicalClock {
func (c *hybridLogicalClock) Now() timestamp {
c.mutex.Lock()
defer c.mutex.Unlock()
physicalTime := c.clock.getTime() & 0xFFFF
physicalTime := c.clock.getTime() &^ 0xFFFF // round to 48 bits to allow counter at end
if c.highestTime >= physicalTime {
c.counter++
} else {
c.counter = 0
c.highestTime = physicalTime
}
return timestamp((c.highestTime << 16) | uint64(c.counter))
return timestamp(c.highestTime | uint64(c.counter))
}
24 changes: 13 additions & 11 deletions hlc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,28 +78,30 @@ func (c *fakeClock) getTime() uint64 {
func TestHLCReverseTime(t *testing.T) {
clock := &fakeClock{}
hlc := hybridLogicalClock{clock: clock}
require.Equal(t, timestamp(1), hlc.Now())
require.Equal(t, timestamp(2), hlc.Now())
startTime := uint64(1000000) // 1 second
clock.time = startTime
require.Equal(t, timestamp(0xf0000), hlc.Now())
require.Equal(t, timestamp(0xf0001), hlc.Now())

// reverse time no counter
clock.time = 0
require.Equal(t, timestamp(3), hlc.Now())
require.Equal(t, timestamp(0xf0002), hlc.Now())

// reset time to normal
clock.time = 6
require.Equal(t, timestamp(0x60000), hlc.Now())
clock.time = startTime
require.Equal(t, timestamp(0xf0003), hlc.Now())

// reverse time again
clock.time = 1
require.Equal(t, timestamp(0x60001), hlc.Now())
require.Equal(t, timestamp(0xf0004), hlc.Now())

// jump to a value we had previously
clock.time = 6
require.Equal(t, timestamp(0x60002), hlc.Now())
require.Equal(t, timestamp(0x60003), hlc.Now())
clock.time = startTime * 2
require.Equal(t, timestamp(0x1e0000), hlc.Now())
require.Equal(t, timestamp(0x1e0001), hlc.Now())

// continue forward
clock.time = 7
require.Equal(t, timestamp(0x70000), hlc.Now())
clock.time *= 2
require.Equal(t, timestamp(0x3d0000), hlc.Now())

}

0 comments on commit d368d58

Please sign in to comment.