-
Notifications
You must be signed in to change notification settings - Fork 0
/
fifo_buffer.go
91 lines (70 loc) · 1.3 KB
/
fifo_buffer.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
package buffer
import (
"container/list"
"sync"
)
type FifoBuffer struct {
sync.RWMutex
items *list.List
cap int
}
func NewFifoBuffer(cap int) *FifoBuffer {
return &FifoBuffer{items: list.New(), cap: cap}
}
func (s *FifoBuffer) First() interface{} {
s.RLock()
defer s.RUnlock()
if s.Empty() {
return nil
}
return s.items.Front().Value
}
func (s *FifoBuffer) Last() interface{} {
s.RLock()
defer s.RUnlock()
if s.Empty() {
return nil
}
return s.items.Back().Value
}
func (s *FifoBuffer) Append(item interface{}) {
s.Lock()
defer s.Unlock()
if s.Full() {
s.Unlock()
s.Shift()
s.Lock()
}
s.items.PushBack(item)
}
func (s *FifoBuffer) Shift() {
s.Lock()
defer s.Unlock()
if s.Empty() {
return
}
if firstContainerItem := s.items.Front(); firstContainerItem != nil {
s.items.Remove(firstContainerItem)
}
}
func (s *FifoBuffer) Full() bool {
return s.Len() == s.cap
}
func (s *FifoBuffer) Empty() bool {
return s.Len() == 0
}
func (s *FifoBuffer) GetItems() []interface{} {
s.RLock()
defer s.RUnlock()
items := make([]interface{}, 0, s.items.Len())
for item := s.items.Front(); item != nil; item = item.Next() {
items = append(items, item.Value)
}
return items
}
func (s *FifoBuffer) Len() int {
return s.items.Len()
}
func (s *FifoBuffer) Cap() int {
return s.cap
}