storj/pkg/ranger/file.go

60 lines
1.1 KiB
Go
Raw Normal View History

2018-04-24 03:16:34 +01:00
// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package ranger
import (
"context"
2018-04-24 03:16:34 +01:00
"io"
"os"
"storj.io/storj/pkg/utils"
2018-04-24 03:16:34 +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)
}
return &fileRanger{path: path, size: info.Size()}, nil
}
func (rr *fileRanger) Size() int64 {
return rr.size
2018-04-24 03:16:34 +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 {
return nil, Error.Wrap(err)
2018-04-24 03:16:34 +01:00
}
_, err = fh.Seek(offset, io.SeekStart)
2018-04-24 03:16:34 +01:00
if err != nil {
err = utils.CombineErrors(err, fh.Close())
return nil, Error.Wrap(err)
2018-04-24 03:16:34 +01:00
}
return struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(fh, length),
Closer: fh,
}, nil
2018-04-24 03:16:34 +01:00
}