/
cache.go
72 lines (58 loc) · 1.26 KB
/
cache.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 pufferpanel
import (
"github.com/pufferpanel/pufferpanel/v3/config"
"sync"
"time"
)
type Message struct {
msg []byte
time int64
}
type MemoryCache struct {
Buffer []Message
Capacity int
Size int
Lock sync.RWMutex
}
func CreateCache() *MemoryCache {
capacity := config.ConsoleBuffer.Value()
if capacity <= 0 {
capacity = 50
}
return &MemoryCache{
Buffer: make([]Message, 0),
Capacity: capacity * 1024, //convert to KB
}
}
func (c *MemoryCache) Read() (msg []byte, lastTime int64) {
msg, lastTime = c.ReadFrom(0)
return
}
func (c *MemoryCache) ReadFrom(startTime int64) (msg []byte, lastTime int64) {
c.Lock.RLock()
defer c.Lock.RUnlock()
lastTime = time.Now().UnixMicro()
msg = make([]byte, 0)
for _, v := range c.Buffer {
if v.time > startTime {
msg = append(msg, v.msg...)
}
}
return
}
func (c *MemoryCache) Write(b []byte) (n int, err error) {
c.Lock.Lock()
defer c.Lock.Unlock()
n = len(b)
//remove data until we've gotten small enough
var pop Message
for c.Size+n > c.Capacity {
pop, c.Buffer = c.Buffer[0], c.Buffer[1:]
c.Size = c.Size - len(pop.msg)
}
co := make([]byte, len(b))
copy(co, b)
c.Buffer = append(c.Buffer, Message{msg: co, time: time.Now().UnixMicro()})
c.Size = c.Size + n
return
}