Skip to content

Commit 8f38fa6

Browse files
ok32ok32YoshiyukiMineo
authored
v2: take only 'bitsMachine' least significant bits from generated machine IDs so it doesn't corrupt the other ID parts (#72)
Co-authored-by: ok32 <[email protected]> Co-authored-by: Yoshiyuki Mineo <[email protected]>
1 parent 5347433 commit 8f38fa6

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

v2/sonyflake.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ func (sf *Sonyflake) toID() (int64, error) {
213213

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

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

270270
// Decompose returns a set of Sonyflake ID parts.

v2/sonyflake_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package sonyflake
33
import (
44
"errors"
55
"fmt"
6+
"math"
67
"net"
78
"runtime"
89
"testing"
@@ -437,3 +438,28 @@ func TestComposeAndDecompose(t *testing.T) {
437438
})
438439
}
439440
}
441+
442+
func TestBigMachineDoesntBreakID(t *testing.T) {
443+
start := time.Now()
444+
sf := newSonyflake(t, Settings{
445+
TimeUnit: time.Millisecond,
446+
StartTime: start,
447+
MachineID: func() (int, error) {
448+
return math.MaxInt, nil
449+
},
450+
})
451+
452+
id := nextID(t, sf)
453+
parts := sf.Decompose(id)
454+
455+
if parts["sequence"] != 0 {
456+
t.Errorf("next id sequence mismatch: got %d, want %d", parts["sequence"], 0)
457+
}
458+
459+
id = sf.Compose(time.Now(), 0, math.MaxInt)
460+
parts = sf.Decompose(id)
461+
462+
if parts["sequence"] != 0 {
463+
t.Errorf("decompose sequence mismatch: got %d, want %d", parts["sequence"], 0)
464+
}
465+
}

0 commit comments

Comments
 (0)