1package custom_comparator
2
3import (
4	"os"
5	"testing"
6	"unsafe"
7
8	"github.com/couchbase/goforestdb"
9)
10
11func TestForestCustomComparator(t *testing.T) {
12	defer os.RemoveAll("test")
13
14	dbfile, err := forestdb.Open("test", nil)
15	if err != nil {
16		t.Fatal(err)
17	}
18	defer dbfile.Close()
19
20	kvconfig := forestdb.DefaultKVStoreConfig()
21	kvconfig.SetCustomCompare(unsafe.Pointer(CompareBytesReversedPointer))
22
23	kvstore, err := dbfile.OpenKVStore("tkv", kvconfig)
24	if err != nil {
25		t.Fatal(err)
26	}
27	defer kvstore.Close()
28
29	// store a bunch of values to test the iterator
30
31	kvstore.SetKV([]byte("a"), []byte("vala"))
32	kvstore.SetKV([]byte("b"), []byte("valb"))
33	kvstore.SetKV([]byte("c"), []byte("valc"))
34	kvstore.SetKV([]byte("d"), []byte("vald"))
35	kvstore.SetKV([]byte("e"), []byte("vale"))
36	kvstore.SetKV([]byte("f"), []byte("valf"))
37	kvstore.SetKV([]byte("g"), []byte("valg"))
38	kvstore.SetKV([]byte("h"), []byte("valh"))
39	kvstore.SetKV([]byte("i"), []byte("vali"))
40	kvstore.SetKV([]byte("j"), []byte("valj"))
41
42	iter, err := kvstore.IteratorInit([]byte("g"), []byte("c"), forestdb.ITR_NONE)
43	if err != nil {
44		t.Fatal(err)
45	}
46
47	doc, err := iter.Next()
48	count := 0
49	var firstKey, lastKey []byte
50	for err == nil {
51		count++
52		if firstKey == nil {
53			firstKey = doc.Key()
54		}
55		lastKey = doc.Key()
56		doc, err = iter.Next()
57	}
58	if count != 5 {
59		t.Errorf("exptected to iterate 5, saw %d", count)
60	}
61	if string(firstKey) != "g" {
62		t.Errorf("expected fist key to be c, got %s", firstKey)
63	}
64	if string(lastKey) != "c" {
65		t.Errorf("expected last key to be g, got %s", lastKey)
66	}
67	if err != forestdb.FDB_RESULT_ITERATOR_FAIL {
68		t.Errorf("expected %#v, got %#v", forestdb.FDB_RESULT_ITERATOR_FAIL, err)
69	}
70}
71