From 7793021260ca97cf10dfedf2f7942876f949100c Mon Sep 17 00:00:00 2001 From: Kyle Isom Date: Sat, 5 Feb 2022 15:00:39 -0800 Subject: [PATCH] New package: seekbuf (a seekable buffer). --- seekbuf/seekbuf.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 seekbuf/seekbuf.go diff --git a/seekbuf/seekbuf.go b/seekbuf/seekbuf.go new file mode 100644 index 0000000..8285fa4 --- /dev/null +++ b/seekbuf/seekbuf.go @@ -0,0 +1,50 @@ +package seekbuf + +import "io" + +// Buffer is a ReadWriteCloser that supports seeking. It's intended to +// replicate the functionality of bytes.Buffer that I use in my projects. +// +// Note that the seeking is limited to the read marker; all writes are +// append-only. +type Buffer struct { + data []byte + pos int +} + +func New(data []byte) *Buffer { + return &Buffer{ + data: data, + } +} + +func (b *Buffer) Read(p []byte) (int, error) { + if b.pos >= len(b.data) { + return 0, io.EOF + } + + n := copy(p, b.data[b.pos:]) + b.pos += n + return n, nil +} + +func (b *Buffer) Write(p []byte) (int, error) { + b.data = append(b.data, p...) + return len(p), nil +} + +// Seek sets the read pointer to pos. +func (b *Buffer) Seek(pos int) { + b.pos = pos +} + +// Rewind resets the read pointer to 0. +func (b *Buffer) Rewind() { + b.pos = 0 +} + +// Close clears all the data out of the buffer and sets the read position to 0. +func (b *Buffer) Close() error { + b.Clear() + return nil +}