| 1 |
package uk.me.parabola.imgfmt.app.labelenc; |
| 2 |
|
| 3 |
import java.io.ByteArrayOutputStream; |
| 4 |
import java.nio.charset.StandardCharsets; |
| 5 |
|
| 6 |
|
| 7 |
|
| 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; |
| 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 |
|
| 36 |
|
| 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 |
|
| 56 |
|
| 57 |
|
| 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 |
|
| 73 |
|
| 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); |
| 91 |
} |
| 92 |
else if(Character.isLetter(b)) { |
| 93 |
|
| 94 |
c = Character.toLowerCase(Format6Encoder.LETTERS.charAt(b)); |
| 95 |
} |
| 96 |
else { |
| 97 |
|
| 98 |
c = Format6Encoder.LETTERS.charAt(b); |
| 99 |
} |
| 100 |
} |
| 101 |
else { |
| 102 |
switch(b) { |
| 103 |
case 0x1B: |
| 104 |
|
| 105 |
lowerCaseOrSeparator = true; |
| 106 |
return; |
| 107 |
|
| 108 |
case 0x1C: |
| 109 |
|
| 110 |
symbol = true; |
| 111 |
return; |
| 112 |
|
| 113 |
case 0x1D: |
| 114 |
case 0x1E: |
| 115 |
case 0x1F: |
| 116 |
|
| 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 |
} |