2018-04-24 03:16:34 +01:00
|
|
|
// Copyright (C) 2018 Storj Labs, Inc.
|
|
|
|
// 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
|
|
|
|
2018-09-14 15:10:43 +01:00
|
|
|
"storj.io/storj/pkg/utils"
|
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 {
|
2018-09-14 15:10:43 +01:00
|
|
|
err = utils.CombineErrors(err, fh.Close())
|
|
|
|
return nil, Error.Wrap(err)
|
2018-04-24 03:16:34 +01:00
|
|
|
}
|
2018-09-14 15:10:43 +01:00
|
|
|
return struct {
|
|
|
|
io.Reader
|
|
|
|
io.Closer
|
|
|
|
}{
|
|
|
|
Reader: io.LimitReader(fh, length),
|
|
|
|
Closer: fh,
|
|
|
|
}, nil
|
2018-04-24 03:16:34 +01:00
|
|
|
}
|