summaryrefslogtreecommitdiffstats
path: root/dozentenmodulserver/src/main/java/fileserv/FileChunk.java
blob: 2fee6378b56b770cb57b6d11c439fc2f2850181a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package fileserv;

import java.util.Collection;
import java.util.List;

import org.openslx.filetransfer.FileRange;

public class FileChunk {
	public static final int CHUNK_SIZE = 16 * 1024 * 1024;

	public final FileRange range;
	public final byte[] sha1sum;

	public FileChunk(long startOffset, long endOffset, byte[] sha1sum) {
		this.range = new FileRange(startOffset, endOffset);
		this.sha1sum = sha1sum;
	}

	public static int fileSizeToChunkCount(long fileSize) {
		return (int) ((fileSize + CHUNK_SIZE - 1) / CHUNK_SIZE);
	}

	public static void createChunkList(Collection<FileChunk> list, long fileSize, List<byte[]> sha1sums) {
		if (fileSize < 0)
			throw new IllegalArgumentException("fileSize cannot be negative");
		long chunkCount = fileSizeToChunkCount(fileSize);
		if (sha1sums != null) {
			if (sha1sums.size() != chunkCount)
				throw new IllegalArgumentException(
						"Passed a sha1sum list, but hash count in list doesn't match expected chunk count");
			long offset = 0;
			for (byte[] sha1sum : sha1sums) { // Do this as we don't know how efficient List.get(index) is...
				long end = offset + CHUNK_SIZE;
				if (end > fileSize)
					end = fileSize;
				list.add(new FileChunk(offset, end, sha1sum));
				offset = end;
			}
			return;
		}
		long offset = 0;
		while (offset < fileSize) { // ...otherwise we could share this code
			long end = offset + CHUNK_SIZE;
			if (end > fileSize)
				end = fileSize;
			list.add(new FileChunk(offset, end, null));
			offset = end;
		}
	}
}