forked from oxfeeefeee/appgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
id.go
72 lines (62 loc) · 1.22 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package appgo
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/json"
"math"
"strconv"
)
var (
base64Encoding = base64.RawURLEncoding
binaryEndian = binary.BigEndian
)
type Id int64
func (id Id) String() string {
return strconv.FormatInt(int64(id), 10)
}
func (id Id) MarshalJSON() ([]byte, error) {
var buffer bytes.Buffer
buffer.WriteByte('"')
buffer.WriteString(id.String())
buffer.WriteByte('"')
return buffer.Bytes(), nil
}
func (id *Id) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
if s == "" {
*id = 0
return nil
}
if val, err := strconv.ParseInt(s, 10, 64); err != nil {
return err
} else {
*id = Id(val)
}
return nil
}
func IdFromStr(str string) Id {
i, _ := strconv.ParseInt(str, 10, 64)
return Id(i)
}
func IdFromBase64(str string) Id {
if len(str) == 0 {
return 0
} else if data, err := base64Encoding.DecodeString(str); err != nil {
return 0
} else {
val := binaryEndian.Uint64(data)
return Id(int64(val))
}
}
func IdMax() Id {
return Id(math.MaxInt64)
}
func (id Id) Base64() string {
buf := make([]byte, 8)
binaryEndian.PutUint64(buf, uint64(int64(id)))
return base64Encoding.EncodeToString(buf)
}