1package bolt_test
2
3import (
4	"bytes"
5	"flag"
6	"fmt"
7	"math/rand"
8	"os"
9	"reflect"
10	"testing/quick"
11	"time"
12)
13
14// testing/quick defaults to 5 iterations and a random seed.
15// You can override these settings from the command line:
16//
17//   -quick.count     The number of iterations to perform.
18//   -quick.seed      The seed to use for randomizing.
19//   -quick.maxitems  The maximum number of items to insert into a DB.
20//   -quick.maxksize  The maximum size of a key.
21//   -quick.maxvsize  The maximum size of a value.
22//
23
24var qcount, qseed, qmaxitems, qmaxksize, qmaxvsize int
25
26func init() {
27	flag.IntVar(&qcount, "quick.count", 5, "")
28	flag.IntVar(&qseed, "quick.seed", int(time.Now().UnixNano())%100000, "")
29	flag.IntVar(&qmaxitems, "quick.maxitems", 1000, "")
30	flag.IntVar(&qmaxksize, "quick.maxksize", 1024, "")
31	flag.IntVar(&qmaxvsize, "quick.maxvsize", 1024, "")
32	flag.Parse()
33	fmt.Fprintln(os.Stderr, "seed:", qseed)
34	fmt.Fprintf(os.Stderr, "quick settings: count=%v, items=%v, ksize=%v, vsize=%v\n", qcount, qmaxitems, qmaxksize, qmaxvsize)
35}
36
37func qconfig() *quick.Config {
38	return &quick.Config{
39		MaxCount: qcount,
40		Rand:     rand.New(rand.NewSource(int64(qseed))),
41	}
42}
43
44type testdata []testdataitem
45
46func (t testdata) Len() int           { return len(t) }
47func (t testdata) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
48func (t testdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == -1 }
49
50func (t testdata) Generate(rand *rand.Rand, size int) reflect.Value {
51	n := rand.Intn(qmaxitems-1) + 1
52	items := make(testdata, n)
53	used := make(map[string]bool)
54	for i := 0; i < n; i++ {
55		item := &items[i]
56		// Ensure that keys are unique by looping until we find one that we have not already used.
57		for {
58			item.Key = randByteSlice(rand, 1, qmaxksize)
59			if !used[string(item.Key)] {
60				used[string(item.Key)] = true
61				break
62			}
63		}
64		item.Value = randByteSlice(rand, 0, qmaxvsize)
65	}
66	return reflect.ValueOf(items)
67}
68
69type revtestdata []testdataitem
70
71func (t revtestdata) Len() int           { return len(t) }
72func (t revtestdata) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
73func (t revtestdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == 1 }
74
75type testdataitem struct {
76	Key   []byte
77	Value []byte
78}
79
80func randByteSlice(rand *rand.Rand, minSize, maxSize int) []byte {
81	n := rand.Intn(maxSize-minSize) + minSize
82	b := make([]byte, n)
83	for i := 0; i < n; i++ {
84		b[i] = byte(rand.Intn(255))
85	}
86	return b
87}
88