This commit is contained in:
Colin Henry 2023-04-05 21:20:45 -07:00
parent 9f88dc9530
commit 7154029136
2 changed files with 19 additions and 15 deletions

View File

@ -1,7 +1,6 @@
package snowflake package snowflake
import ( import (
"fmt"
"hash/fnv" "hash/fnv"
"math" "math"
"net" "net"
@ -15,42 +14,48 @@ const (
nodeIDBits = 10 nodeIDBits = 10
sequenceBits = 12 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 customEpoch int64 = 1420070400000
) )
var maxNodeID int64 var (
var maxSequence int64 maxNodeID int64
maxSequence int64
timestampMutex sync.Mutex
sequenceMutex sync.Mutex
nodeID int64
lastTimestamp int64 = 0
sequence int64
)
var nodeID int64 const two = 2
var lastTimestamp int64 = 0
var sequence int64
func init() { func init() {
maxNodeID = int64(math.Pow(2, nodeIDBits) - 1) maxNodeID = int64(math.Pow(two, nodeIDBits) - 1)
maxSequence = int64(math.Pow(2, sequenceBits) - 1) maxSequence = int64(math.Pow(two, sequenceBits) - 1)
nodeID = generateNodeID() nodeID = generateNodeID()
} }
func generateNodeID() int64 { func generateNodeID() int64 {
var nodeID int64 var nodeID int64
if interfaces, err := net.Interfaces(); err == nil { if interfaces, err := net.Interfaces(); err == nil {
h := fnv.New32a() h := fnv.New32a()
for _, i := range interfaces { for _, i := range interfaces {
h.Write(i.HardwareAddr) h.Write(i.HardwareAddr)
} }
nodeID = int64(h.Sum32()) nodeID = int64(h.Sum32())
} else { } else {
panic("interfaces not available") panic("interfaces not available")
} }
nodeID = nodeID & maxNodeID nodeID = nodeID & maxNodeID
return nodeID return nodeID
} }
var timestampMutex sync.Mutex // Next returns the next logical snowflake.
var sequenceMutex sync.Mutex
// Next returns the next logical snowflake
func Next() int64 { func Next() int64 {
timestampMutex.Lock() timestampMutex.Lock()
currentTimestamp := ts() currentTimestamp := ts()
@ -76,7 +81,6 @@ func Next() int64 {
id |= (nodeID << sequenceBits) id |= (nodeID << sequenceBits)
id |= sequence id |= sequence
fmt.Printf("%b\n", id)
return id return id
} }
@ -88,5 +92,6 @@ func waitNextMillis(currentTimestamp int64) int64 {
for currentTimestamp == lastTimestamp { for currentTimestamp == lastTimestamp {
currentTimestamp = ts() currentTimestamp = ts()
} }
return currentTimestamp return currentTimestamp
} }

View File

@ -9,7 +9,6 @@ func TestNext(t *testing.T) {
fmt.Printf("node id: %b\n", generateNodeID()) fmt.Printf("node id: %b\n", generateNodeID())
fmt.Printf("timestamp: %b\n", ts()) fmt.Printf("timestamp: %b\n", ts())
fmt.Printf("full token: %b\n", Next()) fmt.Printf("full token: %b\n", Next())
// t.Fail()
} }
func BenchmarkNext(b *testing.B) { func BenchmarkNext(b *testing.B) {