-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
99 lines (86 loc) · 1.78 KB
/
utils.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package qradix
import (
"bytes"
"flag"
"fmt"
)
var (
// enable debug mode by "go test -args -d=true"
debug = flag.Bool("d", false, "print debug messages")
)
type Node interface {
Segment() string
FirstChild() (Node, bool)
NextNode() (Node, bool)
Value() (interface{}, bool)
Extra() (interface{}, bool)
}
// BFS is breadth first traverse on the radix tree
func BFS(T *RTree, apply func(Node)) {
Q := make([]Node, 0)
if T.root == nil {
return
}
Q = append(Q, T.root)
for len(Q) > 0 {
n := Q[0]
Q = Q[1:]
firstChild, ok := n.FirstChild()
if ok {
Q = append(Q, firstChild)
}
nextNode, ok := n.NextNode()
if ok {
Q = append(Q, nextNode)
}
apply(n)
}
}
func print(msg string) {
if *debug {
fmt.Println(msg)
}
}
func printActions(actions []string) {
print("\naction list:")
for id, action := range actions {
print(fmt.Sprintf("action%d: %s", id, action))
}
}
func printRTree(T *RTree) {
print("\nrtree:")
BFS(T, PrintNode)
}
func printMap(M map[string]string) {
print("\nmap:")
for _, val := range M {
print(fmt.Sprintf("(%s)", val))
}
}
// PrintNode prints node's fields
func PrintNode(n Node) {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("[prefix: %s] ", n.Segment()))
firstChild, ok := n.FirstChild()
if ok {
buf.WriteString(fmt.Sprintf("[child: %s] ", firstChild.Segment()))
}
nextNode, ok := n.NextNode()
if ok {
buf.WriteString(fmt.Sprintf("[next: %s] ", nextNode.Segment()))
}
value, ok := n.Value()
if ok {
buf.WriteString(fmt.Sprintf("[value(key): %s]", value))
}
extra, ok := n.Extra()
if ok {
buf.WriteString("[idx:")
idx := extra.(map[rune]*node)
for rune1, node := range idx {
buf.WriteString(fmt.Sprintf("(%s->%s)", string(rune1), node.Segment()))
}
buf.WriteString("]")
}
fmt.Println(buf.String())
}