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() {
55 // Disable responsive mode. TODO: Remove?
56 func (r *reader) SetNonResponsive() {
60 // Configure the number of bytes ahead of a read that should also be
61 // prioritized in preparation for further reads.
62 func (r *reader) SetReadahead(readahead int64) {
64 r.readahead = readahead
67 defer r.t.cl.mu.Unlock()
71 func (r *reader) readable(off int64) (ret bool) {
72 if r.t.closed.IsSet() {
75 req, ok := r.t.offsetRequest(off)
80 return r.t.haveChunk(req)
82 return r.t.pieceComplete(int(req.Index))
85 // How many bytes are available to read. Max is the most we could require.
86 func (r *reader) available(off, max int64) (ret int64) {
88 req, ok := r.t.offsetRequest(off)
92 if !r.t.haveChunk(req) {
95 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
100 // Ensure that ret hasn't exceeded our original max.
107 func (r *reader) waitReadable(off int64) {
108 // We may have been sent back here because we were told we could read but
113 // Calculates the pieces this reader wants downloaded, ignoring the cached
114 // value at r.pieces.
115 func (r *reader) piecesUncached() (ret pieceRange) {
120 ret.begin, ret.end = r.t.byteRegionPieces(r.pos, ra)
124 func (r *reader) Read(b []byte) (n int, err error) {
125 return r.ReadContext(context.Background(), b)
128 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
129 // This is set under the Client lock if the Context is canceled.
131 if ctx.Done() != nil {
132 ctx, cancel := context.WithCancel(ctx)
133 // Abort the goroutine when the function returns.
139 r.t.cl.event.Broadcast()
143 // Hmmm, if a Read gets stuck, this means you can't change position for
144 // other purposes. That seems reasonable, but unusual.
146 defer r.opMu.Unlock()
149 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
152 panic("expected error")
163 if r.pos >= r.t.length {
165 } else if err == io.EOF {
166 err = io.ErrUnexpectedEOF
171 // Wait until some data should be available to read. Tickles the client if it
172 // isn't. Returns how much should be readable without blocking.
173 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
175 defer r.t.cl.mu.Unlock()
176 for !r.readable(pos) && *ctxErr == nil {
179 return r.available(pos, wanted)
182 // Performs at most one successful read to torrent storage.
183 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
184 if pos >= r.t.length {
189 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
191 if r.t.closed.IsSet() {
192 err = errors.New("torrent closed")
200 pi := int(pos / r.t.info.PieceLength)
201 ip := r.t.info.Piece(pi)
202 po := pos % r.t.info.PieceLength
203 b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
204 n, err = r.t.readAt(b1, pos)
210 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
211 r.t.updateAllPieceCompletions()
212 r.t.updateAllPiecePriorities()
217 func (r *reader) Close() error {
219 defer r.t.cl.mu.Unlock()
224 func (r *reader) posChanged() {
225 to := r.piecesUncached()
231 r.t.readerPosChanged(from, to)
234 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
236 defer r.opMu.Unlock()
246 r.pos = r.t.info.TotalLength() + off
248 err = errors.New("bad whence")