Skip to content

Commit

Permalink
Use 48 bits of timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
torcolvin committed Dec 18, 2023
1 parent 46b8751 commit 523fb29
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 17 deletions.
14 changes: 7 additions & 7 deletions hlc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,28 @@ type timestamp uint64
// hybridLogicalClock is a hybrid logical clock implementation for rosmar that produces timestamps that will always be increasing regardless of clock changes.
type hybridLogicalClock struct {
clock clock
counter timestamp
highestTime timestamp
counter uint16
highestTime uint64
mutex sync.Mutex
}

// clock interface is used to abstract the system clock for testing purposes.
type clock interface {
// getTime returns the current time in nanoseconds.
getTime() timestamp
getTime() uint64
}

type systemClock struct{}

// getTime returns the current time in nanoseconds.
func (c *systemClock) getTime() timestamp {
return timestamp(time.Now().UnixNano())
func (c *systemClock) getTime() uint64 {
return uint64(time.Now().UnixNano())
}

// NewHybridLogicalClock returns a new HLC from a previously initialized time.
func NewHybridLogicalClock(lastTime timestamp) *hybridLogicalClock {
return &hybridLogicalClock{
highestTime: lastTime,
highestTime: uint64(lastTime),
clock: &systemClock{},
}
}
Expand All @@ -55,5 +55,5 @@ func (c *hybridLogicalClock) Now() timestamp {
c.counter = 0
c.highestTime = physicalTime
}
return c.highestTime + c.counter
return timestamp((c.highestTime << 16) | uint64(c.counter))
}
25 changes: 15 additions & 10 deletions hlc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ loop:
}

type fakeClock struct {
time timestamp
time uint64
}

func (c *fakeClock) getTime() timestamp {
func (c *fakeClock) getTime() uint64 {
return c.time
}

Expand All @@ -82,19 +82,24 @@ func TestHLCReverseTime(t *testing.T) {
require.Equal(t, timestamp(2), hlc.Now())

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

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

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

// jump to a value we had previously
clock.time = timestamp(6)
require.Equal(t, int(timestamp(8)), int(hlc.Now()))
require.Equal(t, int(timestamp(9)), int(hlc.Now()))
clock.time = 6
require.Equal(t, timestamp(0x60002), hlc.Now())
require.Equal(t, timestamp(0x60003), hlc.Now())

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

}

0 comments on commit 523fb29

Please sign in to comment.