uid.go

 1// Package uid generates unique IDs.
 2package uid
 3
 4import (
 5	"github.com/speps/go-hashids"
 6	"go.uber.org/atomic"
 7)
 8
 9// Generator generates unique incrementing IDs. These IDs are only comparable
10// with other IDs from this generator.
11type Generator struct {
12	hid  *hashids.HashID
13	next atomic.Int64
14}
15
16// NewGenerator creates a new Generator with the specified salt. Generators
17// with the same salt generate the same IDs in order.
18func NewGenerator(salt string) *Generator {
19	hd := hashids.NewData()
20	hd.MinLength = 8
21	hd.Salt = salt
22	hid, err := hashids.NewWithData(hd)
23	if err != nil {
24		panic(err)
25	}
26
27	return &Generator{
28		hid: hid,
29	}
30}
31
32// Next gets the next ID, in both an encoded string form and the raw integer form.
33func (g *Generator) Next() (string, int64) {
34	v := g.next.Inc()
35	id, err := g.hid.EncodeInt64([]int64{v})
36	if err != nil {
37		panic(err)
38	}
39	return id, v
40}