SmsHook/ringbuffer/ringbuffer.go
2024-06-16 15:27:46 +02:00

76 lines
1.0 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
}