-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
56 lines (46 loc) · 810 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
package discobot
import (
"context"
"fmt"
)
type Queue[T any] struct {
playQueue chan T
capacity int
}
func NewQueue[T any](capacity int) Queue[T] {
queue := Queue[T]{capacity: capacity}
queue.Clean()
return queue
}
func (pq *Queue[T]) Push(item T) error {
select {
case pq.playQueue <- item:
default:
return fmt.Errorf("queue is full")
}
return nil
}
func (pq *Queue[T]) Pop(ctx context.Context) (T, error) {
for {
select {
case <-ctx.Done():
var empty T
return empty, ctx.Err()
case item, ok := <-pq.playQueue:
if !ok {
continue
}
return item, nil
}
}
}
func (pq *Queue[T]) Clean() {
oldChan := pq.playQueue
pq.playQueue = make(chan T, pq.capacity)
if oldChan != nil {
close(oldChan)
}
}
func (pq *Queue[T]) Len() int {
return len(pq.playQueue)
}