Skip to content

Instantly share code, notes, and snippets.

@icholy
Created April 24, 2020 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icholy/95641ffeacc178015275413b8d1fbed5 to your computer and use it in GitHub Desktop.
Save icholy/95641ffeacc178015275413b8d1fbed5 to your computer and use it in GitHub Desktop.
package ring
type T int
type Buffer struct {
data []T
size int
start int
filled int
}
func New(size int) *Buffer {
return &Buffer{
data: make([]T, size),
size: size,
}
}
func (b *Buffer) Add(v T) {
end := (b.start + b.filled) % b.size
b.data[end] = v
if b.filled < b.size {
b.filled++
} else {
b.start = (b.start + 1) % b.size
}
}
func (b *Buffer) Len() int { return b.filled }
func (b *Buffer) At(i int) T {
return b.data[(b.start+i)%b.size]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment