-
Notifications
You must be signed in to change notification settings - Fork 13
/
internal.go
86 lines (70 loc) · 1.77 KB
/
internal.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
// Copyright 2020 Michael Li <alimy@gility.net>. All rights reserved.
// Use of this source code is governed by Apache License 2.0 that
// can be found in the LICENSE file.
package internal
import (
"context"
"sync"
"github.com/alimy/mir/v3/core"
_ "github.com/alimy/mir/v3/internal/generator"
_ "github.com/alimy/mir/v3/internal/parser"
)
type mirCtx struct {
context.Context
mu *sync.Mutex
err error
capacity int
ifaceChan chan *core.IfaceDescriptor
generatorDone chan struct{}
cancelFunc context.CancelFunc
}
// Err return cancel error
func (c *mirCtx) Err() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.err
}
// ChanCapacity return ifaceChan's capacity
func (c *mirCtx) Capcity() int {
return c.capacity
}
// Cancel cancel mir's process logic with an error
func (c *mirCtx) Cancel(err error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.err != nil {
c.err = err
c.cancelFunc()
}
}
// ParserDone indicate parser done
func (c *mirCtx) ParserDone() {
close(c.ifaceChan)
}
// GeneratorDone indicate generator done
func (c *mirCtx) GeneratorDone() {
close(c.generatorDone)
}
// Wait wait for end of process
func (c *mirCtx) Wait() error {
select {
case <-c.Done():
case <-c.generatorDone:
}
return c.Err()
}
// Pipe return source/sink chan *IfaceDescriptor
func (c *mirCtx) Pipe() (<-chan *core.IfaceDescriptor, chan<- *core.IfaceDescriptor) {
return c.ifaceChan, c.ifaceChan
}
// NewMirCtx return a new mir's context instance
func NewMirCtx(capcity int) core.MirCtx {
ctx := &mirCtx{
mu: &sync.Mutex{},
capacity: capcity,
generatorDone: make(chan struct{}),
ifaceChan: make(chan *core.IfaceDescriptor, capcity),
}
ctx.Context, ctx.cancelFunc = context.WithCancel(context.Background())
return ctx
}