vitess.io/vitess@v0.16.2/go/vt/vtgate/vindexes/xxhash.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package vindexes 18 19 import ( 20 "bytes" 21 "context" 22 "encoding/binary" 23 24 "github.com/cespare/xxhash/v2" 25 26 "vitess.io/vitess/go/sqltypes" 27 "vitess.io/vitess/go/vt/key" 28 ) 29 30 var ( 31 _ SingleColumn = (*XXHash)(nil) 32 _ Hashing = (*XXHash)(nil) 33 ) 34 35 // XXHash defines vindex that hashes any sql types to a KeyspaceId 36 // by using xxhash64. It's Unique and works on any platform giving identical result. 37 type XXHash struct { 38 name string 39 } 40 41 // NewXXHash creates a new XXHash. 42 func NewXXHash(name string, _ map[string]string) (Vindex, error) { 43 return &XXHash{name: name}, nil 44 } 45 46 // String returns the name of the vindex. 47 func (vind *XXHash) String() string { 48 return vind.name 49 } 50 51 // Cost returns the cost of this index as 1. 52 func (vind *XXHash) Cost() int { 53 return 1 54 } 55 56 // IsUnique returns true since the Vindex is unique. 57 func (vind *XXHash) IsUnique() bool { 58 return true 59 } 60 61 // NeedsVCursor satisfies the Vindex interface. 62 func (vind *XXHash) NeedsVCursor() bool { 63 return false 64 } 65 66 // Map can map ids to key.Destination objects. 67 func (vind *XXHash) Map(ctx context.Context, vcursor VCursor, ids []sqltypes.Value) ([]key.Destination, error) { 68 out := make([]key.Destination, 0, len(ids)) 69 for _, id := range ids { 70 ksid, err := vind.Hash(id) 71 if err != nil { 72 return nil, err 73 } 74 out = append(out, key.DestinationKeyspaceID(ksid)) 75 } 76 return out, nil 77 } 78 79 // Verify returns true if ids maps to ksids. 80 func (vind *XXHash) Verify(ctx context.Context, vcursor VCursor, ids []sqltypes.Value, ksids [][]byte) ([]bool, error) { 81 out := make([]bool, 0, len(ids)) 82 for i, id := range ids { 83 ksid, err := vind.Hash(id) 84 if err != nil { 85 return out, err 86 } 87 out = append(out, bytes.Equal(ksid, ksids[i])) 88 } 89 return out, nil 90 } 91 92 func (vind *XXHash) Hash(id sqltypes.Value) ([]byte, error) { 93 idBytes, err := id.ToBytes() 94 if err != nil { 95 return nil, err 96 } 97 return vXXHash(idBytes), nil 98 } 99 100 func init() { 101 Register("xxhash", NewXXHash) 102 } 103 104 func vXXHash(shardKey []byte) []byte { 105 var hashed [8]byte 106 hashKey := xxhash.Sum64(shardKey) 107 binary.LittleEndian.PutUint64(hashed[:], hashKey) 108 return hashed[:] 109 }