8 "github.com/anacrolix/missinggo"
10 "github.com/anacrolix/torrent/metainfo"
13 type fileStorage struct {
15 completed map[[20]byte]bool
18 func NewFile(baseDir string) I {
24 func (me *fileStorage) OpenTorrent(info *metainfo.InfoEx) (Torrent, error) {
25 return fileTorrentStorage{me}, nil
28 type fileTorrentStorage struct {
32 func (me *fileStorage) Piece(p metainfo.Piece) Piece {
33 _io := &fileStorageTorrent{
37 return &fileStoragePiece{
40 missinggo.NewSectionWriter(_io, p.Offset(), p.Length()),
41 io.NewSectionReader(_io, p.Offset(), p.Length()),
45 func (me *fileStorage) Close() error {
49 type fileStoragePiece struct {
56 func (me *fileStoragePiece) GetIsComplete() bool {
57 return me.completed[me.p.Hash()]
60 func (me *fileStoragePiece) MarkComplete() error {
61 if me.completed == nil {
62 me.completed = make(map[[20]byte]bool)
64 me.completed[me.p.Hash()] = true
68 type fileStorageTorrent struct {
73 // Returns EOF on short or missing file.
74 func (me *fileStorageTorrent) readFileAt(fi metainfo.FileInfo, b []byte, off int64) (n int, err error) {
75 f, err := os.Open(me.fileInfoName(fi))
76 if os.IsNotExist(err) {
77 // File missing is treated the same as a short file.
85 // Limit the read to within the expected bounds of this file.
86 if int64(len(b)) > fi.Length-off {
89 for off < fi.Length && len(b) != 0 {
90 n1, err1 := f.ReadAt(b, off)
102 // Only returns EOF at the end of the torrent. Premature EOF is ErrUnexpectedEOF.
103 func (me *fileStorageTorrent) ReadAt(b []byte, off int64) (n int, err error) {
104 for _, fi := range me.info.UpvertedFiles() {
105 for off < fi.Length {
106 n1, err1 := me.readFileAt(fi, b, off)
121 err = io.ErrUnexpectedEOF
131 func (me *fileStorageTorrent) WriteAt(p []byte, off int64) (n int, err error) {
132 for _, fi := range me.info.UpvertedFiles() {
133 if off >= fi.Length {
138 if int64(n1) > fi.Length-off {
139 n1 = int(fi.Length - off)
141 name := me.fileInfoName(fi)
142 os.MkdirAll(filepath.Dir(name), 0770)
144 f, err = os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0660)
148 n1, err = f.WriteAt(p[:n1], off)
163 func (me *fileStorageTorrent) fileInfoName(fi metainfo.FileInfo) string {
164 return filepath.Join(append([]string{me.baseDir, me.info.Name}, fi.Path...)...)