1 package org.djutils.decoderdumper;
2
3 import java.io.IOException;
4
5
6
7
8
9
10
11
12
13 public class CharDecoder implements Decoder
14 {
15
16 private final String prototypeLine;
17
18
19 private final int fieldsPerLine;
20
21
22 private final int extraSpaceAfterEvery;
23
24
25
26
27
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
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 }