SmsHook/ringbuffer/ringbuffer.go
2024-06-18 17:49:07 +02:00

94 lines
1.3 KiB
Go

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 {
rb.mu.Lock()
defer rb.mu.Unlock()
if rb.tail == -1 {
return ""
}
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
}
func (rb *RingBuffer) ContainsItem(item string) bool {
rb.mu.Lock()
defer rb.mu.Unlock()
if rb.head == -1 {
return false
}
for i := 0; i < rb.size; i++ {
index := (rb.head + i) % rb.size
if rb.buffer[index] == item {
return true
}
}
return false
}