-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathid.go
58 lines (46 loc) · 1.26 KB
/
id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package toolbelt
import (
"encoding/base32"
"encoding/binary"
"fmt"
"time"
"github.com/denisbrodbeck/machineid"
"github.com/rzajac/zflake"
"github.com/zeebo/xxh3"
)
var flake *zflake.Gen
func NextID() int64 {
if flake == nil {
id, err := machineid.ID()
if err != nil {
id = time.Now().Format(time.RFC3339Nano)
}
h := xxh3.HashString(id) % (1 << zflake.BitLenGID)
h16 := uint16(h)
flake = zflake.NewGen(
zflake.Epoch(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)),
zflake.GID(h16),
)
}
return flake.NextFID()
}
func NextEncodedID() string {
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, uint64(NextID()))
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf)
}
func AliasHash(alias string) int64 {
return int64(xxh3.HashString(alias) & 0x7fffffffffffffff)
}
func AliasHashf(format string, args ...interface{}) int64 {
return AliasHash(fmt.Sprintf(format, args...))
}
func AliasHashEncoded(alias string) string {
h := AliasHash(alias)
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, uint64(h))
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf)
}
func AliasHashEncodedf(format string, args ...interface{}) string {
return AliasHashEncoded(fmt.Sprintf(format, args...))
}