View Javadoc
1   package org.djutils.decoderdumper;
2   
3   import java.io.IOException;
4   
5   /**
6    * <p>
7    * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
8    * BSD-style license. See <a href="https://djutils.org/docs/current/djutils/licenses.html">DJUTILS License</a>.
9    * </p>
10   * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
11   * @author <a href="https://www.tudelft.nl/staff/p.knoppers/">Peter Knoppers</a>
12   */
13  public class CharDecoder implements Decoder
14  {
15      /** Prototype output line. */
16      private final String prototypeLine;
17  
18      /** Maximum number of fields on one output line. */
19      private final int fieldsPerLine;
20  
21      /** Insert one extra space every N fields. */
22      private final int extraSpaceAfterEvery;
23  
24      /**
25       * Construct a new CharDecoder.
26       * @param fieldsPerLine int; maximum number of fields on one output line
27       * @param extraSpaceAfterEvery int; insert an extra space after every N fields
28       */
29      public CharDecoder(final int fieldsPerLine, final int extraSpaceAfterEvery)
30      {
31          this.fieldsPerLine = fieldsPerLine;
32          this.extraSpaceAfterEvery = extraSpaceAfterEvery > 0 ? extraSpaceAfterEvery : Integer.MAX_VALUE;
33          String format = String.format("%%%ds", fieldsPerLine + (fieldsPerLine - 1) / this.extraSpaceAfterEvery);
34          this.prototypeLine = String.format(format, "");
35      }
36  
37      /** String builder for current output line. */
38      private StringBuilder buffer = new StringBuilder();
39  
40      @Override
41      public String getResult()
42      {
43          String result = this.buffer.toString();
44          this.buffer.setLength(0);
45          return result;
46      }
47  
48      @Override
49      public int getMaximumWidth()
50      {
51          return this.prototypeLine.length();
52      }
53  
54      @Override
55      public boolean append(final int address, final byte theByte) throws IOException
56      {
57          if (this.buffer.length() == 0)
58          {
59              this.buffer.append(this.prototypeLine);
60          }
61          int lineByte = address % this.fieldsPerLine;
62          int index = lineByte + lineByte / this.extraSpaceAfterEvery;
63          this.buffer.replace(index, index + 1, theByte >= 32 && theByte < 127 ? "" + (char) theByte : ".");
64          return lineByte == this.fieldsPerLine - 1;
65      }
66  
67      @Override
68      public boolean ignoreForIdenticalOutputCheck()
69      {
70          return false;
71      }
72  
73      @Override
74      public String toString()
75      {
76          return "CharDecoder [buffer=" + this.buffer + "]";
77      }
78  
79  }