Repository navigation
Expand file tree
/
Copy pathupdate_queue.go
More file actions
104 lines (96 loc) · 1.73 KB
/
Copy pathupdate_queue.go
File metadata and controls
104 lines (96 loc) · 1.73 KB
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
package gotdbot
import "sync"
// updateQueue is an in-memory FIFO that grows without blocking the receiver.
type updateQueue struct {
mu sync.Mutex
memory chan TlObject
backlog []TlObject
ready chan struct{}
closed bool
}
func newUpdateQueue(size int) *updateQueue {
return &updateQueue{memory: make(chan TlObject, size), ready: make(chan struct{}, 1)}
}
func (q *updateQueue) notify() {
select {
case q.ready <- struct{}{}:
default:
}
}
func (q *updateQueue) push(update TlObject) error {
q.mu.Lock()
defer q.mu.Unlock()
if q.closed {
return ErrClientClosed
}
if len(q.backlog) == 0 {
select {
case q.memory <- update:
q.notify()
return nil
default:
}
}
q.backlog = append(q.backlog, update)
q.notify()
return nil
}
func (q *updateQueue) next(stop <-chan struct{}) (TlObject, error) {
for {
select {
case <-stop:
return nil, ErrClientClosed
default:
}
update, err := q.take()
if update != nil || err != nil {
return update, err
}
select {
case <-q.ready:
case <-stop:
return nil, ErrClientClosed
}
}
}
func (q *updateQueue) take() (TlObject, error) {
q.mu.Lock()
defer q.mu.Unlock()
if q.closed {
return nil, ErrClientClosed
}
defer func() {
if len(q.memory) > 0 || len(q.backlog) > 0 {
q.notify()
}
}()
select {
case update := <-q.memory:
return update, nil
default:
}
if len(q.backlog) == 0 {
return nil, nil
}
update := q.backlog[0]
q.backlog[0] = nil
q.backlog = q.backlog[1:]
if len(q.backlog) == 0 {
q.backlog = nil
}
return update, nil
}
func (q *updateQueue) close() error {
q.mu.Lock()
defer q.mu.Unlock()
if q.closed {
return nil
}
q.closed = true
close(q.ready)
for len(q.memory) > 0 {
<-q.memory
}
q.backlog = nil
return nil
}