-
Notifications
You must be signed in to change notification settings - Fork 0
/
elem.go
99 lines (87 loc) · 1.98 KB
/
elem.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 tidata
import (
"fmt"
"strings"
)
type Elem struct {
Text string
Children []Elem
LineNum int
}
func (e *Elem) String() string {
if e == nil {
return "<nil>"
}
return e.pfxString("")
}
func (e *Elem) pfxString(pfx string) string {
s := pfx + e.Text + "\n"
subPfx := pfx + "\t"
for i := range e.Children {
s += e.Children[i].pfxString(subPfx)
}
return s
}
func (e *Elem) JoinSubElems(initialIndent, indent, sep string) string {
val := ""
prefix := initialIndent
for i := range e.Children {
c := &e.Children[i]
val += prefix + c.Text + sep
val += c.JoinSubElems(prefix+indent, indent, sep)
}
return val
}
func (e Elem) Value() (val string) {
if i := strings.IndexAny(e.Text, " \t"); i != -1 {
val = e.Text[i+1:]
}
return
}
func (e Elem) Key() (key string) {
key = e.Text
if i := strings.IndexAny(e.Text, " \t"); i != -1 {
key = key[:i]
}
return
}
// Find the first occurance of ‘key’ in the list of childs,
// on success, return the corresponding slice index
// and a pointer to the Elem. Otherwise, return nil.
func (el *Elem) Lookup(key string) (i int, e *Elem) {
var c Elem
pfxTab := key + "\t"
pfxSpace := key + " "
for i, c = range el.Children {
if key == c.Text || strings.HasPrefix(c.Text, pfxTab) || strings.HasPrefix(c.Text, pfxSpace) {
e = &c
break
}
}
return
}
func (el *Elem) Match(key string) bool {
if strings.HasPrefix(el.Text, key+"\t") || key == el.Text {
return true
}
return false
}
// Create a map from an Elem's slice of children. Each key of a
// child will be used as a key into the map, a pointer to the
// child's Elem as value.
func (el *Elem) MapChildren() (m map[string]*Elem, err error) {
m = make(map[string]*Elem, len(el.Children))
for i := range el.Children {
c := &el.Children[i]
key := c.Text
if i := strings.Index(key, "\t"); i != -1 {
key = key[:i]
}
if _, ok := m[key]; ok {
err = fmt.Errorf("tidata: duplicate keys: \"%s.%s\"", el.Text, key)
} else {
m[key] = c
}
}
return
}