From 7154029136c7529c417c9c8d826d3cadcb038d23 Mon Sep 17 00:00:00 2001 From: Colin Henry Date: Wed, 5 Apr 2023 21:20:45 -0700 Subject: [PATCH] linted --- snowflake/snowflake.go | 33 +++++++++++++++++++-------------- snowflake/snowflake_test.go | 1 - 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/snowflake/snowflake.go b/snowflake/snowflake.go index 52dfdd1..9ce88d6 100755 --- a/snowflake/snowflake.go +++ b/snowflake/snowflake.go @@ -1,7 +1,6 @@ package snowflake import ( - "fmt" "hash/fnv" "math" "net" @@ -15,42 +14,48 @@ const ( nodeIDBits = 10 sequenceBits = 12 - // Custom Epoch (January 1, 2015 Midnight UTC = 2015-01-01T00:00:00Z) + // Custom Epoch (January 1, 2015 Midnight UTC = 2015-01-01T00:00:00Z) . customEpoch int64 = 1420070400000 ) -var maxNodeID int64 -var maxSequence int64 +var ( + maxNodeID int64 + maxSequence int64 + timestampMutex sync.Mutex + sequenceMutex sync.Mutex + nodeID int64 + lastTimestamp int64 = 0 + sequence int64 +) -var nodeID int64 -var lastTimestamp int64 = 0 -var sequence int64 +const two = 2 func init() { - maxNodeID = int64(math.Pow(2, nodeIDBits) - 1) - maxSequence = int64(math.Pow(2, sequenceBits) - 1) + maxNodeID = int64(math.Pow(two, nodeIDBits) - 1) + maxSequence = int64(math.Pow(two, sequenceBits) - 1) nodeID = generateNodeID() } 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 = int64(h.Sum32()) } else { panic("interfaces not available") } + nodeID = nodeID & maxNodeID + return nodeID } -var timestampMutex sync.Mutex -var sequenceMutex sync.Mutex - -// Next returns the next logical snowflake +// Next returns the next logical snowflake. func Next() int64 { timestampMutex.Lock() currentTimestamp := ts() @@ -76,7 +81,6 @@ func Next() int64 { id |= (nodeID << sequenceBits) id |= sequence - fmt.Printf("%b\n", id) return id } @@ -88,5 +92,6 @@ func waitNextMillis(currentTimestamp int64) int64 { for currentTimestamp == lastTimestamp { currentTimestamp = ts() } + return currentTimestamp } diff --git a/snowflake/snowflake_test.go b/snowflake/snowflake_test.go index a6ddcb4..f4abf0c 100755 --- a/snowflake/snowflake_test.go +++ b/snowflake/snowflake_test.go @@ -9,7 +9,6 @@ func TestNext(t *testing.T) { fmt.Printf("node id: %b\n", generateNodeID()) fmt.Printf("timestamp: %b\n", ts()) fmt.Printf("full token: %b\n", Next()) - // t.Fail() } func BenchmarkNext(b *testing.B) {