10 "github.com/anacrolix/missinggo"
11 "golang.org/x/net/context"
14 // Piece range by piece index, [begin, end).
15 type pieceRange struct {
19 // Accesses Torrent data via a Client. Reads block until the data is
20 // available. Seeks and readahead also drive Client behaviour.
24 // Ensure operations that change the position are exclusive, like Read()
28 // Required when modifying pos and readahead, or reading them without
33 // The cached piece range this reader wants downloaded. The zero value
34 // corresponds to nothing. We cache this so that changes can be detected,
35 // and bubbled up to the Torrent only as required.
39 var _ io.ReadCloser = &Reader{}
41 // Don't wait for pieces to complete and be verified. Read calls return as
42 // soon as they can when the underlying chunks become available.
43 func (r *Reader) SetResponsive() {
47 // Configure the number of bytes ahead of a read that should also be
48 // prioritized in preparation for further reads.
49 func (r *Reader) SetReadahead(readahead int64) {
51 r.readahead = readahead
54 defer r.t.cl.mu.Unlock()
58 func (r *Reader) readable(off int64) (ret bool) {
59 if r.t.closed.IsSet() {
62 req, ok := r.t.offsetRequest(off)
67 return r.t.haveChunk(req)
69 return r.t.pieceComplete(int(req.Index))
72 // How many bytes are available to read. Max is the most we could require.
73 func (r *Reader) available(off, max int64) (ret int64) {
75 req, ok := r.t.offsetRequest(off)
79 if !r.t.haveChunk(req) {
82 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
87 // Ensure that ret hasn't exceeded our original max.
94 func (r *Reader) tickleClient() {
98 func (r *Reader) waitReadable(off int64) {
99 // We may have been sent back here because we were told we could read but
105 // Calculates the pieces this reader wants downloaded, ignoring the cached
106 // value at r.pieces.
107 func (r *Reader) piecesUncached() (ret pieceRange) {
112 ret.begin, ret.end = r.t.byteRegionPieces(r.pos, ra)
116 func (r *Reader) Read(b []byte) (n int, err error) {
117 return r.ReadContext(b, context.Background())
120 func (r *Reader) ReadContext(b []byte, ctx context.Context) (n int, err error) {
121 // This is set under the Client lock if the Context is canceled.
123 if ctx.Done() != nil {
124 ctx, cancel := context.WithCancel(ctx)
125 // Abort the goroutine when the function returns.
131 r.t.cl.event.Broadcast()
135 // Hmmm, if a Read gets stuck, this means you can't change position for
136 // other purposes. That seems reasonable, but unusual.
138 defer r.opMu.Unlock()
141 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
144 panic("expected error")
155 if r.pos >= r.t.length {
157 } else if err == io.EOF {
158 err = io.ErrUnexpectedEOF
163 // Wait until some data should be available to read. Tickles the client if it
164 // isn't. Returns how much should be readable without blocking.
165 func (r *Reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
167 defer r.t.cl.mu.Unlock()
168 for !r.readable(pos) && *ctxErr == nil {
171 return r.available(pos, wanted)
174 // Performs at most one successful read to torrent storage.
175 func (r *Reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
176 if pos >= r.t.length {
181 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
183 if r.t.closed.IsSet() {
184 err = errors.New("torrent closed")
193 pi := int(pos / r.t.Info().PieceLength)
194 ip := r.t.Info().Piece(pi)
195 po := pos % r.t.Info().PieceLength
196 missinggo.LimitLen(&b1, ip.Length()-po)
197 n, err = r.t.readAt(b1, pos)
202 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
204 r.t.updateAllPieceCompletions()
205 r.t.updateAllPiecePriorities()
210 func (r *Reader) Close() error {
212 defer r.t.cl.mu.Unlock()
217 func (r *Reader) posChanged() {
218 to := r.piecesUncached()
224 r.t.readerPosChanged(from, to)
227 func (r *Reader) Seek(off int64, whence int) (ret int64, err error) {
229 defer r.opMu.Unlock()
239 r.pos = r.t.info.TotalLength() + off
241 err = errors.New("bad whence")
249 func (r *Reader) Torrent() *Torrent {