-
Notifications
You must be signed in to change notification settings - Fork 1
/
target.go
125 lines (99 loc) · 2.25 KB
/
target.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
package abnf // import "github.com/nathanaelle/abnf"
import (
"strings"
)
func inSlice(a string, list []string) bool {
upper_a := strings.ToUpper(a)
for _, b := range list {
if strings.ToUpper(b) == upper_a {
return true
}
}
return false
}
type Target struct {
Childs []Target
Rule string
Value []byte
}
func (t Target) String() string {
if t.Rule != "" {
val := " "+t.Rule+"={"+string(t.Value)
for _,child := range t.Childs {
val= val+child.String()
}
return val+"}"
}
//if len(t.Childs) == 0 {
// return string(t.Value)
//}
val := "{"+string(t.Value)
for _,child := range t.Childs {
val= val+child.String()
}
return val+"}"
}
func (t Target) Drop(rules ...string) Target {
childs := []Target {}
for _,target := range t.Childs {
if !inSlice(target.Rule, rules) {
childs = append(childs, target.Drop(rules...))
}
}
return Target { childs, t.Rule, t.Value }
}
func merge_leaf(targets ...Target) []Target {
value := []byte{}
for _,c := range targets {
if len(c.Childs) > 0 {
return targets
}
value = append(value, c.Value... )
}
return []Target {{ []Target{}, targets[0].Rule, value }}
}
func (target Target) Merge(rules ...string) Target {
if len(target.Childs) == 0 {
return target
}
t_childs := []Target{}
for _,c := range target.Childs {
t_childs = append(t_childs, c.Merge(rules...) )
}
childs := []Target{}
tmp_t := Target{}
for i,t_c := range t_childs {
if i==0{
tmp_t = t_c
continue
}
if strings.ToUpper(tmp_t.Rule) != strings.ToUpper(t_c.Rule) {
childs = append(childs, tmp_t )
tmp_t = t_c
continue
}
if len(tmp_t.Childs) >0 {
childs = append(childs, tmp_t )
tmp_t = t_c
continue
}
if !inSlice(tmp_t.Rule, rules) {
childs = append(childs, tmp_t )
tmp_t = t_c
continue
}
tmp_t = (merge_leaf(tmp_t, t_c))[0]
}
childs = append(childs, tmp_t )
switch inSlice(target.Rule, rules) {
case true:
t := append( []Target{ {[]Target{}, target.Rule, target.Value} }, childs...)
t = merge_leaf( t... )
if len(t) > 1 {
return Target { childs, target.Rule, target.Value }
}
return t[0]
default:
return Target { childs, target.Rule, target.Value }
}
}