-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtuid.go
62 lines (49 loc) · 1.08 KB
/
tuid.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
59
60
61
62
package tuid
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
type TUID struct {
prefix string
timeLayout string
time time.Time
randomCode string
seq int64
}
func (id TUID) TimeString() string {
ts := id.time.Format(id.timeLayout)
re := regexp.MustCompile(`[^a-zA-Z0-9_-]+`)
ts = re.ReplaceAllString(ts, "")
return ts
}
func (id TUID) EncodeString() string {
weekday := strconv.Itoa(NonZeroWeekday(id.time))
toEncodeStr := weekday + id.time.Format("150405")
if id.seq > 0 {
toEncodeStr += fmt.Sprintf("%04d", id.seq)
}
toEncodeInt64, _ := strconv.ParseInt(toEncodeStr, 10, 64)
return strconv.FormatInt(toEncodeInt64, 36)
}
func (id TUID) String() string {
sb := strings.Builder{}
sb.WriteString(id.prefix)
sb.WriteString(id.TimeString())
sb.WriteString(id.EncodeString())
sb.WriteString(id.randomCode)
return strings.ToUpper(sb.String())
}
func New(opts ...GenOption) TUID {
id := TUID{
timeLayout: TimeLayoutDefualt,
time: time.Now(),
randomCode: RandomString(3),
}
for _, opt := range opts {
opt.apply(&id)
}
return id
}