-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqueue.go
More file actions
56 lines (50 loc) · 1.09 KB
/
queue.go
File metadata and controls
56 lines (50 loc) · 1.09 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
package graphql
import "iter"
type queue[T any] struct {
// primary is the queue currently being iterated
primary []T
// secondary is used for new items
secondary []T
// i is the index in the primary slice to return on next pop
i int
}
//nolint:unused
func (q *queue[T]) empty() bool {
return q.i >= len(q.primary) && len(q.secondary) == 0
}
func (q *queue[T]) all() iter.Seq[T] {
return func(yield func(v T) bool) {
for {
v, ok := q.pop()
if !ok {
return
}
if !yield(v) {
return
}
}
}
}
func (q *queue[T]) push(v T) {
q.secondary = append(q.secondary, v)
}
func (q *queue[T]) pop() (T, bool) {
var empty T
// If at the end of the current primary slice then
// swap primary and secondary.
if q.i >= len(q.primary) {
// Swap queues
q.primary = q.primary[:0]
q.primary, q.secondary = q.secondary, q.primary
q.i = 0
// If we're still at the end after swapping then the queue is empty.
if q.i >= len(q.primary) {
return empty, false
}
}
v := q.primary[q.i]
// Allow the value to be garbage collected
q.primary[q.i] = empty
q.i++
return v, true
}