From 3991c526892c90f6d88324af2d042e2e0e62eaad Mon Sep 17 00:00:00 2001 From: Colin Henry Date: Thu, 9 Jul 2020 20:02:23 -0700 Subject: [PATCH] moving from uint64 to int64. allows use of snowflakes id in databases --- snowflake/snowflake.go | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/snowflake/snowflake.go b/snowflake/snowflake.go index b606028..52dfdd1 100755 --- a/snowflake/snowflake.go +++ b/snowflake/snowflake.go @@ -16,30 +16,30 @@ const ( sequenceBits = 12 // Custom Epoch (January 1, 2015 Midnight UTC = 2015-01-01T00:00:00Z) - customEpoch uint64 = 1420070400000 + customEpoch int64 = 1420070400000 ) -var maxNodeID uint64 -var maxSequence uint64 +var maxNodeID int64 +var maxSequence int64 -var nodeID uint64 -var lastTimestamp uint64 = 0 -var sequence uint64 +var nodeID int64 +var lastTimestamp int64 = 0 +var sequence int64 func init() { - maxNodeID = uint64(math.Pow(2, nodeIDBits) - 1) - maxSequence = uint64(math.Pow(2, sequenceBits) - 1) + maxNodeID = int64(math.Pow(2, nodeIDBits) - 1) + maxSequence = int64(math.Pow(2, sequenceBits) - 1) nodeID = generateNodeID() } -func generateNodeID() uint64 { - var nodeID uint64 +func generateNodeID() int64 { + var nodeID int64 if interfaces, err := net.Interfaces(); err == nil { h := fnv.New32a() for _, i := range interfaces { h.Write(i.HardwareAddr) } - nodeID = uint64(h.Sum32()) + nodeID = int64(h.Sum32()) } else { panic("interfaces not available") } @@ -51,7 +51,7 @@ var timestampMutex sync.Mutex var sequenceMutex sync.Mutex // Next returns the next logical snowflake -func Next() uint64 { +func Next() int64 { timestampMutex.Lock() currentTimestamp := ts() timestampMutex.Unlock() @@ -69,21 +69,22 @@ func Next() uint64 { sequenceMutex.Unlock() lastTimestamp = currentTimestamp - id := currentTimestamp << (totalBits - epochBits) - fmt.Printf("%b\n", id) - id |= (nodeID << (totalBits - epochBits - nodeIDBits)) - fmt.Printf("%b\n", id) - + // id := currentTimestamp << (totalBits - epochBits) + // id |= (nodeID << (totalBits - epochBits - nodeIDBits)) + // id |= sequence + var id int64 = currentTimestamp << (nodeIDBits + sequenceBits) + id |= (nodeID << sequenceBits) id |= sequence + fmt.Printf("%b\n", id) return id } -func ts() uint64 { - return uint64(time.Now().UnixNano()/1000000) - customEpoch +func ts() int64 { + return int64(time.Now().UnixNano()/1000000) - customEpoch } -func waitNextMillis(currentTimestamp uint64) uint64 { +func waitNextMillis(currentTimestamp int64) int64 { for currentTimestamp == lastTimestamp { currentTimestamp = ts() }