2024-06-16 14:49:15 +02:00
|
|
|
package ringbuffer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type RingBuffer struct {
|
|
|
|
buffer []string
|
|
|
|
size int
|
|
|
|
head int
|
|
|
|
tail int
|
|
|
|
mu sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRingBuffer(size int) *RingBuffer {
|
|
|
|
return &RingBuffer{
|
|
|
|
buffer: make([]string, size),
|
|
|
|
size: size,
|
|
|
|
head: -1,
|
|
|
|
tail: -1,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rb *RingBuffer) Add(item string) {
|
|
|
|
rb.mu.Lock()
|
|
|
|
defer rb.mu.Unlock()
|
|
|
|
|
|
|
|
if (rb.tail+1)%rb.size == rb.head {
|
|
|
|
rb.head = (rb.head + 1) % rb.size
|
|
|
|
}
|
|
|
|
|
|
|
|
rb.tail = (rb.tail + 1) % rb.size
|
|
|
|
rb.buffer[rb.tail] = item
|
|
|
|
|
|
|
|
if rb.head == -1 {
|
|
|
|
rb.head = rb.tail
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rb *RingBuffer) GetLast() (string, int) {
|
|
|
|
rb.mu.Lock()
|
|
|
|
defer rb.mu.Unlock()
|
|
|
|
|
|
|
|
if rb.head == -1 {
|
|
|
|
return "", -1
|
|
|
|
}
|
|
|
|
|
|
|
|
return rb.buffer[rb.tail], rb.tail
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rb *RingBuffer) WaitForNewItem() string {
|
2024-06-16 15:27:46 +02:00
|
|
|
rb.mu.Lock()
|
|
|
|
defer rb.mu.Unlock()
|
|
|
|
|
|
|
|
if rb.tail == -1 {
|
|
|
|
return ""
|
2024-06-16 14:49:15 +02:00
|
|
|
}
|
2024-06-16 15:27:46 +02:00
|
|
|
|
|
|
|
return rb.buffer[rb.tail]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rb *RingBuffer) IsEmpty() bool {
|
|
|
|
rb.mu.Lock()
|
|
|
|
defer rb.mu.Unlock()
|
|
|
|
|
|
|
|
return rb.head == -1
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rb *RingBuffer) GetLastPosition() int {
|
|
|
|
rb.mu.Lock()
|
|
|
|
defer rb.mu.Unlock()
|
|
|
|
|
|
|
|
return rb.tail
|
2024-06-16 14:49:15 +02:00
|
|
|
}
|
|
|
|
|
2024-06-18 17:38:01 +02:00
|
|
|
func (rb *RingBuffer) ContainsItem(item string) bool {
|
|
|
|
rb.mu.Lock()
|
|
|
|
defer rb.mu.Unlock()
|
|
|
|
|
2024-06-18 17:49:07 +02:00
|
|
|
if rb.head == -1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-06-18 17:38:01 +02:00
|
|
|
for i := 0; i < rb.size; i++ {
|
|
|
|
index := (rb.head + i) % rb.size
|
|
|
|
if rb.buffer[index] == item {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
2024-06-18 17:49:07 +02:00
|
|
|
|