-
Notifications
You must be signed in to change notification settings - Fork 178
/
max.go
57 lines (49 loc) · 1.43 KB
/
max.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
package operation
import (
"encoding/binary"
"errors"
"fmt"
"github.com/dgraph-io/badger/v2"
"github.com/onflow/flow-go/module/irrecoverable"
"github.com/onflow/flow-go/storage"
)
// maxKey is the biggest allowed key size in badger
const maxKey = 65000
// max holds the maximum length of keys in the database; in order to optimize
// the end prefix of iteration, we need to know how many `0xff` bytes to add.
var max uint32
// we initialize max to maximum size, to detect if it wasn't set yet
func init() {
max = maxKey
}
// InitMax retrieves the maximum key length to have it internally in the
// package after restarting.
// No errors are expected during normal operation.
func InitMax(tx *badger.Txn) error {
key := makePrefix(codeMax)
item, err := tx.Get(key)
if errors.Is(err, badger.ErrKeyNotFound) { // just keep zero value as default
max = 0
return nil
}
if err != nil {
return fmt.Errorf("could not get max: %w", err)
}
_ = item.Value(func(val []byte) error {
max = binary.LittleEndian.Uint32(val)
return nil
})
return nil
}
// SetMax sets the value for the maximum key length used for efficient iteration.
// No errors are expected during normal operation.
func SetMax(tx storage.Transaction) error {
key := makePrefix(codeMax)
val := make([]byte, 4)
binary.LittleEndian.PutUint32(val, max)
err := tx.Set(key, val)
if err != nil {
return irrecoverable.NewExceptionf("could not set max: %w", err)
}
return nil
}