Debian Codegraph @

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

raw
1 // Copyright 2001, FreeHEP.
2 package org.freehep.util.io;
3
4 import java.io.FilterOutputStream;
5 import java.io.IOException;
6 import java.io.OutputStream;
7
8 /**
9 * The RunLengthOutputStream encodes data as Run Length encoding. The exact
10 * definition of Run Length encoding can be found in the PostScript Language
11 * Reference (3rd ed.) chapter 3.13.3.
12 *
13 * @author Mark Donszelmann
14 * @version $Id: RunLengthOutputStream.java 8584 2006-08-10 23:06:37Z duns $
15 */
16 public class RunLengthOutputStream extends FilterOutputStream implements
17 RunLength, FinishableOutputStream {
18
19 private boolean end;
20
21 private int[] buffer = new int[LENGTH];
22
23 private int index;
24
25 private int last;
26
27 private int count;
28
29 /**
30 * Create a Run Length output stream
31 *
32 * @param out stream to write
33 */
34 public RunLengthOutputStream(OutputStream out) {
35 super(out);
36 end = false;
37 index = 0;
38 last = -1;
39 count = 1;
40 }
41
42 public void write(int a) throws IOException {
43 a &= 0x00FF;
44 if (last > 0) {
45 if (a == last) {
46 // counting
47 writeBuffer();
48 count++;
49 if (count >= LENGTH) {
50 writeCount();
51 }
52 } else {
53 // buffering
54 if (count > 1) {
55 writeCount();
56 } else {
57 buffer[index] = last;
58 index++;
59 if (index >= LENGTH) {
60 writeBuffer();
61 }
62 }
63 }
64 }
65
66 last = a;
67 }
68
69 public void finish() throws IOException {
70 if (!end) {
71 end = true;
72 writeCount();
73 writeBuffer();
74
75 // we may have one character left in "last" (FREEHEP-578)
76 if (last >= 0) {
77 super.write(0);
78 super.write(last);
79 }
80 super.write(EOD);
81 flush();
82 if (out instanceof FinishableOutputStream) {
83 ((FinishableOutputStream) out).finish();
84 }
85 }
86 }
87
88 public void close() throws IOException {
89 finish();
90 super.close();
91 }
92
93 private void writeBuffer() throws IOException {
94 if (index > 0) {
95 super.write(index - 1);
96 for (int i = 0; i < index; i++) {
97 super.write((byte) buffer[i]);
98 }
99 }
100
101 index = 0;
102 }
103
104 private void writeCount() throws IOException {
105 if (count > 1) {
106 super.write(257 - count);
107 super.write(last);
108 last = -1;
109 }
110
111 count = 1;
112 }
113 }