schastsp/internal/timeid/timeid.go

52 lines
1.1 KiB
Go
Raw Normal View History

2018-04-25 06:17:20 +00:00
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
*
---------------------------------------------------------*/
2018-09-06 14:41:03 +00:00
func Generate(wsize float64) (uint32, uint32) {
2018-04-25 06:17:20 +00:00
/* (1) If wsize is 0 (div by zero possible error) */
2018-09-06 14:41:03 +00:00
if wsize == 0 {
return 0, 0
}
2018-04-25 06:17:20 +00:00
/* (2) Get current timestamp */
2018-09-06 14:41:03 +00:00
timestamp := float64(time.Now().Unix())
2018-04-25 06:17:20 +00:00
/* (3) Calculate the time id */
2018-09-06 14:41:03 +00:00
var id = uint32(timestamp / wsize)
2018-04-25 06:17:20 +00:00
/* (4) Calculate parity */
2018-09-06 14:41:03 +00:00
var parity = id % 2
2018-04-25 06:17:20 +00:00
2018-09-06 14:41:03 +00:00
return id, parity
2018-04-25 06:17:20 +00:00
}
/* (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
*
---------------------------------------------------------*/
2018-09-06 14:41:03 +00:00
func Guess(wsize float64, parity uint32) uint32 {
2018-04-25 06:17:20 +00:00
/* (1) Get current time id */
2018-09-06 14:41:03 +00:00
var idNow, parityNow = Generate(wsize)
2018-04-25 06:17:20 +00:00
/* (2) Update ID with tidNow parity difference */
2018-09-06 14:41:03 +00:00
return idNow - uint32(math.Abs(float64(parityNow)-float64(parity)))
2018-04-25 06:17:20 +00:00
2018-09-06 14:41:03 +00:00
}