forked from okx/xlayer-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
67 lines (58 loc) · 1.32 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
package state
import (
"fmt"
"sync"
)
// ErrQueueEmpty is returned when a queue operation
// depends on the queue to not be empty, but it is empty
var ErrQueueEmpty = fmt.Errorf("queue is empty")
// Queue is a generic queue implementation that implements FIFO
type Queue[T any] struct {
items []T
mutex *sync.Mutex
}
// NewQueue creates a new instance of queue and initializes it
func NewQueue[T any]() *Queue[T] {
return &Queue[T]{
items: make([]T, 0),
mutex: &sync.Mutex{},
}
}
// Push enqueue an item
func (q *Queue[T]) Push(item T) {
q.mutex.Lock()
defer q.mutex.Unlock()
q.items = append(q.items, item)
}
// Top returns the top level item without removing it
func (q *Queue[T]) Top() (T, error) {
q.mutex.Lock()
defer q.mutex.Unlock()
var v T
if len(q.items) == 0 {
return v, ErrQueueEmpty
}
return q.items[0], nil
}
// Pop returns the top level item and unqueues it
func (q *Queue[T]) Pop() (T, error) {
q.mutex.Lock()
defer q.mutex.Unlock()
var v T
if len(q.items) == 0 {
return v, ErrQueueEmpty
}
v = q.items[0]
q.items = q.items[1:]
return v, nil
}
// Len returns the size of the queue
func (q *Queue[T]) Len() int {
q.mutex.Lock()
defer q.mutex.Unlock()
return len(q.items)
}
// IsEmpty returns false if the queue has itens, otherwise true
func (q *Queue[T]) IsEmpty() bool {
return q.Len() == 0
}