torrent/storage/piece_resource.go

75 lines
1.5 KiB
Go
Raw Normal View History

2016-05-16 08:44:58 +00:00
package storage
import (
"path"
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
}
func NewResourcePieces(p resource.Provider) ClientImpl {
2016-05-16 08:44:58 +00:00
return &piecePerResource{
p: p,
}
}
func (s *piecePerResource) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, 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) PieceImpl {
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) MarkNotComplete() error {
return s.c.Delete()
}
func (s piecePerResourcePiece) ReadAt(b []byte, off int64) (int, error) {
if s.GetIsComplete() {
return s.c.ReadAt(b, off)
} else {
return s.i.ReadAt(b, off)
2016-05-16 08:44:58 +00:00
}
}
func (s piecePerResourcePiece) WriteAt(b []byte, off int64) (n int, err error) {
return s.i.WriteAt(b, off)
}