SmsHook/ringbuffer/ringbuffer.go

76 lines
1.0 KiB
Go
Raw Permalink Normal View History

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
}