1 /* Copyright 2017 Google Inc. All Rights Reserved.
2 
3    Distributed under MIT license.
4    See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
5 */
6 
7 package org.brotli.wrapper.dec;
8 
9 import static org.junit.Assert.assertEquals;
10 
11 import org.brotli.integration.BrotliJniTestBase;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import org.junit.Test;
15 import org.junit.runner.RunWith;
16 import org.junit.runners.JUnit4;
17 
18 /** Tests for {@link org.brotli.wrapper.dec.BrotliInputStream}. */
19 @RunWith(JUnit4.class)
20 public class EagerStreamTest extends BrotliJniTestBase {
21 
22   @Test
testEagerReading()23   public void testEagerReading() throws IOException {
24     final StringBuilder log = new StringBuilder();
25     final byte[] data = {0, 0, 16, 42, 3};
26     InputStream source = new InputStream() {
27       int index;
28 
29       @Override
30       public int read() {
31         if (index < data.length) {
32           log.append("<").append(index);
33           return data[index++];
34         } else {
35           log.append("<#");
36           return -1;
37         }
38       }
39 
40       @Override
41       public int read(byte[] b) throws IOException {
42         return read(b, 0, b.length);
43       }
44 
45       @Override
46       public int read(byte[] b, int off, int len) throws IOException {
47         if (len < 1) {
48           return 0;
49         }
50         int d = read();
51         if (d == -1) {
52           return 0;
53         }
54         b[off] = (byte) d;
55         return 1;
56       }
57     };
58     BrotliInputStream reader = new BrotliInputStream(source);
59     reader.enableEagerOutput();
60     int count = 0;
61     while (true) {
62       log.append("^").append(count);
63       int b = reader.read();
64       if (b == -1) {
65         log.append(">#");
66         break;
67       } else {
68         log.append(">").append(count++);
69       }
70     }
71     // Lazy log:  ^0<0<1<2<3<4>0^1>#
72     assertEquals("^0<0<1<2<3>0^1<4>#", log.toString());
73   }
74 
75 }
76