1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.imaging.formats.pcx;
17
18 import java.io.IOException;
19
20 import org.apache.commons.imaging.common.BinaryOutputStream;
21
22 final class RleWriter {
23 private final boolean isCompressed;
24 private int previousByte = -1;
25 private int repeatCount;
26
27 RleWriter(final boolean isCompressed) {
28 this.isCompressed = isCompressed;
29 }
30
31 void flush(final BinaryOutputStream bos) throws IOException {
32 if (repeatCount > 0) {
33 if (repeatCount != 1 || (previousByte & 0xc0) == 0xc0) {
34 bos.write(0xc0 | repeatCount);
35 }
36 bos.write(previousByte);
37 }
38 }
39
40 void write(final BinaryOutputStream bos, final byte[] samples) throws IOException {
41 if (isCompressed) {
42 for (final byte element : samples) {
43 if ((element & 0xff) == previousByte && repeatCount < 63) {
44 ++repeatCount;
45 } else {
46 if (repeatCount > 0) {
47 if (repeatCount != 1 || (previousByte & 0xc0) == 0xc0) {
48 bos.write(0xc0 | repeatCount);
49 }
50 bos.write(previousByte);
51 }
52 previousByte = 0xff & element;
53 repeatCount = 1;
54 }
55 }
56 } else {
57 bos.write(samples);
58 }
59 }
60 }