This repository has been archived by the owner on Feb 11, 2021. It is now read-only.
forked from titanous/go-wireguard
-
Notifications
You must be signed in to change notification settings - Fork 2
/
queue.go
100 lines (79 loc) · 1.3 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package wireguard
// PacketQueue is a FIFO queue backed by a single linked list.
import "sync"
type PacketQueue struct {
head, tail *node
len int
sync.RWMutex
}
type node struct {
value []byte
next *node
}
func (pq *PacketQueue) BoundedAppend(v []byte, maxSize int) {
pq.Lock()
defer pq.Unlock()
if maxSize > 0 {
for pq.len > maxSize {
pq.Pop()
}
}
n := &node{value: v}
if pq.len > 0 {
pq.tail.next = n
pq.tail = n
} else {
pq.head = n
pq.tail = n
}
pq.len++
}
func (pq *PacketQueue) Append(v []byte) {
pq.Lock()
defer pq.Unlock()
n := &node{value: v}
if pq.len > 0 {
pq.tail.next = n
pq.tail = n
} else {
pq.head = n
pq.tail = n
}
pq.len++
}
func (pq *PacketQueue) Pop() (v []byte) {
pq.Lock()
defer pq.Unlock()
v = nil
if pq.len > 0 {
v = pq.head.value
pq.len--
pq.head = pq.head.next
if pq.len == 0 {
pq.tail = nil
}
}
return v
}
func (pq *PacketQueue) Peek() []byte {
pq.RLock()
defer pq.RUnlock()
if pq.len == 0 {
return nil
}
return pq.head.value
}
func (pq *PacketQueue) Len() int {
pq.RLock()
defer pq.RUnlock()
return pq.len
}
func (pq *PacketQueue) Steal() *PacketQueue {
pq.Lock()
defer pq.Unlock()
newq := &PacketQueue{head: pq.head, tail: pq.tail, len: pq.len}
pq.len = 0
pq.head = nil
pq.tail = nil
return newq
}