1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.codec.digest;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20
21 import java.io.ByteArrayOutputStream;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.net.URL;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.stream.Stream;
31
32 import org.apache.commons.io.IOUtils;
33 import org.junit.jupiter.params.ParameterizedTest;
34 import org.junit.jupiter.params.provider.Arguments;
35 import org.junit.jupiter.params.provider.MethodSource;
36
37 class XXHash32Test {
38
39 private static long copy(final InputStream input, final OutputStream output, final int bufferSize) throws IOException {
40 return IOUtils.copyLarge(input, output, new byte[bufferSize]);
41 }
42
43 public static Stream<Arguments> data() {
44
45 return Stream.of(
46
47
48 Arguments.of("org/apache/commons/codec/bla.tar", "fbb5c8d1"),
49 Arguments.of("org/apache/commons/codec/bla.tar.xz", "4106a208"),
50 Arguments.of("org/apache/commons/codec/small.bin", "f66c26f8")
51 );
52
53 }
54
55 private static byte[] toByteArray(final InputStream input) throws IOException {
56 final ByteArrayOutputStream output = new ByteArrayOutputStream();
57 copy(input, output, 10240);
58 return output.toByteArray();
59 }
60
61 private Path file;
62
63 private String expectedChecksum;
64
65 public void initData(final String path, final String c) throws Exception {
66 final URL url = XXHash32Test.class.getClassLoader().getResource(path);
67 if (url == null) {
68 throw new FileNotFoundException("couldn't find " + path);
69 }
70 file = Paths.get(url.toURI());
71 expectedChecksum = c;
72 }
73
74 @ParameterizedTest
75 @MethodSource("data")
76 public void verifyChecksum(final String path, final String c) throws Exception {
77 initData(path, c);
78 final XXHash32 hasher = new XXHash32();
79 try (InputStream in = Files.newInputStream(file)) {
80 final byte[] bytes = toByteArray(in);
81 hasher.update(bytes, 0, bytes.length);
82 }
83 assertEquals(expectedChecksum, Long.toHexString(hasher.getValue()), "checksum for " + file);
84 }
85
86 @ParameterizedTest
87 @MethodSource("data")
88 public void verifyIncrementalChecksum(final String path, final String c) throws Exception {
89 initData(path, c);
90 final XXHash32 hasher = new XXHash32();
91 try (InputStream in = Files.newInputStream(file)) {
92 final byte[] bytes = toByteArray(in);
93
94 hasher.update(bytes[0]);
95 hasher.reset();
96
97 hasher.update(bytes[0]);
98 hasher.update(bytes, 1, bytes.length - 2);
99 hasher.update(bytes, bytes.length - 1, 1);
100
101 hasher.update(bytes, 0, -1);
102 }
103 assertEquals(expectedChecksum, Long.toHexString(hasher.getValue()), "checksum for " + file);
104 }
105 }