Documentation
¶
Overview ¶
Package ringbuffer provides a thread-safe generic ring buffer implementation.
A ring buffer (circular buffer) is a fixed-size buffer that wraps around when full. This implementation uses Go generics to support any type and provides thread-safe operations through mutex locking.
Example usage:
type Event struct {
Timestamp time.Time
Message string
}
buffer := ringbuffer.New[Event](100)
buffer.Add(Event{Timestamp: time.Now(), Message: "Event 1"})
recent := buffer.GetLast(10) // Get last 10 events
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type RingBuffer ¶
type RingBuffer[T any] struct { // contains filtered or unexported fields }
RingBuffer is a thread-safe circular buffer that stores a fixed number of items. When the buffer is full, new items overwrite the oldest items.
The buffer uses Go generics to support any type T.
func New ¶
func New[T any](size int) *RingBuffer[T]
New creates a new ring buffer with the specified capacity.
The size parameter determines the maximum number of items the buffer can hold. Once full, adding new items will overwrite the oldest items.
Example:
buffer := ringbuffer.New[string](100) // Can hold up to 100 strings
func (*RingBuffer[T]) Add ¶
func (rb *RingBuffer[T]) Add(item T)
Add inserts an item into the buffer.
If the buffer is full, the oldest item is overwritten. This operation is thread-safe.
Example:
buffer.Add("event 1")
buffer.Add("event 2")
func (*RingBuffer[T]) Cap ¶
func (rb *RingBuffer[T]) Cap() int
Cap returns the maximum capacity of the buffer.
This is the size specified when creating the buffer with New(). This operation is thread-safe.
Example:
capacity := buffer.Cap() // Returns the buffer's maximum size
func (*RingBuffer[T]) Clear ¶
func (rb *RingBuffer[T]) Clear()
Clear removes all items from the buffer, resetting it to empty state.
This operation is thread-safe.
Example:
buffer.Clear() // Buffer is now empty
func (*RingBuffer[T]) GetAll ¶
func (rb *RingBuffer[T]) GetAll() []T
GetAll returns all items currently in the buffer, in chronological order.
The returned slice is ordered from oldest to newest. This operation is thread-safe.
Example:
all := buffer.GetAll()
func (*RingBuffer[T]) GetLast ¶
func (rb *RingBuffer[T]) GetLast(n int) []T
GetLast returns the n most recently added items, in chronological order.
If n is greater than the number of items in the buffer, all items are returned. The returned slice is ordered from oldest to newest. This operation is thread-safe.
Example:
buffer.Add("event 1")
buffer.Add("event 2")
buffer.Add("event 3")
recent := buffer.GetLast(2) // Returns ["event 2", "event 3"]
func (*RingBuffer[T]) Len ¶
func (rb *RingBuffer[T]) Len() int
Len returns the current number of items in the buffer.
This operation is thread-safe.
Example:
count := buffer.Len() // Returns number of items currently stored