-
Notifications
You must be signed in to change notification settings - Fork 55
/
chan.go
148 lines (129 loc) · 2.2 KB
/
chan.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
145
146
147
148
//go:build go1.18
// +build go1.18
package zutil
type (
chanType int
conf struct {
len *Uint32
typ chanType
cap int64
}
Opt func(*conf)
Chan[T any] struct {
in, out chan T
close chan struct{}
conf conf
q []T
}
Options struct {
Cap int
}
)
const (
unbuffered chanType = iota
buffered
unbounded
)
func NewChan[T any](cap ...int) *Chan[T] {
o := conf{
typ: unbounded,
cap: -1,
len: NewUint32(0),
}
if len(cap) > 0 {
if cap[0] == 0 {
o.cap = int64(0)
o.typ = unbuffered
} else if cap[0] > 0 {
o.cap = int64(cap[0])
o.typ = buffered
} else {
o.cap = int64(-1)
o.typ = unbounded
}
}
ch := &Chan[T]{conf: o, close: make(chan struct{})}
switch ch.conf.typ {
case unbuffered:
ch.in = make(chan T)
ch.out = ch.in
case buffered:
ch.in = make(chan T, ch.conf.cap)
ch.out = ch.in
case unbounded:
ch.in = make(chan T, 16)
ch.out = make(chan T, 16)
go ch.process()
}
return ch
}
func (ch *Chan[T]) In() chan<- T { return ch.in }
func (ch *Chan[T]) Out() <-chan T { return ch.out }
func (ch *Chan[T]) Close() {
switch ch.conf.typ {
case buffered, unbuffered:
close(ch.in)
close(ch.close)
default:
ch.close <- struct{}{}
}
}
func (ch *Chan[T]) Len() int {
switch ch.conf.typ {
case buffered, unbuffered:
return len(ch.in)
default:
return int(ch.conf.len.Load()) + len(ch.in) + len(ch.out)
}
}
func (ch *Chan[T]) process() {
var nilT T
ch.q = make([]T, 0, 1<<10)
for {
select {
case e, ok := <-ch.in:
if !ok {
return
}
ch.conf.len.Add(1)
ch.q = append(ch.q, e)
case <-ch.close:
ch.closeUnbounded()
return
}
for len(ch.q) > 0 {
select {
case ch.out <- ch.q[0]:
ch.conf.len.Sub(1)
ch.q[0] = nilT
ch.q = ch.q[1:]
case e, ok := <-ch.in:
if !ok {
return
}
ch.conf.len.Add(1)
ch.q = append(ch.q, e)
case <-ch.close:
ch.closeUnbounded()
return
}
}
if cap(ch.q) < 1<<5 {
ch.q = make([]T, 0, 1<<10)
}
}
}
func (ch *Chan[T]) closeUnbounded() {
var nilT T
close(ch.in)
for e := range ch.in {
ch.q = append(ch.q, e)
}
for len(ch.q) > 0 {
ch.out <- ch.q[0]
ch.q[0] = nilT
ch.q = ch.q[1:]
}
close(ch.out)
close(ch.close)
}