forked from gammazero/radixtree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator.go
More file actions
47 lines (41 loc) · 1.12 KB
/
iterator.go
File metadata and controls
47 lines (41 loc) · 1.12 KB
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
package radixtree
// Iterator iterates all keys and values in the radix tree.
//
// Is is safe to use different Iterator instances concurrently. Any
// modification to the Tree that the Iterator was created from invalidates the
// Iterator instance.
type Iterator struct {
nodes []*radixNode
}
// NewIterator returns a new Iterator.
func (t *Tree) NewIterator() *Iterator {
return &Iterator{
nodes: []*radixNode{&t.root},
}
}
// Copy creates a new Iterator at this iterator's state of iteration.
func (it *Iterator) Copy() *Iterator {
nodes := make([]*radixNode, len(it.nodes))
copy(nodes, it.nodes)
return &Iterator{
nodes: nodes,
}
}
// Next returns the next key and value stored in the Tree, and true when
// iteration is complete.
func (it *Iterator) Next() (key string, value any, done bool) {
for {
if len(it.nodes) == 0 {
break
}
node := it.nodes[len(it.nodes)-1]
it.nodes = it.nodes[:len(it.nodes)-1]
for i := len(node.edges) - 1; i >= 0; i-- {
it.nodes = append(it.nodes, node.edges[i].node)
}
if node.leaf != nil {
return node.leaf.key, node.leaf.value, false
}
}
return "", nil, true
}