-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
132 lines (112 loc) · 2.31 KB
/
Copy pathqueue.go
File metadata and controls
132 lines (112 loc) · 2.31 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
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
package axsafe
import (
"errors"
"sync"
)
var ErrEmptyQueue = errors.New("queue is empty")
const maxQueueCapacity = 0x10000 // 65536 items
type Queue struct {
lock sync.RWMutex
buffer []interface{}
head int
tail int
size int
capacity int
}
func NewSafeQueue(capacity int) *Queue {
if capacity <= 0 {
capacity = 0x100
}
if capacity > maxQueueCapacity {
capacity = maxQueueCapacity
}
return &Queue{
buffer: make([]interface{}, capacity),
capacity: capacity,
}
}
func (q *Queue) Len() int {
q.lock.RLock()
defer q.lock.RUnlock()
return q.size
}
func (q *Queue) Push(value interface{}) {
q.lock.Lock()
defer q.lock.Unlock()
if q.size == q.capacity {
if q.capacity >= maxQueueCapacity {
q.buffer[q.head] = nil
q.head = (q.head + 1) % q.capacity
q.size--
} else {
q.resize()
}
}
q.buffer[q.tail] = value
q.tail = (q.tail + 1) % q.capacity
q.size++
}
func (q *Queue) Pop() (interface{}, error) {
q.lock.Lock()
defer q.lock.Unlock()
if q.size == 0 {
return nil, ErrEmptyQueue
}
val := q.buffer[q.head]
q.buffer[q.head] = nil
q.head = (q.head + 1) % q.capacity
q.size--
return val, nil
}
func (q *Queue) resize() {
newCap := q.capacity * 2
if newCap > maxQueueCapacity {
newCap = maxQueueCapacity
}
newBuf := make([]interface{}, newCap)
for i := 0; i < q.size; i++ {
newBuf[i] = q.buffer[(q.head+i)%q.capacity]
}
q.buffer = newBuf
q.head = 0
q.tail = q.size
q.capacity = newCap
}
func (q *Queue) RemoveIf(predicate func(v interface{}) bool) (bool, interface{}) {
q.lock.Lock()
defer q.lock.Unlock()
var found bool
var removed interface{}
newBuf := make([]interface{}, 0, q.capacity)
for i := 0; i < q.size; i++ {
idx := (q.head + i) % q.capacity
item := q.buffer[idx]
if !found && predicate(item) {
found = true
removed = item
continue
}
newBuf = append(newBuf, item)
}
if !found {
return false, nil
}
q.buffer = make([]interface{}, q.capacity)
copy(q.buffer, newBuf)
q.head = 0
q.tail = len(newBuf)
q.size = len(newBuf)
return true, removed
}
func (q *Queue) FindIf(predicate func(v interface{}) bool) (bool, interface{}) {
q.lock.RLock()
defer q.lock.RUnlock()
for i := 0; i < q.size; i++ {
idx := (q.head + i) % q.capacity
item := q.buffer[idx]
if predicate(item) {
return true, item
}
}
return false, nil
}