Skip to content

Instantly share code, notes, and snippets.

@koonix
Created December 25, 2024 06:23
Show Gist options
  • Save koonix/da43e1668dba252755b81b5149b22874 to your computer and use it in GitHub Desktop.
Save koonix/da43e1668dba252755b81b5149b22874 to your computer and use it in GitHub Desktop.
Ring buffer.
package ringbuf
type RingBuf[T any] struct {
Buf []T
head int
tail int
}
func New[T any](size int) *RingBuf[T] {
return &RingBuf[T]{
Buf: make([]T, size),
}
}
func (r *RingBuf[T]) Write(v T) {
r.Buf[r.head] = v
r.head++
if r.head >= len(r.Buf) {
r.head = 0
}
if r.tail == r.head {
r.tail++
if r.tail >= len(r.Buf) {
r.tail = 0
}
}
}
func (r *RingBuf[T]) Read() T {
v := r.Buf[r.tail]
r.tail++
if r.tail >= len(r.Buf) {
r.tail = 0
}
return v
}
func (r *RingBuf[T]) Len() int {
if r.head >= r.tail {
return r.head - r.tail + 1
}
return (r.tail + 1) + (len(r.Buf) - r.head)
}
func (r *RingBuf[T]) Resize(size int) {
newBuf := make([]T, size)
copy(newBuf, r.Buf)
r.Buf = newBuf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment