-
Notifications
You must be signed in to change notification settings - Fork 21
/
encoding.go
60 lines (46 loc) · 1023 Bytes
/
encoding.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
package session
import (
"encoding/base64"
)
var b64Encoding = base64.StdEncoding
// MSGPEncode MessagePack encode
func MSGPEncode(src Dict) ([]byte, error) {
if len(src.KV) == 0 {
return nil, nil
}
dst, err := src.MarshalMsg(nil)
if err != nil {
return nil, err
}
return dst, nil
}
// MSGPDecode MessagePack decode
func MSGPDecode(dst *Dict, src []byte) error {
for k := range dst.KV {
delete(dst.KV, k)
}
if len(src) == 0 {
return nil
}
_, err := dst.UnmarshalMsg(src)
return err
}
// Base64Encode base64 encode
func Base64Encode(src Dict) ([]byte, error) {
srcBytes, err := MSGPEncode(src)
if err != nil {
return nil, err
}
dst := make([]byte, b64Encoding.EncodedLen(len(srcBytes)))
b64Encoding.Encode(dst, srcBytes)
return dst, nil
}
// Base64Decode base64 decode
func Base64Decode(dst *Dict, src []byte) error {
tmp := make([]byte, b64Encoding.DecodedLen(len(src)))
n, err := b64Encoding.Decode(tmp, src)
if err != nil {
return err
}
return MSGPDecode(dst, tmp[:n])
}