diff --git a/core/src/main/groovy/com/muwire/core/download/DownloadSession.groovy b/core/src/main/groovy/com/muwire/core/download/DownloadSession.groovy index 1fc47c5a..24a933f9 100644 --- a/core/src/main/groovy/com/muwire/core/download/DownloadSession.groovy +++ b/core/src/main/groovy/com/muwire/core/download/DownloadSession.groovy @@ -112,6 +112,8 @@ class DownloadSession { byte[] tmp = new byte[0x1 << 13] while(mapped.hasRemaining()) { + if (mapped.remaining() < tmp.length) + tmp = new byte[mapped.remaining()] int read = is.read(tmp) if (read == -1) throw new IOException() 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 4692525d..eb91169c 100644 --- a/core/src/main/groovy/com/muwire/core/download/Pieces.groovy +++ b/core/src/main/groovy/com/muwire/core/download/Pieces.groovy @@ -27,4 +27,8 @@ class Pieces { synchronized boolean isComplete() { bitSet.cardinality() == nPieces } + + synchronized int donePieces() { + bitSet.cardinality() + } } diff --git a/core/src/test/groovy/com/muwire/core/download/DownloadSessionTest.groovy b/core/src/test/groovy/com/muwire/core/download/DownloadSessionTest.groovy index f465ac46..7dab580f 100644 --- a/core/src/test/groovy/com/muwire/core/download/DownloadSessionTest.groovy +++ b/core/src/test/groovy/com/muwire/core/download/DownloadSessionTest.groovy @@ -86,4 +86,51 @@ class DownloadSessionTest { assert pieces.isComplete() assert target.bytes == source.bytes } + + @Test + public void testPieceSizeFile() { + int size = FileHasher.getPieceSize(1) + size = 1 << size + initSession(size) + + assert "GET $rootBase64" == readTillRN(fromDownloader) + readTillRN(fromDownloader) + assert "" == readTillRN(fromDownloader) + + toDownloader.write("200 OK\r\n".bytes) + toDownloader.write(("Content-Range: 0-"+(size - 1)+"\r\n\r\n").bytes) + toDownloader.write(source.bytes) + toDownloader.flush() + + Thread.sleep(150) + assert pieces.isComplete() + assert target.bytes == source.bytes + } + + @Test + public void testPieceSizePlusOne() { + int pieceSize = FileHasher.getPieceSize(1) + int size = (1 << pieceSize) + 1 + initSession(size) + + assert "GET $rootBase64" == readTillRN(fromDownloader) + String range = readTillRN(fromDownloader) + def matcher = (range =~ /^Range: (\d+)-(\d+)$/) + long start = Long.parseLong(matcher[0][1]) + long end = Long.parseLong(matcher[0][2]) + + assert (start == 0 && end == ((1 << pieceSize) - 1)) || + (start == (1 << pieceSize) && end == (1 << pieceSize)) + + assert "" == readTillRN(fromDownloader) + + toDownloader.write("200 OK\r\n".bytes) + toDownloader.write(("Content-Range: $start-$end\r\n\r\n").bytes) + toDownloader.write(source.bytes) + toDownloader.flush() + + Thread.sleep(150) + assert !pieces.isComplete() + assert 1 == pieces.donePieces() + } }