1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.compress.compressors.lz77support;
20
21 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
22 import static org.junit.jupiter.api.Assertions.assertEquals;
23 import static org.junit.jupiter.api.Assertions.assertThrows;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28
29 import org.apache.commons.compress.utils.ByteUtils;
30 import org.junit.jupiter.api.Test;
31
32 public class AbstractLZ77CompressorInputStreamTest {
33
34 private static final class TestStream extends AbstractLZ77CompressorInputStream {
35
36 private boolean literal;
37
38 TestStream(final InputStream in) {
39 super(in, 1024);
40 }
41
42 void literal(final int len) {
43 startLiteral(len);
44 literal = true;
45 }
46
47 @Override
48 public int read(final byte[] b, final int off, final int len) throws IOException {
49 if (literal) {
50 return readLiteral(b, off, len);
51 }
52 return readBackReference(b, off, len);
53 }
54 }
55
56 @Test
57 public void testCantPrefillAfterDataHasBeenRead() throws IOException {
58 final byte[] data = { 1, 2, 3, 4 };
59 try (TestStream s = new TestStream(new ByteArrayInputStream(data))) {
60 s.literal(3);
61 assertEquals(1, s.read());
62 assertThrows(IllegalStateException.class, () -> s.prefill(new byte[] { 1, 2, 3 }));
63 }
64 }
65
66 @Test
67 public void testIfPrefillExceedsWindowSizeTheLastBytesAreUsed() throws IOException {
68 final byte[] data = new byte[2048];
69 data[2046] = 3;
70 data[2047] = 4;
71 try (TestStream s = new TestStream(new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY))) {
72 s.prefill(data);
73 s.startBackReference(2, 4);
74 final byte[] r = new byte[4];
75 assertEquals(4, s.read(r));
76 assertArrayEquals(new byte[] { 3, 4, 3, 4 }, r);
77 }
78 }
79
80 @Test
81 public void testPrefillCanBeUsedForBackReferences() throws IOException {
82 final byte[] data = { 1, 2, 3, 4 };
83 try (TestStream s = new TestStream(new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY))) {
84 s.prefill(data);
85 s.startBackReference(2, 4);
86 final byte[] r = new byte[4];
87 assertEquals(4, s.read(r));
88 assertArrayEquals(new byte[] { 3, 4, 3, 4 }, r);
89 }
90 }
91 }