forked from gwuhaolin/livego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
executable file
·72 lines (56 loc) · 1.19 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
package queue
import (
"sync"
"github.com/chornenky/livego/av"
)
// Queue is a basic FIFO queue for Messages.
type Queue struct {
maxSize int
list []*av.Packet
mutex sync.Mutex
}
// NewQueue returns a new Queue. If maxSize is greater than zero the queue will
// not grow more than the defined size.
func NewQueue(maxSize int) *Queue {
return &Queue{
maxSize: maxSize,
}
}
// Push adds a message to the queue.
func (q *Queue) Push(msg *av.Packet) {
q.mutex.Lock()
defer q.mutex.Unlock()
if len(q.list) == q.maxSize {
q.pop()
}
q.list = append(q.list, msg)
}
// Pop removes and returns a message from the queue in first to last order.
func (q *Queue) Pop() *av.Packet {
q.mutex.Lock()
defer q.mutex.Unlock()
if len(q.list) == 0 {
return nil
}
return q.pop()
}
func (q *Queue) pop() *av.Packet {
x := len(q.list) - 1
msg := q.list[x]
q.list = q.list[:x]
return msg
}
// Len returns the length of the queue.
func (q *Queue) Len() int {
q.mutex.Lock()
defer q.mutex.Unlock()
return len(q.list)
}
// All returns and removes all messages from the queue.
func (q *Queue) All() []*av.Packet {
q.mutex.Lock()
defer q.mutex.Unlock()
cache := q.list
q.list = nil
return cache
}