-
Notifications
You must be signed in to change notification settings - Fork 0
/
inmem.go
86 lines (68 loc) · 1.31 KB
/
inmem.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
package cerra
import (
"sync"
)
type inMemoryBackend struct {
sync.RWMutex
tasks []*Task
head int
tail int
count int
exit chan struct{}
stopSync sync.Once
}
func NewInMemoryBackend() *inMemoryBackend {
return &inMemoryBackend{
tasks: make([]*Task, 1),
exit: make(chan struct{}),
}
}
func (b *inMemoryBackend) Enqueue(task *Task) error {
b.Lock()
defer b.Unlock()
if b.count == len(b.tasks) {
b.resize(b.count * 2)
}
b.tasks[b.tail] = task
b.tail = (b.tail + 1) % len(b.tasks)
b.count++
return nil
}
func (b *inMemoryBackend) Dequeue() (*Task, error) {
b.Lock()
defer b.Unlock()
if b.count == 0 {
select {
case b.exit <- struct{}{}:
return nil, ErrQueueClosed
default:
}
return nil, ErrEmtpyQueue
}
data := b.tasks[b.head]
b.tasks[b.head] = nil
b.head = (b.head + 1) % len(b.tasks)
b.count--
if n := len(b.tasks) / 2; n > 1 && b.count <= n {
b.resize(n)
}
return data, nil
}
func (b *inMemoryBackend) Close() error {
b.stopSync.Do(func() {
<-b.exit
})
return nil
}
func (b *inMemoryBackend) resize(size int) {
nodes := make([]*Task, size)
if b.head < b.tail {
copy(nodes, b.tasks[b.head:b.tail])
} else {
copy(nodes, b.tasks[b.head:])
copy(nodes[len(b.tasks)-b.head:], b.tasks[:b.tail])
}
b.tail = b.count % size
b.head = 0
b.tasks = nodes
}