2018-04-11 13:46:19 +01:00
|
|
|
// Copyright (C) 2018 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package ranger
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
type readerAtRanger struct {
|
|
|
|
r io.ReaderAt
|
|
|
|
size int64
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReaderAtRanger converts a ReaderAt with a given size to a Ranger
|
|
|
|
func ReaderAtRanger(r io.ReaderAt, size int64) Ranger {
|
|
|
|
return &readerAtRanger{
|
|
|
|
r: r,
|
|
|
|
size: size,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *readerAtRanger) Size() int64 {
|
|
|
|
return r.size
|
|
|
|
}
|
|
|
|
|
|
|
|
type readerAtReader struct {
|
|
|
|
r io.ReaderAt
|
|
|
|
offset, length int64
|
|
|
|
}
|
|
|
|
|
2018-06-18 17:46:49 +01:00
|
|
|
func (r *readerAtRanger) Range(offset, length int64) (io.ReadCloser, error) {
|
2018-04-11 13:46:19 +01:00
|
|
|
if offset < 0 {
|
2018-06-18 17:46:49 +01:00
|
|
|
return nil, Error.New("negative offset")
|
2018-04-17 14:39:14 +01:00
|
|
|
}
|
|
|
|
if length < 0 {
|
2018-06-18 17:46:49 +01:00
|
|
|
return nil, Error.New("negative length")
|
2018-04-11 13:46:19 +01:00
|
|
|
}
|
|
|
|
if offset+length > r.size {
|
2018-06-18 17:46:49 +01:00
|
|
|
return nil, Error.New("buffer runoff")
|
2018-04-11 13:46:19 +01:00
|
|
|
}
|
2018-06-18 17:46:49 +01:00
|
|
|
return &readerAtReader{r: r.r, offset: offset, length: length}, nil
|
2018-04-11 13:46:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *readerAtReader) Read(p []byte) (n int, err error) {
|
|
|
|
if r.length == 0 {
|
|
|
|
return 0, io.EOF
|
|
|
|
}
|
|
|
|
if int64(len(p)) > r.length {
|
|
|
|
p = p[:r.length]
|
|
|
|
}
|
|
|
|
n, err = r.r.ReadAt(p, r.offset)
|
|
|
|
r.offset += int64(n)
|
|
|
|
r.length -= int64(n)
|
|
|
|
return n, err
|
|
|
|
}
|
2018-04-17 14:39:14 +01:00
|
|
|
|
|
|
|
func (r *readerAtReader) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|