Skip to content

Commit

Permalink
fix: scan trie with one key
Browse files Browse the repository at this point in the history
Problem:

If there is only one key, the walking algo does not work,
because it stores scanning progress on parent node.
A one key trie does not have a parent node thus it just return nothing.

Solution:

Treat a one key trie a special case and return an iterator that just returns
the only one record.

- Fix: #170
  • Loading branch information
drmingdrmer committed Nov 2, 2022
1 parent 5b6aea8 commit e045937
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
31 changes: 31 additions & 0 deletions trie/slimtrie_scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,37 @@ func (st *SlimTrie) newIter(path []int32, skipFirst, withValue bool) NextRaw {

if skipFirst {
stackIdx = next(stack, stackIdx)
} else {

if len(path) == 1 {
// SlimTrie is built with only one key.
//
// The walking algo depends on parent node. If there is only one node in a trie, there is no parent node.
// Thus, it is a special case.

consumed := false
nodeId := path[0]

return func() ([]byte, []byte) {
if consumed {
return nil, nil
}

var val []byte
qr := &querySession{}
st.getNode(nodeId, qr)
if qr.hasLeafPrefix {
buf = append(buf, qr.leafPrefix...)
}
if withValue {
leafI, _ := st.getLeafIndex(nodeId)
val = st.getIthLeafBytes(leafI)
}

consumed = true
return buf, val
}
}
}

return func() ([]byte, []byte) {
Expand Down
6 changes: 6 additions & 0 deletions trie/slimtrie_scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ var iterCases = map[string]struct {
paths: [][]int32{{}},
scanFromKeys: defaultScan,
},
"single": {
keys: []string{"ab"},
slimStr: trim(`#000=0`),
paths: [][]int32{{0}, {}},
scanFromKeys: defaultScan,
},
"simple": {
keys: []string{
"abc",
Expand Down

0 comments on commit e045937

Please sign in to comment.