Created
April 24, 2020 19:51
-
-
Save icholy/95641ffeacc178015275413b8d1fbed5 to your computer and use it in GitHub Desktop.
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
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