2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-04-24 03:16:34 +01:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package ranger
|
|
|
|
|
|
|
|
import (
|
2018-09-14 15:10:43 +01:00
|
|
|
"context"
|
2018-04-24 03:16:34 +01:00
|
|
|
"io"
|
|
|
|
"os"
|
2018-07-16 20:22:34 +01:00
|
|
|
|
2019-02-06 05:41:41 +00:00
|
|
|
"github.com/zeebo/errs"
|
2018-04-24 03:16:34 +01:00
|
|
|
)
|
|
|
|
|
2018-09-14 15:10:43 +01:00
|
|
|
type fileRanger struct {
|
|
|
|
path string
|
|
|
|
size int64
|
|
|
|
}
|
|
|
|
|
|
|
|
// FileRanger returns a Ranger from a path.
|
|
|
|
func FileRanger(path string) (Ranger, error) {
|
|
|
|
info, err := os.Stat(path)
|
2018-04-24 03:16:34 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, Error.Wrap(err)
|
|
|
|
}
|
2018-09-14 15:10:43 +01:00
|
|
|
return &fileRanger{path: path, size: info.Size()}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rr *fileRanger) Size() int64 {
|
|
|
|
return rr.size
|
2018-04-24 03:16:34 +01:00
|
|
|
}
|
|
|
|
|
2018-09-14 15:10:43 +01:00
|
|
|
func (rr *fileRanger) Range(ctx context.Context, offset, length int64) (io.ReadCloser, error) {
|
|
|
|
if offset < 0 {
|
|
|
|
return nil, Error.New("negative offset")
|
|
|
|
}
|
|
|
|
if length < 0 {
|
|
|
|
return nil, Error.New("negative length")
|
|
|
|
}
|
|
|
|
if offset+length > rr.size {
|
|
|
|
return nil, Error.New("range beyond end")
|
|
|
|
}
|
|
|
|
|
|
|
|
fh, err := os.Open(rr.path)
|
2018-04-24 03:16:34 +01:00
|
|
|
if err != nil {
|
2018-09-14 15:10:43 +01:00
|
|
|
return nil, Error.Wrap(err)
|
2018-04-24 03:16:34 +01:00
|
|
|
}
|
2018-09-14 15:10:43 +01:00
|
|
|
_, err = fh.Seek(offset, io.SeekStart)
|
2018-04-24 03:16:34 +01:00
|
|
|
if err != nil {
|
2019-02-06 05:41:41 +00:00
|
|
|
return nil, Error.Wrap(errs.Combine(err, fh.Close()))
|
2018-04-24 03:16:34 +01:00
|
|
|
}
|
2019-02-06 05:41:41 +00:00
|
|
|
|
|
|
|
return &FileReader{fh, length}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// FileReader implements limit reader with io.EOF only on last read.
|
|
|
|
type FileReader struct {
|
|
|
|
file *os.File
|
|
|
|
remaining int64
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read reads from the underlying file.
|
|
|
|
func (reader *FileReader) Read(data []byte) (n int, err error) {
|
|
|
|
if reader.remaining <= 0 {
|
|
|
|
return 0, io.EOF
|
|
|
|
}
|
|
|
|
if int64(len(data)) > reader.remaining {
|
|
|
|
data = data[0:reader.remaining]
|
|
|
|
}
|
|
|
|
n, err = reader.file.Read(data)
|
|
|
|
reader.remaining -= int64(n)
|
|
|
|
if err == io.EOF && reader.remaining == 0 {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the underlying file.
|
|
|
|
func (reader *FileReader) Close() error {
|
|
|
|
return reader.file.Close()
|
2018-04-24 03:16:34 +01:00
|
|
|
}
|