Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions v2/sonyflake.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ func (sf *Sonyflake) toID() (int64, error) {

return sf.elapsedTime<<(sf.bitsSequence+sf.bitsMachine) |
int64(sf.sequence)<<sf.bitsMachine |
int64(sf.machine), nil
(int64(sf.machine) & ((1 << sf.bitsMachine) - 1)), nil
}

func privateIPv4(interfaceAddrs types.InterfaceAddrs) (net.IP, error) {
Expand Down Expand Up @@ -264,7 +264,7 @@ func (sf *Sonyflake) Compose(t time.Time, sequence, machineID int) int64 {
elapsedTime := sf.toInternalTime(t.UTC()) - sf.startTime
return elapsedTime<<(sf.bitsSequence+sf.bitsMachine) |
int64(sequence)<<sf.bitsMachine |
int64(machineID)
(int64(machineID) & ((1 << sf.bitsMachine) - 1))
}

// Decompose returns a set of Sonyflake ID parts.
Expand Down
26 changes: 26 additions & 0 deletions v2/sonyflake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package sonyflake
import (
"errors"
"fmt"
"math"
"net"
"runtime"
"testing"
Expand Down Expand Up @@ -437,3 +438,28 @@ func TestComposeAndDecompose(t *testing.T) {
})
}
}

func TestBigMachineDoesntBreakID(t *testing.T) {
start := time.Now()
sf := newSonyflake(t, Settings{
TimeUnit: time.Millisecond,
StartTime: start,
MachineID: func() (int, error) {
return math.MaxInt, nil
},
})

id := nextID(t, sf)
parts := sf.Decompose(id)

if parts["sequence"] != 0 {
t.Errorf("next id sequence mismatch: got %d, want %d", parts["sequence"], 0)
}

id = sf.Compose(time.Now(), 0, math.MaxInt)
parts = sf.Decompose(id)

if parts["sequence"] != 0 {
t.Errorf("decompose sequence mismatch: got %d, want %d", parts["sequence"], 0)
}
}
Loading