diff --git a/libtransmission/completion.c b/libtransmission/completion.c index e11bed310..cd83946b6 100644 --- a/libtransmission/completion.c +++ b/libtransmission/completion.c @@ -10,6 +10,8 @@ * $Id$ */ +#include + #include "transmission.h" #include "completion.h" #include "torrent.h" @@ -213,12 +215,19 @@ tr_cpMissingBytesInPiece( const tr_completion * cp, tr_piece_index_t piece ) else { size_t haveBytes = 0; tr_block_index_t f, l; + const size_t pieceByteSize = tr_torPieceCountBytes( cp->tor, piece ); tr_torGetPieceBlockRange( cp->tor, piece, &f, &l ); - haveBytes = tr_bitfieldCountRange( &cp->blockBitfield, f, l+1 ); - haveBytes *= cp->tor->blockSize; - if( tr_bitfieldHas( &cp->blockBitfield, l ) ) + if( f != l ) { + /* nb: we don't pass the usual l+1 here to tr_bitfieldCountRange(). + It's faster to handle the last block separately because its size + needs to be checked separately. */ + haveBytes = tr_bitfieldCountRange( &cp->blockBitfield, f, l ); + haveBytes *= cp->tor->blockSize; + } + if( tr_bitfieldHas( &cp->blockBitfield, l ) ) /* handle the last block */ haveBytes += tr_torBlockCountBytes( cp->tor, l ); - return tr_torPieceCountBytes( cp->tor, piece ) - haveBytes; + assert( haveBytes <= pieceByteSize ); + return pieceByteSize - haveBytes; } } diff --git a/libtransmission/peer-mgr.c b/libtransmission/peer-mgr.c index 723c5ae4c..9973b9fb6 100644 --- a/libtransmission/peer-mgr.c +++ b/libtransmission/peer-mgr.c @@ -2557,7 +2557,7 @@ peerIsSeed( const tr_peer * peer ) return false; } -/* count how many pieces we want that connected peers have */ +/* count how many bytes we want that connected peers have */ uint64_t tr_peerMgrGetDesiredAvailable( const tr_torrent * tor ) { @@ -2594,6 +2594,7 @@ tr_peerMgrGetDesiredAvailable( const tr_torrent * tor ) if( !tor->info.pieces[i].dnd && ( t->pieceReplication[i] > 0 ) ) desiredAvailable += tr_cpMissingBytesInPiece( &t->tor->completion, i ); + assert( desiredAvailable <= tor->info.totalSize ); return desiredAvailable; } diff --git a/libtransmission/torrent.c b/libtransmission/torrent.c index 98b8e78a2..e6c566c34 100644 --- a/libtransmission/torrent.c +++ b/libtransmission/torrent.c @@ -1261,6 +1261,10 @@ tr_torrentStat( tr_torrent * tor ) tr_torrentUnlock( tor ); + /* test some of the constraints */ + assert( s->sizeWhenDone <= tor->info.totalSize ); + assert( s->leftUntilDone <= s->sizeWhenDone ); + assert( s->desiredAvailable <= s->leftUntilDone ); return s; }