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