goext/dataext/bufferedReadCloser.go

57 lines
927 B
Go
Raw Normal View History

2022-10-27 16:00:57 +02:00
package dataext
import "io"
type BufferedReadCloser interface {
io.ReadCloser
BufferedAll() ([]byte, error)
}
type bufferedReadCloser struct {
buffer []byte
inner io.ReadCloser
finished bool
}
func (b *bufferedReadCloser) Read(p []byte) (int, error) {
n, err := b.inner.Read(p)
if n > 0 {
b.buffer = append(b.buffer, p[0:n]...)
}
if err == io.EOF {
b.finished = true
}
return n, err
}
func NewBufferedReadCloser(sub io.ReadCloser) BufferedReadCloser {
return &bufferedReadCloser{
buffer: make([]byte, 0, 1024),
inner: sub,
finished: false,
}
}
func (b *bufferedReadCloser) Close() error {
err := b.inner.Close()
if err != nil {
b.finished = true
}
return err
}
func (b *bufferedReadCloser) BufferedAll() ([]byte, error) {
arr := make([]byte, 1024)
for !b.finished {
_, err := b.Read(arr)
if err != nil && err != io.EOF {
return nil, err
}
}
return b.buffer, nil
}