-
Notifications
You must be signed in to change notification settings - Fork 45
/
chunk_queue.go
68 lines (54 loc) · 1.23 KB
/
chunk_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
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package vnet
import (
"sync"
)
type chunkQueue struct {
chunks []Chunk
maxSize int // 0 or negative value: unlimited
maxBytes int // 0 or negative value: unlimited
currentBytes int
mutex sync.RWMutex
}
func newChunkQueue(maxSize int, maxBytes int) *chunkQueue {
return &chunkQueue{
chunks: []Chunk{},
maxSize: maxSize,
maxBytes: maxBytes,
currentBytes: 0,
mutex: sync.RWMutex{},
}
}
func (q *chunkQueue) push(c Chunk) bool {
q.mutex.Lock()
defer q.mutex.Unlock()
if q.maxSize > 0 && len(q.chunks) >= q.maxSize {
return false // dropped
}
if q.maxBytes > 0 && q.currentBytes+len(c.UserData()) >= q.maxBytes {
return false
}
q.currentBytes += len(c.UserData())
q.chunks = append(q.chunks, c)
return true
}
func (q *chunkQueue) pop() (Chunk, bool) {
q.mutex.Lock()
defer q.mutex.Unlock()
if len(q.chunks) == 0 {
return nil, false
}
c := q.chunks[0]
q.chunks = q.chunks[1:]
q.currentBytes -= len(c.UserData())
return c, true
}
func (q *chunkQueue) peek() Chunk {
q.mutex.RLock()
defer q.mutex.RUnlock()
if len(q.chunks) == 0 {
return nil
}
return q.chunks[0]
}