-
Notifications
You must be signed in to change notification settings - Fork 4
/
batch.go
95 lines (81 loc) · 2.31 KB
/
batch.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
92
93
94
95
package kv
import (
"bytes"
"errors"
)
// RawKeyValuePair represents the key/value pair with Kind.
type RawKeyValuePair struct {
key []byte
value Value
kind Kind
}
// Key returns the key.
func (kv RawKeyValuePair) Key() []byte {
return kv.key
}
// Value returns the value.
func (kv RawKeyValuePair) Value() Value {
return kv.value
}
var DuplicateKeyInBatchErr = errors.New("batch already contains the key")
// Batch is a collection of RawKeyValuePair.
// Batch is typically used in a transaction (txn.Transaction). All the inserts within a transaction (read/write transaction)
// are batched and finally the entire Batch is committed.
type Batch struct {
pairs []RawKeyValuePair
}
// NewBatch creates an empty Batch.
func NewBatch() *Batch {
return &Batch{}
}
// Put puts the key/value pair in Batch.
// Returns DuplicateKeyInBatchErr if the key is already present in the Batch.
func (batch *Batch) Put(key, value []byte) error {
if batch.Contains(key) {
return DuplicateKeyInBatchErr
}
batch.pairs = append(batch.pairs, RawKeyValuePair{
key: key,
value: NewValue(value),
kind: EntryKindPut,
})
return nil
}
// Delete is modeled as an append operation. It results in another RawKeyValuePair in batch with kind as EntryKindDelete.
func (batch *Batch) Delete(key []byte) {
batch.pairs = append(batch.pairs, RawKeyValuePair{
key: key,
value: EmptyValue,
kind: EntryKindDelete,
})
}
// Get returns the Value for the given key if found.
func (batch *Batch) Get(key []byte) (Value, bool) {
for _, pair := range batch.pairs {
if bytes.Compare(pair.key, key) == 0 {
return pair.value, true
}
}
return EmptyValue, false
}
// Contains returns true of the key is present in Batch.
func (batch *Batch) Contains(key []byte) bool {
_, ok := batch.Get(key)
return ok
}
// IsEmpty returns true if the Batch is empty.
func (batch *Batch) IsEmpty() bool {
return len(batch.pairs) == 0
}
// Length returns the number of RawKeyValuePair(s) in the Batch.
func (batch *Batch) Length() int {
return len(batch.pairs)
}
// CloneKeyValuePairs clones the RawKeyValuePair(s) present in the Batch.
func (batch *Batch) CloneKeyValuePairs() []RawKeyValuePair {
keyValuePairs := make([]RawKeyValuePair, 0, batch.Length())
for _, pair := range batch.pairs {
keyValuePairs = append(keyValuePairs, pair)
}
return keyValuePairs
}