forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
113 lines (99 loc) · 2.15 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
// Copyright 2017 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package util
// LIFO represents a simple LIFO queue.
type LIFO struct {
top *queueNode
size int
}
type queueNode struct {
v T
next *queueNode
}
// NewLIFO returns a new LIFO queue containing elements ts starting with the
// left-most argument at the bottom.
func NewLIFO(ts ...T) *LIFO {
s := &LIFO{}
for i := range ts {
s.Push(ts[i])
}
return s
}
// Push adds a new element onto the LIFO.
func (s *LIFO) Push(t T) {
node := &queueNode{v: t, next: s.top}
s.top = node
s.size++
}
// Peek returns the top of the LIFO. If LIFO is empty, returns nil, false.
func (s *LIFO) Peek() (T, bool) {
if s.top == nil {
return nil, false
}
return s.top.v, true
}
// Pop returns the top of the LIFO and removes it. If LIFO is empty returns
// nil, false.
func (s *LIFO) Pop() (T, bool) {
if s.top == nil {
return nil, false
}
node := s.top
s.top = node.next
s.size--
return node.v, true
}
// Size returns the size of the LIFO.
func (s *LIFO) Size() int {
return s.size
}
// FIFO represents a simple FIFO queue.
type FIFO struct {
front *queueNode
back *queueNode
size int
}
// NewFIFO returns a new FIFO queue containing elements ts starting with the
// left-most argument at the front.
func NewFIFO(ts ...T) *FIFO {
s := &FIFO{}
for i := range ts {
s.Push(ts[i])
}
return s
}
// Push adds a new element onto the LIFO.
func (s *FIFO) Push(t T) {
node := &queueNode{v: t, next: nil}
if s.front == nil {
s.front = node
s.back = node
} else {
s.back.next = node
s.back = node
}
s.size++
}
// Peek returns the top of the LIFO. If LIFO is empty, returns nil, false.
func (s *FIFO) Peek() (T, bool) {
if s.front == nil {
return nil, false
}
return s.front.v, true
}
// Pop returns the top of the LIFO and removes it. If LIFO is empty returns
// nil, false.
func (s *FIFO) Pop() (T, bool) {
if s.front == nil {
return nil, false
}
node := s.front
s.front = node.next
s.size--
return node.v, true
}
// Size returns the size of the LIFO.
func (s *FIFO) Size() int {
return s.size
}