-
Notifications
You must be signed in to change notification settings - Fork 4
/
queue.go
68 lines (52 loc) · 927 Bytes
/
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
package utils
import "sync"
type Queue[T any] interface {
Add(val T)
Pop() T
Items() []T
Clear()
IsFull() bool
IsEmpty() bool
}
type queue[T any] struct {
mx sync.Mutex
values []T
capacity int
}
func NewQueue[T any](capacity int) Queue[T] {
return &queue[T]{
mx: sync.Mutex{},
values: make([]T, 0),
capacity: capacity,
}
}
func (q *queue[T]) Add(val T) {
q.mx.Lock()
defer q.mx.Unlock()
q.values = append(q.values, val)
}
func (q *queue[T]) Pop() T {
var val T
q.mx.Lock()
defer q.mx.Unlock()
if len(q.values) == 0 {
return val
}
val = q.values[0]
q.values = q.values[1:]
return val
}
func (q *queue[T]) Items() []T {
return q.values
}
func (q *queue[T]) Clear() {
q.mx.Lock()
defer q.mx.Unlock()
q.values = make([]T, 0)
}
func (q *queue[T]) IsFull() bool {
return len(q.values) >= q.capacity
}
func (q *queue[T]) IsEmpty() bool {
return len(q.values) == 0
}