From e8f3f98aa086936e7975443f4f6f37ccd3c32a73 Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Tue, 15 Aug 2023 21:03:57 +0100 Subject: [PATCH] lib/readers: add NoSeeker to adapt io.Reader to io.ReadSeeker --- lib/readers/noseeker.go | 22 ++++++++++++++++++++++ lib/readers/noseeker_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 lib/readers/noseeker.go create mode 100644 lib/readers/noseeker_test.go diff --git a/lib/readers/noseeker.go b/lib/readers/noseeker.go new file mode 100644 index 000000000..1cd7e762c --- /dev/null +++ b/lib/readers/noseeker.go @@ -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 +} diff --git a/lib/readers/noseeker_test.go b/lib/readers/noseeker_test.go new file mode 100644 index 000000000..3f8d88c2f --- /dev/null +++ b/lib/readers/noseeker_test.go @@ -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{} +)