-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevents.go
72 lines (61 loc) · 1.02 KB
/
events.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 go_gb
import (
"strings"
"sync"
)
var (
Events = NewEventQueue(1000)
)
type event struct {
data string
prev, next *event
}
func (e event) String() string {
return e.data
}
type eventQueue struct {
size, cap int
head, tail *event
mutex sync.Mutex
}
func (e *eventQueue) String() string {
var sb strings.Builder
for node := e.head; node != nil; node = node.next {
sb.WriteString(node.String() + "\n")
}
return sb.String()
}
func NewEventQueue(cap int) *eventQueue {
return &eventQueue{cap: cap}
}
func (e *eventQueue) Add(ev string) {
e.mutex.Lock()
defer e.mutex.Unlock()
newNode := &event{
data: ev,
prev: e.tail,
next: nil,
}
if e.tail == nil {
e.head = newNode
e.tail = newNode
e.size = 1
return
}
if e.size == e.cap {
_ = e.pop()
e.tail.next = newNode
e.tail = newNode
return
}
e.tail.next = newNode
e.tail = newNode
e.size += 1
}
func (e *eventQueue) pop() *event {
oldHead := e.head
e.head = e.head.next
e.head.prev = nil
oldHead.next = nil
return oldHead
}