-
Notifications
You must be signed in to change notification settings - Fork 8
/
root_generator.go
144 lines (122 loc) · 2.54 KB
/
root_generator.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
138
139
140
141
142
143
144
//go:build !tinywasm
package gtree
import (
"bufio"
"context"
"io"
"strings"
"sync"
)
type rootGeneratorSimple struct {
counter *counter
scanner *bufio.Scanner
nodeGenerator *nodeGenerator
}
func newRootGeneratorSimple(r io.Reader) *rootGeneratorSimple {
return &rootGeneratorSimple{
counter: newCounter(),
scanner: bufio.NewScanner(r),
nodeGenerator: newNodeGenerator(),
}
}
func (rg *rootGeneratorSimple) generate() ([]*Node, error) {
var (
stack *stack
roots []*Node
)
for rg.scanner.Scan() {
currentNode, err := rg.nodeGenerator.generate(rg.scanner.Text(), rg.counter.next())
if err != nil {
return nil, err
}
if currentNode == nil {
continue
}
if currentNode.isRoot() {
rg.counter.reset()
roots = append(roots, currentNode)
stack = newStack()
stack.push(currentNode)
continue
}
if stack == nil {
return nil, errNilStack
}
stack.dfs(currentNode)
}
return roots, rg.scanner.Err()
}
type rootGeneratorPipeline struct {
nodeGenerator *nodeGenerator
}
func newRootGeneratorPipeline() *rootGeneratorPipeline {
return &rootGeneratorPipeline{
nodeGenerator: newNodeGenerator(),
}
}
const workerGenerateNum = 10
func (rg *rootGeneratorPipeline) generate(ctx context.Context, blocks <-chan string) (<-chan *Node, <-chan error) {
rootc := make(chan *Node)
errc := make(chan error, 1)
go func() {
defer func() {
close(rootc)
close(errc)
}()
wg := &sync.WaitGroup{}
for i := 0; i < workerGenerateNum; i++ {
wg.Add(1)
go rg.worker(ctx, wg, blocks, rootc, errc)
}
wg.Wait()
}()
return rootc, errc
}
func (rg *rootGeneratorPipeline) worker(ctx context.Context, wg *sync.WaitGroup, blocks <-chan string, rootc chan<- *Node, errc chan<- error) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case block, ok := <-blocks:
if !ok {
return
}
var (
sc = bufio.NewScanner(strings.NewReader(block))
root *Node
nodes = newStack()
counter = newCounter()
)
for sc.Scan() {
currentNode, err := rg.nodeGenerator.generate(sc.Text(), counter.next())
if err != nil {
errc <- err
return
}
if currentNode == nil {
continue
}
if currentNode.isRoot() {
root = currentNode
nodes.push(currentNode)
continue
}
if nodes == nil {
errc <- errNilStack
return
}
nodes.dfs(currentNode)
}
if err := sc.Err(); err != nil {
errc <- err
return
}
select {
case <-ctx.Done():
return
case rootc <- root:
}
}
}
}