Files
hamlab/internal/term/ring.go
T

38 lines
717 B
Go

package term
// Ring is a fixed-size byte ring buffer holding the most recent output.
type Ring struct {
buf []byte
start int
n int
}
func NewRing(size int) *Ring { return &Ring{buf: make([]byte, size)} }
func (r *Ring) Write(p []byte) {
size := len(r.buf)
if len(p) >= size {
copy(r.buf, p[len(p)-size:])
r.start, r.n = 0, size
return
}
end := (r.start + r.n) % size
first := copy(r.buf[end:], p)
copy(r.buf, p[first:])
if r.n+len(p) > size {
r.start = (end + len(p)) % size
r.n = size
} else {
r.n += len(p)
}
}
func (r *Ring) Bytes() []byte {
out := make([]byte, r.n)
first := copy(out, r.buf[r.start:])
if first < r.n {
copy(out[first:], r.buf[:r.n-first])
}
return out
}