Skip to content

Commit 2c163b8

Browse files
joamakidylandreimerink
authored andcommitted
part: Improve prefixSearch
The function can be simplified and we don't need to return the root watch channel if we've already seen matching nodes. Signed-off-by: Jussi Maki <[email protected]>
1 parent 7d6b3a4 commit 2c163b8

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

part/iterator.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -64,33 +64,33 @@ func newIterator[T any](start *header[T]) *Iterator[T] {
6464
return &Iterator[T]{[][]*header[T]{{start}}}
6565
}
6666

67-
func prefixSearch[T any](root *header[T], key []byte) (*Iterator[T], <-chan struct{}) {
67+
func prefixSearch[T any](root *header[T], prefix []byte) (*Iterator[T], <-chan struct{}) {
6868
this := root
69-
var watch <-chan struct{}
69+
watch := root.watch
7070
for {
71+
// Does the node have part of the prefix we're looking for?
72+
commonPrefix := this.prefix[:min(len(prefix), len(this.prefix))]
73+
if !bytes.HasPrefix(prefix, commonPrefix) {
74+
// Mismatching prefix, return the watch channel from the previous matching node.
75+
return newIterator[T](nil), watch
76+
}
77+
7178
if !this.isLeaf() && this.watch != nil {
7279
// Leaf watch channels only close when the leaf is manipulated,
7380
// thus we only return non-leaf watch channels.
7481
watch = this.watch
7582
}
7683

77-
switch {
78-
case bytes.Equal(key, this.prefix[:min(len(key), len(this.prefix))]):
84+
// Consume the prefix of this node
85+
prefix = prefix[len(commonPrefix):]
86+
if len(prefix) == 0 {
87+
// Exact match to our search prefix.
7988
return newIterator(this), watch
80-
81-
case bytes.HasPrefix(key, this.prefix):
82-
key = key[len(this.prefix):]
83-
if len(key) == 0 {
84-
return newIterator(this), this.watch
85-
}
86-
87-
default:
88-
return newIterator[T](nil), root.watch
8989
}
9090

91-
this = this.find(key[0])
91+
this = this.find(prefix[0])
9292
if this == nil {
93-
return newIterator[T](nil), root.watch
93+
return newIterator[T](nil), watch
9494
}
9595
}
9696
}

0 commit comments

Comments
 (0)