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