-
Notifications
You must be signed in to change notification settings - Fork 79
/
path_iter.go
62 lines (51 loc) · 1.26 KB
/
path_iter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package iradix
import "bytes"
// PathIterator is used to iterate over a set of nodes from the root
// down to a specified path. This will iterate over the same values that
// the Node.WalkPath method will.
type PathIterator[T any] struct {
node *Node[T]
path []byte
done bool
}
// Next returns the next node in order
func (i *PathIterator[T]) Next() ([]byte, T, bool) {
// This is mostly just an asynchronous implementation of the WalkPath
// method on the node.
var zero T
var leaf *leafNode[T]
for leaf == nil && i.node != nil {
// visit the leaf values if any
if i.node.leaf != nil {
leaf = i.node.leaf
}
i.iterate()
}
if leaf != nil {
return leaf.key, leaf.val, true
}
return nil, zero, false
}
func (i *PathIterator[T]) iterate() {
// Check for key exhaustion
if len(i.path) == 0 {
i.node = nil
return
}
// Look for an edge
_, i.node = i.node.getEdge(i.path[0])
if i.node == nil {
return
}
// Consume the search prefix
if bytes.HasPrefix(i.path, i.node.prefix) {
i.path = i.path[len(i.node.prefix):]
} else {
// there are no more nodes to iterate through so
// nil out the node to prevent returning results
// for subsequent calls to Next()
i.node = nil
}
}