Debian Codegraph @

src/main/java/org/freehep/util/io/RunLengthInputStream.java

raw
1 // Copyright 2001-2005, FreeHEP.
2 package org.freehep.util.io;
3
4 import java.io.IOException;
5 import java.io.InputStream;
6
7 /**
8 * The RunLengthStream decodes Run Length encoding. The exact definition of Run
9 * Length encoding can be found in the PostScript Language Reference (3rd ed.)
10 * chapter 3.13.3.
11 *
12 * IMPORTANT: inherits from InputStream rather than FilterInputStream so that
13 * the correct read(byte[], int, int) method is used.
14 *
15 * @author Mark Donszelmann
16 * @version $Id: RunLengthInputStream.java 8584 2006-08-10 23:06:37Z duns $
17 */
18 public class RunLengthInputStream extends InputStream implements RunLength {
19
20 private int[] buffer = new int[LENGTH];
21
22 private int index;
23
24 private int count;
25
26 private InputStream in;
27
28 /**
29 * Create a Run Length input stream
30 *
31 * @param input stream to read from
32 */
33 public RunLengthInputStream(InputStream input) {
34 super();
35 in = input;
36 index = 0;
37 count = 0;
38 }
39
40 public int read() throws IOException {
41
42 if ((index >= count) || (index > 128)) {
43 if (!fillBuffer())
44 return -1;
45 }
46
47 int b = buffer[index];
48 index++;
49 return b & 0x00FF;
50 }
51
52 private boolean fillBuffer() throws IOException {
53 count = in.read();
54
55 if (end(count))
56 return false;
57
58 if (count < 128) {
59 // buffered
60 count++;
61 for (int i = 0; i < count; i++) {
62 buffer[i] = in.read();
63 if (end(buffer[i]))
64 return false;
65 }
66 } else {
67 // counted
68 count = 257 - count;
69 int b = in.read();
70 if (end(b))
71 return false;
72
73 for (int i = 0; i < count; i++) {
74 buffer[i] = b;
75 }
76 }
77 index = 0;
78 return true;
79 }
80
81 private boolean end(int b) {
82 if ((b < 0) || (b == EOD)) {
83 return true;
84 }
85 return false;
86 }
87 }