A ring buffer, also known as a circular buffer, is a fixed-size data structure that efficiently uses memory by overwriting old data when new data arrives. This makes it particularly useful for applications such as streaming data, producer-consumer problems, and buffering I/O.
Below is an example implementation of a ring buffer in Go.
package main
import (
"fmt"
)
type RingBuffer struct {
buffer []interface{}
head int
tail int
size int
}
func NewRingBuffer(capacity int) *RingBuffer {
return &RingBuffer{
buffer: make([]interface{}, capacity),
head: 0,
tail: 0,
size: 0,
}
}
func (rb *RingBuffer) Push(value interface{}) {
rb.buffer[rb.tail] = value
rb.tail = (rb.tail + 1) % len(rb.buffer)
if rb.size == len(rb.buffer) {
rb.head = (rb.head + 1) % len(rb.buffer) // Overwrite if full
} else {
rb.size++
}
}
func (rb *RingBuffer) Pop() (interface{}, bool) {
if rb.size == 0 {
return nil, false
}
value := rb.buffer[rb.head]
rb.head = (rb.head + 1) % len(rb.buffer)
rb.size--
return value, true
}
func (rb *RingBuffer) IsEmpty() bool {
return rb.size == 0
}
func main() {
rb := NewRingBuffer(5)
rb.Push(1)
rb.Push(2)
rb.Push(3)
rb.Push(4)
rb.Push(5)
rb.Push(6) // This will overwrite the oldest value (1)
for !rb.IsEmpty() {
if value, ok := rb.Pop(); ok {
fmt.Println(value)
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?