-
Notifications
You must be signed in to change notification settings - Fork 41
/
hash.go
55 lines (48 loc) · 921 Bytes
/
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
package jsondiff
import (
"encoding/binary"
"hash/maphash"
"math"
)
type hasher struct {
mh maphash.Hash
}
func (h *hasher) digest(val interface{}) uint64 {
h.mh.Reset()
h.hash(val)
return h.mh.Sum64()
}
func (h *hasher) hash(i interface{}) {
switch v := i.(type) {
case string:
_, _ = h.mh.WriteString(v)
case bool:
if v {
_ = h.mh.WriteByte('1')
} else {
_ = h.mh.WriteByte('0')
}
case float64:
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], math.Float64bits(v))
_, _ = h.mh.Write(buf[:])
case nil:
_ = h.mh.WriteByte('0')
case []interface{}:
for _, e := range v {
h.hash(e)
}
case map[string]interface{}:
keys := make([]string, 0, len(v))
// Extract keys first, and sort them
// in lexicographical order.
for k := range v {
keys = append(keys, k)
}
sortStrings(keys)
for _, k := range keys {
_, _ = h.mh.WriteString(k)
h.hash(v[k])
}
}
}