-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathlinked.go
More file actions
255 lines (196 loc) · 4.92 KB
/
linked.go
File metadata and controls
255 lines (196 loc) · 4.92 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package queue
import (
"encoding/json"
"sync"
)
var _ Queue[any] = (*Linked[any])(nil)
// node is an individual element of the linked list.
type node[T any] struct {
value T
next *node[T]
}
// Linked represents a data structure representing a queue that uses a
// linked list for its internal storage.
type Linked[T comparable] struct {
head *node[T] // first node of the queue.
tail *node[T] // last node of the queue.
size int // number of elements in the queue.
// nolint: revive
initialElements []T // initial elements with which the queue was created, allowing for a reset to its original state if needed.
// synchronization
lock sync.RWMutex
// free is a stack of recycled nodes. Offer pulls from here before
// allocating; Get pushes onto it. Bounded to freeCap so Clear/Reset
// can't cause unbounded retention.
free *node[T]
freeLen int
}
// freeCap is the maximum number of nodes cached for reuse.
const freeCap = 64
// NewLinked creates a new Linked containing the given elements.
func NewLinked[T comparable](elements []T) *Linked[T] {
queue := &Linked[T]{
head: nil,
tail: nil,
size: 0,
initialElements: make([]T, len(elements)),
}
copy(queue.initialElements, elements)
for _, element := range elements {
_ = queue.offer(element)
}
return queue
}
// Get retrieves and removes the head of the queue.
func (lq *Linked[T]) Get() (elem T, _ error) {
lq.lock.Lock()
defer lq.lock.Unlock()
if lq.isEmpty() {
return elem, ErrNoElementsAvailable
}
popped := lq.head
value := popped.value
lq.head = popped.next
lq.size--
if lq.isEmpty() {
lq.tail = nil
}
lq.recycle(popped)
return value, nil
}
// Offer inserts the element into the queue.
func (lq *Linked[T]) Offer(value T) error {
lq.lock.Lock()
defer lq.lock.Unlock()
return lq.offer(value)
}
// offer inserts the element into the queue.
func (lq *Linked[T]) offer(value T) error {
newNode := lq.acquireNode()
newNode.value = value
if lq.isEmpty() {
lq.head = newNode
} else {
lq.tail.next = newNode
}
lq.tail = newNode
lq.size++
return nil
}
// acquireNode pulls a node off the free list or allocates a fresh one.
func (lq *Linked[T]) acquireNode() *node[T] {
if lq.free == nil {
return &node[T]{}
}
n := lq.free
lq.free = n.next
lq.freeLen--
n.next = nil
return n
}
// recycle zeroes a popped node and returns it to the free list, capped
// at freeCap to avoid pinning memory after a large drain.
func (lq *Linked[T]) recycle(n *node[T]) {
if lq.freeLen >= freeCap {
return
}
var zero T
n.value = zero
n.next = lq.free
lq.free = n
lq.freeLen++
}
// Reset sets the queue to its initial state.
func (lq *Linked[T]) Reset() {
lq.lock.Lock()
defer lq.lock.Unlock()
lq.head = nil
lq.tail = nil
lq.size = 0
for _, element := range lq.initialElements {
_ = lq.offer(element)
}
}
// Contains returns true if the queue contains the element.
func (lq *Linked[T]) Contains(value T) bool {
lq.lock.RLock()
defer lq.lock.RUnlock()
current := lq.head
for current != nil {
if current.value == value {
return true
}
current = current.next
}
return false
}
// Peek retrieves but does not remove the head of the queue.
func (lq *Linked[T]) Peek() (elem T, _ error) {
lq.lock.RLock()
defer lq.lock.RUnlock()
if lq.isEmpty() {
return elem, ErrNoElementsAvailable
}
return lq.head.value, nil
}
// Size returns the number of elements in the queue.
func (lq *Linked[T]) Size() int {
lq.lock.RLock()
defer lq.lock.RUnlock()
return lq.size
}
// IsEmpty returns true if the queue is empty, false otherwise.
func (lq *Linked[T]) IsEmpty() bool {
lq.lock.RLock()
defer lq.lock.RUnlock()
return lq.isEmpty()
}
// isEmpty returns true if the queue is empty, false otherwise.
func (lq *Linked[T]) isEmpty() bool {
return lq.size == 0
}
// Iterator returns a channel that will be filled with the elements.
// It removes the elements from the queue.
func (lq *Linked[T]) Iterator() <-chan T {
lq.lock.Lock()
defer lq.lock.Unlock()
elems := lq.drainLocked()
ch := make(chan T, len(elems))
for i := range elems {
ch <- elems[i]
}
close(ch)
return ch
}
// Clear removes and returns all elements from the queue.
func (lq *Linked[T]) Clear() []T {
lq.lock.Lock()
defer lq.lock.Unlock()
return lq.drainLocked()
}
// drainLocked collects all elements in order and resets the queue.
// Caller must hold the write lock.
func (lq *Linked[T]) drainLocked() []T {
elements := make([]T, lq.size)
current := lq.head
for i := 0; current != nil; i++ {
elements[i] = current.value
current = current.next
}
lq.head = nil
lq.tail = nil
lq.size = 0
return elements
}
// MarshalJSON serializes the Linked queue to JSON.
func (lq *Linked[T]) MarshalJSON() ([]byte, error) {
lq.lock.RLock()
defer lq.lock.RUnlock()
elements := make([]T, lq.size)
current := lq.head
for i := 0; current != nil; i++ {
elements[i] = current.value
current = current.next
}
return json.Marshal(elements)
}