-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
indexer.go
78 lines (64 loc) · 2.35 KB
/
indexer.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 indexer
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/hashicorp/go-memdb"
)
var (
// Ensure the required memdb interfaces are met at compile time.
_ memdb.Indexer = SingleIndexer{}
_ memdb.SingleIndexer = SingleIndexer{}
)
// SingleIndexer implements both memdb.Indexer and memdb.SingleIndexer. It may
// be used in a memdb.IndexSchema to specify functions that generate the index
// value for memdb.Txn operations.
type SingleIndexer struct {
// readIndex is used by memdb for Txn.Get, Txn.First, and other operations
// that read data.
ReadIndex
// writeIndex is used by memdb for Txn.Insert, Txn.Delete, and other
// operations that write data to the index.
WriteIndex
}
// ReadIndex implements memdb.Indexer. It exists so that a function can be used
// to provide the interface.
//
// Unlike memdb.Indexer, a readIndex function accepts only a single argument. To
// generate an index from multiple values, use a struct type with multiple fields.
type ReadIndex func(arg any) ([]byte, error)
func (f ReadIndex) FromArgs(args ...interface{}) ([]byte, error) {
if len(args) != 1 {
return nil, fmt.Errorf("index supports only a single arg")
}
return f(args[0])
}
var ErrMissingValueForIndex = fmt.Errorf("object is missing a value for this index")
// WriteIndex implements memdb.SingleIndexer. It exists so that a function
// can be used to provide this interface.
//
// Instead of a bool return value, writeIndex expects errMissingValueForIndex to
// indicate that an index could not be build for the object. It will translate
// this error into a false value to satisfy the memdb.SingleIndexer interface.
type WriteIndex func(raw any) ([]byte, error)
func (f WriteIndex) FromObject(raw any) (bool, []byte, error) {
v, err := f(raw)
if errors.Is(err, ErrMissingValueForIndex) {
return false, nil, nil
}
return err == nil, v, err
}
// IndexBuilder is a buffer used to construct memdb index values.
type IndexBuilder bytes.Buffer
// Bytes returns the stored IndexBuilder value as a byte array.
func (b *IndexBuilder) Bytes() []byte { return (*bytes.Buffer)(b).Bytes() }
// Time is used to write the passed time into the IndexBuilder for use as a
// memdb index value.
func (b *IndexBuilder) Time(t time.Time) {
val := t.Unix()
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(val))
(*bytes.Buffer)(b).Write(buf)
}