7 "github.com/anacrolix/missinggo/v2"
8 "github.com/anacrolix/torrent/metainfo"
15 func NewClient(cl ClientImpl) *Client {
19 func (cl Client) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (*Torrent, error) {
20 t, err := cl.ci.OpenTorrent(info, infoHash)
24 return &Torrent{t}, nil
31 func (t Torrent) Piece(p metainfo.Piece) Piece {
32 return Piece{t.TorrentImpl.Piece(p), p}
40 var _ io.WriterTo = Piece{}
42 // Why do we have this wrapper? Well PieceImpl doesn't implement io.Reader, so we can't let io.Copy
43 // and friends check for io.WriterTo and fallback for us since they expect an io.Reader.
44 func (p Piece) WriteTo(w io.Writer) (int64, error) {
45 if i, ok := p.PieceImpl.(io.WriterTo); ok {
49 r := io.NewSectionReader(p, 0, n)
50 return io.CopyN(w, r, n)
53 func (p Piece) WriteAt(b []byte, off int64) (n int, err error) {
54 // Callers should not be writing to completed pieces, but it's too
55 // expensive to be checking this on every single write using uncached
58 // c := p.Completion()
59 // if c.Ok && c.Complete {
60 // err = errors.New("piece already completed")
63 if off+int64(len(b)) > p.mip.Length() {
64 panic("write overflows piece")
66 b = missinggo.LimitLen(b, p.mip.Length()-off)
67 return p.PieceImpl.WriteAt(b, off)
70 func (p Piece) ReadAt(b []byte, off int64) (n int, err error) {
75 if off >= p.mip.Length() {
79 b = missinggo.LimitLen(b, p.mip.Length()-off)
83 n, err = p.PieceImpl.ReadAt(b, off)
87 if n == 0 && err == nil {
88 panic("io.Copy will get stuck")
92 // Doing this here may be inaccurate. There's legitimate reasons we may fail to read while the
93 // data is still there, such as too many open files. There should probably be a specific error
94 // to return if the data has been lost.
95 if off < p.mip.Length() {