diff --git a/src/git.xdrm.io/schastsp/lib/wtime/wtime.go b/src/git.xdrm.io/schastsp/lib/wtime/wtime.go index 3dec14d..cbbf53e 100644 --- a/src/git.xdrm.io/schastsp/lib/wtime/wtime.go +++ b/src/git.xdrm.io/schastsp/lib/wtime/wtime.go @@ -1,6 +1,7 @@ package wtime import ( + "math" "time" ) @@ -14,10 +15,10 @@ type TimeID struct { ID uint; Parity uint } /* (1) Generates the current time id * -* @wsize Window Size in seconds +* @wsize Window Size in seconds * ---------------------------------------------------------*/ -func GetID(wsize uint) *TimeID{ +func GenerateID(wsize float64) *TimeID{ /* (0) Initialise instance */ instance := new(TimeID); @@ -26,13 +27,32 @@ func GetID(wsize uint) *TimeID{ if wsize == 0 { return instance } /* (2) Get current timestamp */ - timestamp := uint( time.Now().Unix() ); + timestamp := float64( time.Now().Unix() ); /* (3) Calculate the time id */ - instance.ID = timestamp / wsize; + instance.ID = uint( timestamp / wsize ); /* (4) Calculate parity */ instance.Parity = instance.ID % 2; return instance; +} + + +/* (2) Try to guess the received ID from current time and received parity +* +* @wsize Window Size in seconds +* @parity Received parity +* +* @return id The guessed time id +* +---------------------------------------------------------*/ +func GuessID(wsize float64, parity uint) uint{ + + /* (1) Get current time id */ + var tidNow *TimeID = GenerateID(wsize); + + /* (2) Update ID with tidNow parity difference */ + return tidNow.ID - uint(math.Abs( float64(tidNow.Parity) - float64(parity) )); + } \ No newline at end of file diff --git a/src/git.xdrm.io/schastsp/lib/wtime/wtime_test.go b/src/git.xdrm.io/schastsp/lib/wtime/wtime_test.go new file mode 100644 index 0000000..d7f9365 --- /dev/null +++ b/src/git.xdrm.io/schastsp/lib/wtime/wtime_test.go @@ -0,0 +1,23 @@ +package wtime + +import ( + "time" + "testing" +) + + +func TestGuessing(t *testing.T){ + + var windowSize float64 = .5; + + var tid *TimeID = GenerateID(windowSize); + + time.Sleep( time.Duration(windowSize) * time.Second); + + var guessedId uint = GuessID(windowSize, tid.Parity); + + if tid.ID != guessedId { + t.Errorf("Wrong guessed id, expected '%d' ; got '%d'", tid.ID, guessedId); + } + +} \ No newline at end of file