forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 6
/
numeric.go
70 lines (60 loc) · 1.79 KB
/
numeric.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
// Copyright 2014, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vindexes
import (
"bytes"
"encoding/binary"
"fmt"
)
// Numeric defines a bit-pattern mapping of a uint64 to the KeyspaceId.
// It's Unique and Reversible.
type Numeric struct {
name string
}
// NewNumeric creates a Numeric vindex.
func NewNumeric(name string, _ map[string]string) (Vindex, error) {
return &Numeric{name: name}, nil
}
// String returns the name of the vindex.
func (vind *Numeric) String() string {
return vind.name
}
// Cost returns the cost of this vindex as 0.
func (*Numeric) Cost() int {
return 0
}
// Verify returns true if id and ksid match.
func (*Numeric) Verify(_ VCursor, id interface{}, ksid []byte) (bool, error) {
var keybytes [8]byte
num, err := getNumber(id)
if err != nil {
return false, fmt.Errorf("Numeric.Verify: %v", err)
}
binary.BigEndian.PutUint64(keybytes[:], uint64(num))
return bytes.Compare(keybytes[:], ksid) == 0, nil
}
// Map returns the associated keyspae ids for the given ids.
func (*Numeric) Map(_ VCursor, ids []interface{}) ([][]byte, error) {
out := make([][]byte, 0, len(ids))
for _, id := range ids {
num, err := getNumber(id)
if err != nil {
return nil, fmt.Errorf("Numeric.Map: %v", err)
}
var keybytes [8]byte
binary.BigEndian.PutUint64(keybytes[:], uint64(num))
out = append(out, []byte(keybytes[:]))
}
return out, nil
}
// ReverseMap returns the associated id for the ksid.
func (*Numeric) ReverseMap(_ VCursor, ksid []byte) (interface{}, error) {
if len(ksid) != 8 {
return nil, fmt.Errorf("Numeric.ReverseMap: length of keyspace is not 8: %d", len(ksid))
}
return binary.BigEndian.Uint64([]byte(ksid)), nil
}
func init() {
Register("numeric", NewNumeric)
}