This repository has been archived by the owner on Apr 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
queue.go
115 lines (100 loc) · 1.96 KB
/
queue.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
package c3
const (
// queue_max_free_length is an arbitratry large-ish number of free entries
// to keep around to prevent busywork for the garbage collector.
// You can see the effect in the performance difference between
// BenchmarkEnqueue1000 and BenchmarkEnqDeq1000.
queue_max_free_length int = 1024
)
type queue struct {
head *entry
tail *entry
free *entry
version int
length int
freeLength int
}
type entry struct {
item interface{}
next *entry
}
func (q *queue) Len() int {
return q.length
}
func (q *queue) Clear() {
if q.length == 0 {
return
}
q.head = nil
q.tail = nil
q.free = nil
q.length = 0
q.freeLength = 0
q.version++
}
func (q *queue) Contains(item interface{}) bool {
for e := q.head; e != nil; e = e.next {
if e.item == item {
return true
}
}
return false
}
func (q *queue) Peek() (interface{}, bool) {
if q.head != nil {
return q.head.item, true
}
return defaultElementValue, false
}
func (q *queue) Dequeue() (interface{}, bool) {
if q.head != nil {
// remove entry from queue
e := q.head
item := e.item
e.item = defaultElementValue
q.head = e.next
if e.next == nil {
q.tail = nil
}
// add freed entry to free list but don't keep
// too many of them, it's a waste of space
if q.freeLength < queue_max_free_length {
e.next = q.free
q.free = e
q.freeLength++
}
q.length--
q.version++
return item, true
}
return defaultElementValue, false
}
func (q *queue) Enqueue(item interface{}) bool {
e := q.free
if e != nil {
// get entry from the free list
q.free = e.next
q.freeLength--
e.item = item
e.next = nil
} else {
// create a new entry
e = &entry{item, nil}
}
if q.tail == nil {
q.head = e
q.tail = e
} else {
q.tail.next = e
q.tail = e
}
q.version++
q.length++
return true
}
func (q *queue) Iterator() Iterator {
return &queueIterator{q, nil, false, q.version}
}
func (q *queue) Consumer() Consumer {
return &queueConsumer{q, defaultElementValue}
}