RingChan is a thread-safe, fixed-capacity ring buffer implemented as a channel in Go. It mimics Go's channel behavior while providing ring-buffer semantics — meaning new items overwrite the oldest when full.
- Fixed-size buffer with overwrite behavior
- Range-friendly: can be iterated using
for ... range
- Safe for concurrent producers and consumers
go get github.com/floatdrop/ringchan
package main
import (
"fmt"
"time"
"github.com/floatdrop/ringchan"
)
func main() {
input := make(chan string, 5)
ring := ringchan.New(input, 3)
go func() {
inputs := []string{"A", "B", "C", "D", "E"}
for _, v := range inputs {
input <- v
}
close(input)
}()
time.Sleep(50 * time.Millisecond)
for v := range ring.C {
fmt.Println("Got:", v)
}
// Output:
// Got: C
// Got: D
// Got: E
}
go test -bench=. -benchmem
goos: darwin
goarch: arm64
pkg: github.com/floatdrop/ringchan
cpu: Apple M1 Pro
BenchmarkSingleSender-10 7097070 167.3 ns/op 0 B/op 0 allocs/op
BenchmarkParallelSenders-10 4145682 295.0 ns/op 0 B/op 0 allocs/op
PASS
coverage: 90.9% of statements
ok github.com/floatdrop/ringchan 3.050s
For high-throughput write-heavy workloads it is better to use preallocated ringbuffer, like https://github.com/peterbourgon/rb
This project is licensed under the MIT License - see the LICENSE file for details.