forked from elves/elvish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
47 lines (43 loc) · 1.01 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
package vals
import (
"github.com/xiaq/persistent/hash"
)
// Hasher wraps the Hash method.
type Hasher interface {
// Hash computes the hash code of the receiver.
Hash() uint32
}
// Hash returns the 32-bit hash of a value. It is implemented for the builtin
// types bool and string, and types satisfying the listHashable, mapHashable or
// Hasher interface. For other values, it returns 0 (which is OK in terms of
// correctness).
func Hash(v interface{}) uint32 {
switch v := v.(type) {
case bool:
if v {
return 1
}
return 0
case listHashable:
h := hash.DJBInit
for it := v.Iterator(); it.HasElem(); it.Next() {
h = hash.DJBCombine(h, Hash(it.Elem()))
}
return h
case mapIterable:
h := hash.DJBInit
for it := v.Iterator(); it.HasElem(); it.Next() {
k, v := it.Elem()
h = hash.DJBCombine(h, Hash(k))
h = hash.DJBCombine(h, Hash(v))
}
return h
case string:
return hash.String(v)
case Hasher:
return v.Hash()
}
return 0
}
type listHashable listIterable
type mapHashable mapIterable