7

Is there an implementation of io.ReaderAt that can be created from an implementation of io.Reader without first being read into a []byte or string?

2
  • That limitation means that you cannot seek backward nor re-read any read section. Is that OK?
    – Tim Cooper
    Oct 23, 2016 at 16:29
  • Hey Tim, yeah, that'd be fine. The end goal would be a SectionReader, so no reading backwards and no re-reading necessary.
    – Rob
    Oct 23, 2016 at 16:38

2 Answers 2

8

Something like the below. Note bytes.Reader implements the ReadAt(...) method/function: https://golang.org/pkg/bytes/#Reader.ReadAt. So the line bytes.NewReader is esssentially what you are looking for.

Getting a bytes.Reader:

var ioReader io.Reader
...
buff := bytes.NewBuffer([]byte{})
size, err := io.Copy(buff, ioReader)
if err != nil {
    return err
}

reader := bytes.NewReader(buff.Bytes())
// Do something with `reader`
6

Yes, this is possible. As mentioned in my comment above, the implementation is limited in that you cannot seek backward nor can you re-read a section that has already been read.

Here is a example implementation:

type unbufferedReaderAt struct {
    R io.Reader
    N int64
}

func NewUnbufferedReaderAt(r io.Reader) io.ReaderAt {
    return &unbufferedReaderAt{R: r}
}

func (u *unbufferedReaderAt) ReadAt(p []byte, off int64) (n int, err error) {
    if off < u.N {
        return 0, errors.New("invalid offset")
    }
    diff := off - u.N
    written, err := io.CopyN(ioutil.Discard, u.R, diff)
    u.N += written
    if err != nil {
        return 0, err
    }

    n, err = u.R.Read(p)
    u.N += int64(n)
    return
}

Example usage:

s := strings.NewReader("hello world")

var b [5]byte
ura := NewUnbufferedReaderAt(s)
if _, err := ura.ReadAt(b[:], 0); err != nil {
    panic(err)
}
fmt.Printf("%s\n", b[:]) // prints "hello"

/*
if _, err := ura.ReadAt(b[:], 0); err != nil {
    panic(err) // panics
}
fmt.Printf("%s\n", b[:])
*/

if _, err := ura.ReadAt(b[:], 6); err != nil {
    panic(err)
}
fmt.Printf("%s\n", b[:]) // prints "world"
2
  • This is great! Thanks :)
    – Rob
    Oct 23, 2016 at 18:50
  • 4
    2nd return should be return written, err instead of return 0, err.
    – icza
    Oct 23, 2016 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.