torrent/storage/piece_resource.go

81 lines
1.6 KiB
Go
Raw Normal View History

2016-05-16 08:44:58 +00:00
package storage
import (
"io"
"path"
"github.com/anacrolix/missinggo"
2016-05-16 12:32:00 +00:00
"github.com/anacrolix/missinggo/resource"
2016-05-16 08:44:58 +00:00
"github.com/anacrolix/torrent/metainfo"
)
type piecePerResource struct {
2016-05-16 12:32:00 +00:00
p resource.Provider
2016-05-16 08:44:58 +00:00
}
2016-05-16 12:32:00 +00:00
func NewResourcePieces(p resource.Provider) Client {
2016-05-16 08:44:58 +00:00
return &piecePerResource{
p: p,
}
}
func (s *piecePerResource) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (Torrent, error) {
2016-05-16 08:44:58 +00:00
return s, nil
}
func (s *piecePerResource) Close() error {
return nil
}
func (s *piecePerResource) Piece(p metainfo.Piece) Piece {
2016-05-16 12:32:00 +00:00
completed, err := s.p.NewInstance(path.Join("completed", p.Hash().HexString()))
2016-05-16 08:44:58 +00:00
if err != nil {
panic(err)
}
2016-05-16 12:32:00 +00:00
incomplete, err := s.p.NewInstance(path.Join("incomplete", p.Hash().HexString()))
2016-05-16 08:44:58 +00:00
if err != nil {
panic(err)
}
return piecePerResourcePiece{
p: p,
c: completed,
i: incomplete,
}
}
type piecePerResourcePiece struct {
p metainfo.Piece
2016-05-16 12:32:00 +00:00
c resource.Instance
i resource.Instance
2016-05-16 08:44:58 +00:00
}
func (s piecePerResourcePiece) GetIsComplete() bool {
fi, err := s.c.Stat()
return err == nil && fi.Size() == s.p.Length()
}
func (s piecePerResourcePiece) MarkComplete() error {
2016-05-16 12:32:00 +00:00
return resource.Move(s.i, s.c)
2016-05-16 08:44:58 +00:00
}
func (s piecePerResourcePiece) ReadAt(b []byte, off int64) (n int, err error) {
missinggo.LimitLen(&b, s.p.Length()-off)
n, err = s.c.ReadAt(b, off)
if err != nil {
n, err = s.i.ReadAt(b, off)
}
off += int64(n)
if off >= s.p.Length() {
err = io.EOF
} else if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return
}
func (s piecePerResourcePiece) WriteAt(b []byte, off int64) (n int, err error) {
missinggo.LimitLen(&b, s.p.Length()-off)
return s.i.WriteAt(b, off)
}