-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathevent.go
103 lines (86 loc) · 2.31 KB
/
event.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
// Copyright 2012-2018, Rolf Veen and contributors.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ogdl
// SimpleEventHandler receives events and produces a tree.
type SimpleEventHandler struct {
current int // Current level
max int // Max level
levels []int // Level of each item
items []interface{} // Items
}
// AddBytes creates a byte array node at the current level
func (e *SimpleEventHandler) AddBytes(b []byte) {
e.items = append(e.items, b)
e.levels = append(e.levels, e.current)
}
// Add creates a string node at the current level.
func (e *SimpleEventHandler) Add(s string) {
e.items = append(e.items, s)
e.levels = append(e.levels, e.current)
}
// AddItf creates a string node at the current level.
func (e *SimpleEventHandler) AddItf(i interface{}) {
e.items = append(e.items, i)
e.levels = append(e.levels, e.current)
}
// AddBytesAt creates a byte array node at the specified level
func (e *SimpleEventHandler) AddBytesAt(b []byte, lv int) {
e.items = append(e.items, b)
e.levels = append(e.levels, lv)
if e.max < lv {
e.max = lv
}
}
// AddAt creates a string node at the specified level.
func (e *SimpleEventHandler) AddAt(s string, lv int) {
e.items = append(e.items, s)
e.levels = append(e.levels, lv)
if e.max < lv {
e.max = lv
}
}
// Delete removes the last node added
func (e *SimpleEventHandler) Delete() {
e.items = e.items[0 : len(e.items)-1]
e.levels = e.levels[0 : len(e.levels)-1]
}
// Level returns the current level
func (e *SimpleEventHandler) Level() int {
return e.current
}
// SetLevel sets the current level
func (e *SimpleEventHandler) SetLevel(l int) {
e.current = l
if e.max < l {
e.max = l
}
}
// Inc increments the current level by 1.
func (e *SimpleEventHandler) Inc() {
e.current++
if e.max < e.current {
e.max = e.current
}
}
// Dec decrements the current level by 1.
func (e *SimpleEventHandler) Dec() {
if e.current > 0 {
e.current--
}
}
// Tree returns the Graph object built from
// the events sent to this event handler.
//
func (e *SimpleEventHandler) Tree() *Graph {
g := make([]*Graph, e.max+2)
g[0] = New("_")
for i := 0; i < len(e.items); i++ {
lv := e.levels[i] + 1
item := e.items[i]
n := New(item)
g[lv] = n
g[lv-1].Add(n)
}
return g[0]
}