lib/readers: add NoSeeker to adapt io.Reader to io.ReadSeeker

This commit is contained in:
Nick Craig-Wood 2023-08-15 21:03:57 +01:00
parent d61328e459
commit e8f3f98aa0
2 changed files with 53 additions and 0 deletions

22
lib/readers/noseeker.go Normal file
View File

@ -0,0 +1,22 @@
package readers
import (
"errors"
"io"
)
var (
errCantSeek = errors.New("can't Seek")
)
// NoSeeker adapts an io.Reader into an io.ReadSeeker.
//
// However if Seek() is called it will return an error.
type NoSeeker struct {
io.Reader
}
// Seek the stream - returns an error
func (r NoSeeker) Seek(offset int64, whence int) (abs int64, err error) {
return 0, errCantSeek
}

View File

@ -0,0 +1,31 @@
package readers
import (
"bytes"
"io"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNoSeeker(t *testing.T) {
r := bytes.NewBufferString("hello")
rs := NoSeeker{Reader: r}
// Check read
b := make([]byte, 4)
n, err := rs.Read(b)
assert.NoError(t, err)
assert.Equal(t, 4, n)
assert.Equal(t, []byte("hell"), b)
// Check seek
_, err = rs.Seek(0, io.SeekCurrent)
assert.Equal(t, errCantSeek, err)
}
// check interfaces
var (
_ io.Reader = NoSeeker{}
_ io.Seeker = NoSeeker{}
)