diff --git a/core/src/main/groovy/com/muwire/core/FileHasher.groovy b/core/src/main/groovy/com/muwire/core/FileHasher.groovy new file mode 100644 index 00000000..18ce2503 --- /dev/null +++ b/core/src/main/groovy/com/muwire/core/FileHasher.groovy @@ -0,0 +1,24 @@ +package com.muwire.core + +class FileHasher { + + /** max size of shared file is 128 GB */ + public static final long MAX_SIZE = 0x1 << 37 + + /** + * @param size of the file to be shared + * @return the size of each piece in power of 2 + */ + static int getPieceSize(long size) { + if (size <= 0x1 << 25) + return 18 + + for (int i = 26; i <= 37; i++) { + if (size <= 0x1 << i) { + return i-7 + } + } + + throw new IllegalArgumentException("File too large $size") + } +} diff --git a/core/src/test/groovy/com/muwire/core/FileHasherTest.groovy b/core/src/test/groovy/com/muwire/core/FileHasherTest.groovy new file mode 100644 index 00000000..61cc2409 --- /dev/null +++ b/core/src/test/groovy/com/muwire/core/FileHasherTest.groovy @@ -0,0 +1,18 @@ +package com.muwire.core + +import static org.junit.jupiter.api.Assertions.assertEquals + +import org.junit.Test + +class FileHasherTest extends GroovyTestCase { + + @Test + void testPieceSize() { + assert 18 == FileHasher.getPieceSize(1000000) + assert 20 == FileHasher.getPieceSize(100000000) + shouldFail IllegalArgumentException, { + FileHasher.getPieceSize(Long.MAX_VALUE) + } + + } +}