Created
May 12, 2016 16:42
-
-
Save gobwas/6c5350b7cc4fca2ce567f4571d9fd06e to your computer and use it in GitHub Desktop.
Ring buffer
This file contains 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
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