Debian Codegraph @

src/uk/me/parabola/imgfmt/app/labelenc/Format6Decoder.java

raw symbols SCIP
1 package uk.me.parabola.imgfmt.app.labelenc;
2
3 import java.io.ByteArrayOutputStream;
4 import java.nio.charset.StandardCharsets;
5
6 /**
7 * Convert the 6-bit label format back to a java string.
8 */
9 public class Format6Decoder implements CharacterDecoder {
10 private final ByteArrayOutputStream out = new ByteArrayOutputStream();
11 private boolean needReset;
12
13 private boolean symbol;
14 private boolean lowerCaseOrSeparator;
15
16 private int store;
17 private int nbits;
18
19 public boolean addByte(int in) {
20 int b = 0xff & in; //wipe out high bits (in case of negative byte)
21
22 if (needReset) {
23 needReset = false;
24 out.reset();
25 }
26
27 store <<= 8;
28 store |= b;
29 nbits += 8;
30
31 while (nbits >= 6) {
32 convertChar((store >> (nbits-6)) & 0x3f);
33
34 if (needReset) {
35 // Skip until the next byte boundary. Note that may mean that
36 // we skip more or *less* than 6 bits.
37 if (nbits > 8)
38 nbits = 8;
39 else
40 nbits = 0;
41
42 break;
43 } else
44 nbits -= 6;
45 }
46
47 return needReset;
48 }
49
50 public DecodedText getText() {
51 byte[] ba = out.toByteArray();
52 DecodedText text = new DecodedText(ba, StandardCharsets.US_ASCII);
53
54 assert nbits == 0 || nbits == 8;
55 // If there is a byte left inside the decoder then we have to let our
56 // caller know, so that they can adjust the offset of the next label
57 // appropriately.
58 if (nbits == 8)
59 text.setOffsetAdjustment(-1);
60 return text;
61 }
62
63 public void reset() {
64 needReset = false;
65 out.reset();
66 store = 0;
67 nbits = 0;
68 }
69
70
71 /**
72 * Convert a single 6 bit quantity into a character.
73 * @param b The six bit int.
74 */
75 private void convertChar(int b) {
76 if (b > 0x2f) {
77 needReset = true;
78 return;
79 }
80
81 char c;
82
83 if (symbol) {
84 symbol = false;
85 c = Format6Encoder.SYMBOLS.charAt(b);
86 }
87 else if(lowerCaseOrSeparator) {
88 lowerCaseOrSeparator = false;
89 if(b == 0x2b || b == 0x2c) {
90 c = (char)(b - 0x10); // "thin" separator
91 }
92 else if(Character.isLetter(b)) {
93 // lower case letter
94 c = Character.toLowerCase(Format6Encoder.LETTERS.charAt(b));
95 }
96 else {
97 // not a letter so just use as is (could be a digit)
98 c = Format6Encoder.LETTERS.charAt(b);
99 }
100 }
101 else {
102 switch(b) {
103 case 0x1B:
104 // next char is lower case or a separator
105 lowerCaseOrSeparator = true;
106 return;
107
108 case 0x1C:
109 // next char is symbol
110 symbol = true;
111 return;
112
113 case 0x1D:
114 case 0x1E:
115 case 0x1F:
116 // these are separators - use as is
117 c = (char)b;
118 break;
119
120 default:
121 c = Format6Encoder.LETTERS.charAt(b);
122 break;
123 }
124 }
125 out.write(c);
126 }
127 }