-
Notifications
You must be signed in to change notification settings - Fork 1
/
attributes.go
137 lines (108 loc) · 2.35 KB
/
attributes.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package gockl
import (
"io"
"strings"
)
type Attribute struct {
Name string
Content string
}
type attributeTokenizer struct {
Input string
Position int
}
func (me *attributeTokenizer) shiftUntil(next string) string {
if pos := strings.Index(me.Input[me.Position+1:], next); pos > -1 {
r := me.Input[me.Position : me.Position+pos+1]
me.Position += pos + 1
return r
}
r := me.Input[me.Position:]
me.Position = len(me.Input)
return r
}
func (me *attributeTokenizer) shiftUntilSpace() string {
if me.Position+1 >= len(me.Input) {
goto whaa
}
if pos := strings.IndexAny(me.Input[me.Position+1:], spaceChars); pos > -1 {
r := me.Input[me.Position : me.Position+pos+1]
me.Position += pos + 1
return r
}
whaa:
r := me.Input[me.Position:]
me.Position = len(me.Input)
return r
}
func (me *attributeTokenizer) eatSpace() string {
if me.Position > len(me.Input) {
return ""
}
old := me.Position
for ; me.Position < len(me.Input); me.Position++ {
if !strings.Contains(spaceChars, me.Input[me.Position:me.Position+1]) {
break
}
}
return me.Input[old:me.Position]
}
func (me *attributeTokenizer) shiftValue() string {
value := me.shiftUntilSpace()
quoteChars := `"'`
if value == "" || !strings.ContainsAny(value[0:1], quoteChars) {
return value
}
q := value[0:1]
for value[len(value)-1:] != q {
part := me.eatSpace() + me.shiftUntilSpace()
if part == "" {
break
}
value += part
}
return strings.Trim(value, q)
}
func (me *attributeTokenizer) Next() (Attribute, error) {
me.eatSpace()
if me.Position >= len(me.Input) {
return Attribute{}, io.EOF
}
key := me.shiftUntil("=")
me.Position++
me.eatSpace()
if me.Position >= len(me.Input) {
return Attribute{key, ""}, nil
}
return Attribute{key, me.shiftValue()}, nil
}
func getAttribute(rawInput, name string) (string, bool) {
name = strings.ToLower(name)
z := &attributeTokenizer{Input: rawInput}
// eat the element name
z.shiftUntilSpace()
for {
a, err := z.Next()
if err != nil {
break
}
if strings.ToLower(a.Name) == name {
return a.Content, true
}
}
return "", false
}
func getAttributes(rawInput string) []Attribute {
list := []Attribute{}
z := &attributeTokenizer{Input: rawInput}
// eat the element name
z.shiftUntilSpace()
for {
a, err := z.Next()
if err != nil {
break
}
list = append(list, a)
}
return list
}