This repository was archived by the owner on Sep 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
93 lines (80 loc) · 2.02 KB
/
util.go
File metadata and controls
93 lines (80 loc) · 2.02 KB
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
package gobbc
import (
"encoding/binary"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/google/uuid"
)
// UntilError execute all func until error returned
func UntilError(fns ...func() error) error {
for _, fn := range fns {
if e := fn(); e != nil {
return e
}
}
return nil
}
// CopyReverse copy and reverse []byte
func CopyReverse(bs []byte) []byte {
s := make([]byte, len(bs))
copy(s, bs)
return reverseBytes(s)
}
// reverseBytes reverse []byte s, and return s
func reverseBytes(s []byte) []byte {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
// CopyReverseThenEncodeHex 复制[]byte,反转后hex.EncodeToString
func CopyReverseThenEncodeHex(bs []byte) string {
return hex.EncodeToString(CopyReverse(bs))
}
// GetTemplateType 如果解析失败则返回TemplateTypeMin(0)
func GetTemplateType(templateData string) TemplateType {
b, err := hex.DecodeString(templateData[:4])
if err != nil {
return TemplateTypeMin
}
v := binary.LittleEndian.Uint16(b)
return TemplateType(v)
}
// DataDetail .
type DataDetail struct {
UUID string
UnixTime uint32
Data string
}
// UtilDataEncoding 将tx data 进行编码
func UtilDataEncoding(data string) string {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, uint32(time.Now().Unix()))
return strings.Join([]string{
strings.Replace(uuid.New().String(), "-", "", -1),
hex.EncodeToString(b),
"00",
hex.EncodeToString([]byte(data)),
}, "")
}
// UtilDataDecoding .
func UtilDataDecoding(data string) (DataDetail, error) {
var dd DataDetail
if l := len(data); l < 32+8+2 {
return dd, fmt.Errorf("invalid len: %d, should > 42", l)
}
dd.UUID = data[:32]
timeBytes, err := hex.DecodeString(data[32 : 32+8])
if err != nil {
return dd, fmt.Errorf("unable to decode time, %v", err)
}
dd.UnixTime = binary.LittleEndian.Uint32(timeBytes)
content, err := hex.DecodeString(data[42:])
if err != nil {
return dd, fmt.Errorf("unable to decode content, %v", err)
}
dd.Data = string(content)
return dd, nil
}