View Javadoc
1   /*
2    *  Licensed under the Apache License, Version 2.0 (the "License");
3    *  you may not use this file except in compliance with the License.
4    *  You may obtain a copy of the License at
5    *
6    *       http://www.apache.org/licenses/LICENSE-2.0
7    *
8    *  Unless required by applicable law or agreed to in writing, software
9    *  distributed under the License is distributed on an "AS IS" BASIS,
10   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   *  See the License for the specific language governing permissions and
12   *  limitations under the License.
13   *  under the License.
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  }