]> Sergey Matveev's repositories - btrtrc.git/blob - storage/wrappers.go
Tweaks to storage error and completion handling
[btrtrc.git] / storage / wrappers.go
1 package storage
2
3 import (
4         "io"
5         "os"
6
7         "github.com/anacrolix/missinggo"
8
9         "github.com/anacrolix/torrent/metainfo"
10 )
11
12 type Client struct {
13         ci ClientImpl
14 }
15
16 func NewClient(cl ClientImpl) *Client {
17         return &Client{cl}
18 }
19
20 func (cl Client) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (*Torrent, error) {
21         t, err := cl.ci.OpenTorrent(info, infoHash)
22         if err != nil {
23                 return nil, err
24         }
25         return &Torrent{t}, nil
26 }
27
28 type Torrent struct {
29         TorrentImpl
30 }
31
32 func (t Torrent) Piece(p metainfo.Piece) Piece {
33         return Piece{t.TorrentImpl.Piece(p), p}
34 }
35
36 type Piece struct {
37         PieceImpl
38         mip metainfo.Piece
39 }
40
41 func (p Piece) WriteAt(b []byte, off int64) (n int, err error) {
42         // Callers should not be writing to completed pieces, but it's too
43         // expensive to be checking this on every single write using uncached
44         // completions.
45
46         // c := p.Completion()
47         // if c.Ok && c.Complete {
48         //      err = errors.New("piece already completed")
49         //      return
50         // }
51         if off+int64(len(b)) > p.mip.Length() {
52                 panic("write overflows piece")
53         }
54         b = missinggo.LimitLen(b, p.mip.Length()-off)
55         return p.PieceImpl.WriteAt(b, off)
56 }
57
58 func (p Piece) ReadAt(b []byte, off int64) (n int, err error) {
59         if off < 0 {
60                 err = os.ErrInvalid
61                 return
62         }
63         if off >= p.mip.Length() {
64                 err = io.EOF
65                 return
66         }
67         b = missinggo.LimitLen(b, p.mip.Length()-off)
68         if len(b) == 0 {
69                 return
70         }
71         n, err = p.PieceImpl.ReadAt(b, off)
72         if n > len(b) {
73                 panic(n)
74         }
75         if n == 0 && err == nil {
76                 panic("io.Copy will get stuck")
77         }
78         off += int64(n)
79
80         // Doing this here may be inaccurate. There's legitimate reasons we may fail to read while the
81         // data is still there, such as too many open files. There should probably be a specific error
82         // to return if the data has been lost.
83         if off < p.mip.Length() {
84                 if err == io.EOF {
85                         p.MarkNotComplete()
86                 }
87         }
88
89         return
90 }