9 "github.com/anacrolix/missinggo"
10 "golang.org/x/net/context"
13 type Reader interface {
17 missinggo.ReadContexter
22 // Piece range by piece index, [begin, end).
23 type pieceRange struct {
27 // Accesses Torrent data via a Client. Reads block until the data is
28 // available. Seeks and readahead also drive Client behaviour.
32 // Ensure operations that change the position are exclusive, like Read()
36 // Required when modifying pos and readahead, or reading them without
41 // The cached piece range this reader wants downloaded. The zero value
42 // corresponds to nothing. We cache this so that changes can be detected,
43 // and bubbled up to the Torrent only as required.
47 var _ io.ReadCloser = &reader{}
49 // Don't wait for pieces to complete and be verified. Read calls return as
50 // soon as they can when the underlying chunks become available.
51 func (r *reader) SetResponsive() {
53 r.t.cl.event.Broadcast()
56 // Disable responsive mode. TODO: Remove?
57 func (r *reader) SetNonResponsive() {
59 r.t.cl.event.Broadcast()
62 // Configure the number of bytes ahead of a read that should also be
63 // prioritized in preparation for further reads.
64 func (r *reader) SetReadahead(readahead int64) {
66 r.readahead = readahead
69 defer r.t.cl.mu.Unlock()
73 func (r *reader) readable(off int64) (ret bool) {
74 if r.t.closed.IsSet() {
77 req, ok := r.t.offsetRequest(off)
82 return r.t.haveChunk(req)
84 return r.t.pieceComplete(int(req.Index))
87 // How many bytes are available to read. Max is the most we could require.
88 func (r *reader) available(off, max int64) (ret int64) {
90 req, ok := r.t.offsetRequest(off)
94 if !r.t.haveChunk(req) {
97 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
102 // Ensure that ret hasn't exceeded our original max.
109 func (r *reader) waitReadable(off int64) {
110 // We may have been sent back here because we were told we could read but
115 // Calculates the pieces this reader wants downloaded, ignoring the cached
116 // value at r.pieces.
117 func (r *reader) piecesUncached() (ret pieceRange) {
122 ret.begin, ret.end = r.t.byteRegionPieces(r.pos, ra)
126 func (r *reader) Read(b []byte) (n int, err error) {
127 return r.ReadContext(context.Background(), b)
130 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
131 // This is set under the Client lock if the Context is canceled.
133 if ctx.Done() != nil {
134 ctx, cancel := context.WithCancel(ctx)
135 // Abort the goroutine when the function returns.
141 r.t.cl.event.Broadcast()
145 // Hmmm, if a Read gets stuck, this means you can't change position for
146 // other purposes. That seems reasonable, but unusual.
148 defer r.opMu.Unlock()
151 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
154 panic("expected error")
165 if r.pos >= r.t.length {
167 } else if err == io.EOF {
168 err = io.ErrUnexpectedEOF
173 // Wait until some data should be available to read. Tickles the client if it
174 // isn't. Returns how much should be readable without blocking.
175 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
177 defer r.t.cl.mu.Unlock()
178 for !r.readable(pos) && *ctxErr == nil {
181 return r.available(pos, wanted)
184 // Performs at most one successful read to torrent storage.
185 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
186 if pos >= r.t.length {
191 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
193 if r.t.closed.IsSet() {
194 err = errors.New("torrent closed")
202 pi := int(pos / r.t.info.PieceLength)
203 ip := r.t.info.Piece(pi)
204 po := pos % r.t.info.PieceLength
205 b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
206 n, err = r.t.readAt(b1, pos)
212 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
213 r.t.updateAllPieceCompletions()
214 r.t.updateAllPiecePriorities()
219 func (r *reader) Close() error {
221 defer r.t.cl.mu.Unlock()
226 func (r *reader) posChanged() {
227 to := r.piecesUncached()
233 r.t.readerPosChanged(from, to)
236 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
238 defer r.opMu.Unlock()
248 r.pos = r.t.info.TotalLength() + off
250 err = errors.New("bad whence")