-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.go
59 lines (52 loc) · 1.17 KB
/
hash.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
package json_diff
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/520MianXiangDuiXiang520/json-diff/decode"
"sort"
"strings"
)
func hashByMD5(s []byte) string {
h := md5.New()
h.Write(s)
cipherStr := h.Sum(nil)
return hex.EncodeToString(cipherStr)
}
func hash(v interface{}) string {
return hashByMD5([]byte(fmt.Sprintf("%v", v)))
}
func setHash(node *decode.JsonNode) string {
var hashCode string
switch node.Type {
case decode.JsonNodeTypeObject:
hashCode = setObjectHash(node)
case decode.JsonNodeTypeSlice:
hashCode = setSliceHash(node)
case decode.JsonNodeTypeValue:
hashCode = hash(node.Value)
node.Hash = hashCode
}
return hashCode
}
func setObjectHash(node *decode.JsonNode) string {
hashList := make([]string, len(node.ChildrenMap))
for _, v := range node.ChildrenMap {
hc := setHash(v)
hashList = append(hashList, hc)
}
sort.Strings(hashList)
hashCode := hash(strings.Join(hashList, ""))
node.Hash = hashCode
return hashCode
}
func setSliceHash(node *decode.JsonNode) string {
h := bytes.NewBufferString("")
for _, v := range node.Children {
hc := setHash(v)
h.WriteString(hc)
}
node.Hash = hash(h)
return node.Hash
}