-
Notifications
You must be signed in to change notification settings - Fork 106
/
ringbuf.go
47 lines (40 loc) · 841 Bytes
/
ringbuf.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
package byzcoin
import (
"bytes"
"sync"
)
// newRingBuf initializes a ring buffer. It's used in byzcoin for recording
// transaction errors. But it is general enough to be used for other purposes.
func newRingBuf(size int) ringBuf {
return ringBuf{
current: 0,
size: size,
items: make([]ringBufElem, size),
}
}
type ringBufElem struct {
key []byte
value string
}
type ringBuf struct {
sync.RWMutex
current int
size int
items []ringBufElem
}
func (b *ringBuf) add(key []byte, value string) {
b.Lock()
defer b.Unlock()
b.items[b.current] = ringBufElem{key, value}
b.current = (b.current + 1) % b.size
}
func (b *ringBuf) get(key []byte) (string, bool) {
b.RLock()
defer b.RUnlock()
for _, item := range b.items {
if bytes.Equal(item.key, key) {
return item.value, true
}
}
return "", false
}