-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
91 lines (76 loc) · 1.73 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package fastimagehash
import (
"bytes"
"encoding/binary"
"encoding/hex"
"math/bits"
"github.com/pkg/errors"
)
var (
ErrHash1024InvalidSize = errors.New("invalid hash1024 size")
)
type Hash64 [1]uint64
func (h Hash64) Bytes() []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, h[0])
return b
}
func (h Hash64) Hex() string {
return hex.EncodeToString(h.Bytes())
}
func (h Hash64) String() string {
return h.Hex()
}
func (h Hash64) Distance(o Hash64) int {
hamming := uint64(h[0] ^ o[0])
return bits.OnesCount64(hamming)
}
type Hash1024 [16]uint64
func (h Hash1024) Bytes() []byte {
buf := bytes.NewBuffer(make([]byte, 0, 128))
for i := 0; i < 16; i += 1 {
binary.Write(buf, binary.BigEndian, h[i])
}
return buf.Bytes()
}
func (h Hash1024) Hex() string {
return hex.EncodeToString(h.Bytes())
}
func (h Hash1024) String() string {
return h.Hex()
}
func (h Hash1024) Distance(o Hash1024) int {
distance := 0
for i := 0; i < 16; i += 1 {
lh := h[i]
rh := o[i]
hamming := uint64(lh ^ rh)
distance += bits.OnesCount64(hamming)
}
return distance
}
func Hash1024FromBytes(data []byte) (Hash1024, error) {
if len(data) != 128 {
return Hash1024{}, errors.Wrapf(ErrHash1024InvalidSize, "len(bytes) != 128")
}
hash := Hash1024{}
for i := 0; i < 16; i += 1 {
hash[i] = binary.BigEndian.Uint64(data[:8])
data = data[8:]
}
return hash, nil
}
func Hash1024FromString(s string) (Hash1024, error) {
if len(s) != 256 {
return Hash1024{}, errors.Wrapf(ErrHash1024InvalidSize, "len(hex) != 256")
}
data, err := hex.DecodeString(s)
if err != nil {
return Hash1024{}, errors.WithStack(err)
}
hash, err := Hash1024FromBytes(data)
if err != nil {
return Hash1024{}, errors.WithStack(err)
}
return hash, nil
}