forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 6
/
binarymd5.go
78 lines (66 loc) · 1.66 KB
/
binarymd5.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
package vindexes
import (
"bytes"
"crypto/md5"
"fmt"
"github.com/youtube/vitess/go/sqltypes"
)
// BinaryMD5 is a vindex that hashes binary bits to a keyspace id.
type BinaryMD5 struct {
name string
}
// NewBinaryMD5 creates a new BinaryMD5.
func NewBinaryMD5(name string, _ map[string]string) (Vindex, error) {
return &BinaryMD5{name: name}, nil
}
// String returns the name of the vindex.
func (vind *BinaryMD5) String() string {
return vind.name
}
// Cost returns the cost as 1.
func (vind *BinaryMD5) Cost() int {
return 1
}
// Verify returns true if id maps to ksid.
func (vind *BinaryMD5) Verify(_ VCursor, id interface{}, ksid []byte) (bool, error) {
data, err := binHashKey(id)
if err != nil {
return false, fmt.Errorf("BinaryMD5_hash.Verify: %v", err)
}
return bytes.Compare(data, ksid) == 0, nil
}
// Map returns the corresponding keyspace id values for the given ids.
func (vind *BinaryMD5) Map(_ VCursor, ids []interface{}) ([][]byte, error) {
out := make([][]byte, 0, len(ids))
for _, id := range ids {
data, err := binHashKey(id)
if err != nil {
return nil, fmt.Errorf("BinaryMd5.Map :%v", err)
}
out = append(out, data)
}
return out, nil
}
func binHashKey(key interface{}) ([]byte, error) {
source, err := getBytes(key)
if err != nil {
return nil, err
}
return binHash(source), nil
}
func getBytes(key interface{}) ([]byte, error) {
switch v := key.(type) {
case []byte:
return v, nil
case sqltypes.Value:
return v.Raw(), nil
}
return nil, fmt.Errorf("unexpected data type for binHash: %T", key)
}
func binHash(source []byte) []byte {
sum := md5.Sum(source)
return sum[:]
}
func init() {
Register("binary_md5", NewBinaryMD5)
}