Skip to content

Commit

Permalink
Merge pull request #9 from manosriram/feat/reader
Browse files Browse the repository at this point in the history
add keyreader and keyvaluereader
  • Loading branch information
manosriram authored Dec 26, 2023
2 parents 077a003 + 99de573 commit e13f921
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ func main() {
fmt.Println(string(z))
} else if text == "sync" {
d.Sync()
} else if text == "keyreader" {
prefix := ""
d.KeyReader(prefix, func(k []byte) {
fmt.Printf("%s\n", string(k))
})
} else if text == "keyvaluereader" {
keyPrefix := ""
d.KeyValueReader(keyPrefix, func(k []byte, v []byte) {
fmt.Printf("%s %s\n", string(k), string(v))
})
}
}
}
38 changes: 38 additions & 0 deletions reader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package nimbusdb

import (
"strings"

"github.com/google/btree"
)

// KeyReader iterates through each key matching given prefix.
// If prefix is an empty string, all keys are matched.
// The second argument is a callback function which contains the key.
func (db *Db) KeyReader(prefix string, handler func(k []byte)) {
db.keyDir.tree.Ascend(func(it btree.Item) bool {
key := it.(*item).key
if strings.HasPrefix(string(key), prefix) {
handler(key)
}
return true
})
}

// KeyValueReader iterates through each key-value pair matching given key's prefix.
// If prefix is an empty string, all key-value pairs are matched.
// The second argument is a callback function which contains key and the value.
func (db *Db) KeyValueReader(keyPrefix string, handler func(k []byte, v []byte)) (bool, error) {
db.keyDir.tree.Ascend(func(it btree.Item) bool {
key := it.(*item).key
if strings.HasPrefix(string(key), keyPrefix) {
v, err := db.getKeyDir(key)
if err != nil {
return false
}
handler(it.(*item).key, v.v)
}
return true
})
return false, nil
}

0 comments on commit e13f921

Please sign in to comment.