sonyflake.go 1.25 KB
Newer Older
1
// Package id provides unique ID generation using the Sonyflake algorithm
2 3 4
package id

import (
5
	"fmt"
6 7 8 9 10 11 12 13 14 15
	"log"
	"math/rand"
	"strconv"
	"time"

	"github.com/sony/sonyflake"
)

var sf *sonyflake.Sonyflake

16
const maxMachineID = 1<<16 - 1
17 18

func init() {
19 20 21 22 23
	// Initialize random source for machine ID generation
	// Note: There is a small risk of machineID collisions if multiple
	// instances are started within the same microsecond
	r := rand.New(rand.NewSource(time.Now().UnixMicro()))

24 25 26
	st := sonyflake.Settings{
		StartTime: time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC),
		MachineID: func() (uint16, error) {
27
			return uint16(r.Intn(maxMachineID)), nil
28 29 30 31 32 33
		},
		CheckMachineID: nil,
	}

	sf = sonyflake.NewSonyflake(st)
	if sf == nil {
34
		log.Panicf("failed to initialize sonyflake")
35 36 37
	}
}

38 39
// Str returns a string representation of a unique Sonyflake ID.
// It panics if ID generation fails.
40
func Str() string {
41 42 43 44 45
	id, err := sf.NextID()
	if err != nil {
		panic(fmt.Sprintf("failed to generate sonyflake ID: %v", err))
	}
	return strconv.FormatUint(id, 10)
46 47
}

48 49
// UInt64 returns a uint64 unique Sonyflake ID.
// It panics if ID generation fails.
50
func UInt64() uint64 {
51 52 53 54 55
	id, err := sf.NextID()
	if err != nil {
		panic(fmt.Sprintf("failed to generate sonyflake ID: %v", err))
	}
	return id
56
}