-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsequence.go
123 lines (100 loc) · 1.96 KB
/
sequence.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package stream
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
)
// Sequence todo
type Sequence struct {
id ID
number int64
}
func NewSequence[T any](id string, n ...int64) (s Sequence, err error) {
if s.id, err = NewID[T](id); err != nil {
return s, Err("invalid id string %w", err)
}
if len(n) > 0 {
s.number = n[0]
}
return s, nil
}
func MustSequence[T any](id string) Sequence {
rid, err := NewSequence[T](id)
if err != nil {
panic(err)
}
return rid
}
func ParseSequence(s string) (n Sequence, err error) {
var p = strings.Split(s, ".")
var l = len(p)
if l < 2 {
return n, Err("wrong `%s` format, please use <id>.<type>.<number> ie `N8hY13fsd.Chat.43`", s)
}
if n.id, err = ParseID(s); err != nil {
return n, Err("parse sequence failed %w", err)
}
if l == 3 {
m, err := strconv.Atoi(p[2])
if err != nil {
return n, Err("parse sequence number failed %w", err)
}
n.number = int64(m)
}
return
}
func (s Sequence) ID() ID {
return s.id
}
func (s Sequence) Number() int64 {
return s.number
}
func (s Sequence) Next() Sequence {
s.number++
return s
}
func (s Sequence) Hash() UUID {
return NewUUID(fmt.Sprintf("%s:%d", s.id.Hash(), s.number))
}
func (s Sequence) MarshalJSON() ([]byte, error) {
return json.Marshal(view{
"ID": s.id.UUID(),
"Type": s.id.Type(),
"Number": s.Number(),
})
}
func (s *Sequence) UnmarshalJSON(b []byte) error {
if bytes.Equal(b, null) {
return nil
}
var v view
if err := json.Unmarshal(b, &v); err != nil {
return err
}
r, err := ParseSequence(fmt.Sprintf("%s.%s", v["ID"], v["Type"]))
if err != nil {
return err
}
*s = r
return nil
}
func (s Sequence) String() string {
if s.IsEmpty() {
return ""
}
if s.number == 0 {
return s.id.String()
}
return fmt.Sprintf("%s#%d", s.id, s.number)
}
func (s Sequence) Reset() {
s.number = 0
}
func (s Sequence) IsEmpty() bool {
return s.id.IsEmpty()
}
func (s Sequence) Resource() Resource {
return s.id.Resource()
}