-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexpecting.go
69 lines (60 loc) · 1.21 KB
/
expecting.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
package goleri
const (
modeRequired = iota
modeOptional = iota
)
type expecting struct {
required []Element
optional []Element
pos int
modes map[int]uint8
}
func newExpecting() *expecting {
modes := make(map[int]uint8)
modes[0] = modeRequired
return &expecting{
pos: 0,
modes: modes,
}
}
func (e *expecting) empty() {
e.required = []Element{}
e.optional = []Element{}
}
func (e *expecting) update(elem Element, pos int) {
if pos > e.pos {
e.empty()
e.pos = pos
}
if pos == e.pos {
if e.modes[pos] == modeRequired {
e.required = appendIfMissing(e.required, elem)
} else {
e.optional = appendIfMissing(e.optional, elem)
}
}
}
func (e *expecting) setMode(pos int, mode uint8) {
// do nothing when mode is already set to optional
if m, ok := e.modes[pos]; ok && m == modeOptional {
return
}
e.modes[pos] = mode
}
func (e *expecting) getExpecting() []Element {
if e.optional != nil {
for _, elem := range e.optional {
e.required = appendIfMissing(e.required, elem)
}
e.optional = nil
}
return e.required
}
func appendIfMissing(slice []Element, elem Element) []Element {
for _, e := range slice {
if e == elem {
return slice
}
}
return append(slice, elem)
}