Created
December 25, 2024 06:23
-
-
Save koonix/da43e1668dba252755b81b5149b22874 to your computer and use it in GitHub Desktop.
Ring buffer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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