forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
63 lines (46 loc) · 952 Bytes
/
codec.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
package util
import (
"bytes"
"compress/zlib"
"crypto/md5"
"encoding/hex"
"io/ioutil"
)
// 字符串转为16位整形哈希
func StringHash(s string) (hash uint16) {
for _, c := range s {
ch := uint16(c)
hash = hash + ((hash) << 5) + ch + (ch << 7)
}
return
}
// 字节计算MD5
func BytesMD5(data []byte) string {
m := md5.New()
m.Write(data)
return hex.EncodeToString(m.Sum(nil))
}
// 字符串计算MD5
func StringMD5(str string) string {
return BytesMD5([]byte(str))
}
// 压缩字节
func CompressBytes(data []byte) ([]byte, error) {
var buf bytes.Buffer
writer := zlib.NewWriter(&buf)
_, err := writer.Write(data)
if err != nil {
return nil, err
}
writer.Close()
return buf.Bytes(), nil
}
// 解压字节
func DecompressBytes(data []byte) ([]byte, error) {
reader, err := zlib.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
defer reader.Close()
return ioutil.ReadAll(reader)
}