Skip to content

Instantly share code, notes, and snippets.

@gobwas
Created May 12, 2016 16:42
Show Gist options
  • Save gobwas/6c5350b7cc4fca2ce567f4571d9fd06e to your computer and use it in GitHub Desktop.
Save gobwas/6c5350b7cc4fca2ce567f4571d9fd06e to your computer and use it in GitHub Desktop.
Ring buffer
type ring struct {
data []byte
size int
pos int
len int
}
func newRing(size int) *ring {
return &ring{
size: size,
data: make([]byte, size),
}
}
func (r *ring) append(b ...byte) {
var start int
if len(b) > r.size {
// get bytes that could be stored
// from the end of b
start = len(b) - r.size
}
var end int
if len(b) < r.size-r.pos {
end = len(b)
} else {
end = r.size - r.pos
}
rc := copy(r.data[r.pos:], b[start:end])
lc := copy(r.data[:r.pos], b[start+end:])
r.pos = (r.pos + rc + lc) % r.size
if r.len+rc+lc > r.size {
r.len = r.size
} else {
r.len += rc + lc
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment