diff --git a/core/src/main/groovy/com/muwire/core/download/Pieces.groovy b/core/src/main/groovy/com/muwire/core/download/Pieces.groovy index eb91169c..64705e32 100644 --- a/core/src/main/groovy/com/muwire/core/download/Pieces.groovy +++ b/core/src/main/groovy/com/muwire/core/download/Pieces.groovy @@ -3,16 +3,29 @@ package com.muwire.core.download class Pieces { private final BitSet bitSet private final int nPieces + private final float ratio private final Random random = new Random() Pieces(int nPieces) { + this(nPieces, 1.0f) + } + + Pieces(int nPieces, float ratio) { this.nPieces = nPieces + this.ratio = ratio bitSet = new BitSet(nPieces) } synchronized int getRandomPiece() { - if (isComplete()) + int cardinality = bitSet.cardinality() + if (cardinality == nPieces) return -1 + + // if fuller than ratio just do sequential + if ( (1.0f * cardinality) / nPieces > ratio) { + return bitSet.nextClearBit(0) + } + while(true) { int start = random.nextInt(nPieces) while(bitSet.get(start) && ++start < nPieces);