51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package timeid
|
|
|
|
import (
|
|
"math"
|
|
"time"
|
|
)
|
|
|
|
|
|
/* (1) Generates the current time id
|
|
*
|
|
* @wsize<float64> Window Size in seconds
|
|
*
|
|
* @return id<uint32> Current time id
|
|
* @return parity<uint32> Current time parity
|
|
*
|
|
---------------------------------------------------------*/
|
|
func Generate(wsize float64) (uint32, uint32){
|
|
|
|
/* (1) If wsize is 0 (div by zero possible error) */
|
|
if wsize == 0 { return 0, 0 }
|
|
|
|
/* (2) Get current timestamp */
|
|
timestamp := float64( time.Now().Unix() );
|
|
|
|
/* (3) Calculate the time id */
|
|
var id = uint32( timestamp / wsize );
|
|
|
|
/* (4) Calculate parity */
|
|
var parity = id % 2;
|
|
|
|
return id, parity;
|
|
}
|
|
|
|
|
|
/* (2) Try to guess a previous time id from its parity
|
|
*
|
|
* @wsize<float64> Window Size in seconds
|
|
* @parity<uint32> Received parity
|
|
*
|
|
* @return id<uint32> The guessed time id
|
|
*
|
|
---------------------------------------------------------*/
|
|
func Guess(wsize float64, parity uint32) uint32{
|
|
|
|
/* (1) Get current time id */
|
|
var idNow, parityNow = Generate(wsize);
|
|
|
|
/* (2) Update ID with tidNow parity difference */
|
|
return idNow - uint32(math.Abs( float64(parityNow) - float64(parity) ));
|
|
|
|
} |