Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright (C) 2007,2014 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: 31-Oct-2007
16 */
17 package uk.me.parabola.imgfmt.app.labelenc;
18
19 import java.nio.ByteBuffer;
20 import java.nio.CharBuffer;
21 import java.nio.charset.Charset;
22 import java.nio.charset.CharsetEncoder;
23 import java.nio.charset.CoderResult;
24 import java.nio.charset.CodingErrorAction;
25 import java.text.Normalizer;
26 import java.util.Arrays;
27 import java.util.Locale;
28
29 /**
30 * Convert text to a specified charset. This is used when you give a
31 * charset name on the command line to convert to.
32 *
33 * @author Steve Ratcliffe
34 */
35 public class AnyCharsetEncoder extends BaseEncoder implements CharacterEncoder {
36
37 private final CharsetEncoder encoder;
38 private final Transliterator transliterator;
39
40 public AnyCharsetEncoder(String cs, Transliterator transliterator) {
41 this.transliterator = transliterator;
42 prepareForCharacterSet(cs);
43 if (isCharsetSupported()) {
44 encoder = Charset.forName(cs).newEncoder();
45 encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
46 } else {
47 encoder = null;
48 }
49 }
50
51 public EncodedText encodeText(String text) {
52 if (text == null || text.isEmpty())
53 return NO_TEXT;
54
55 if (!isCharsetSupported())
56 return simpleEncode(text);
57
58 String ucText;
59 if (isUpperCase())
60 ucText = text.toUpperCase(Locale.ENGLISH);
61 else
62 ucText = text;
63 ucText = Normalizer.normalize(ucText, Normalizer.Form.NFC);
64
65 // Allocate a buffer for the encoded text. This will be large enough in almost all cases,
66 // but the code below allocates more space if necessary.
67 ByteBuffer outBuf = ByteBuffer.allocate(ucText.length() + 20);
68 CharBuffer charBuffer = CharBuffer.wrap(ucText);
69
70 CoderResult result;
71
72 do {
73 result = encoder.encode(charBuffer, outBuf, true);
74
75 if (result.isUnmappable()) {
76 // There is a character that cannot be represented in the target code page.
77 // Read the character(s), transliterate them, and add them to the output.
78 // We then continue onward with the rest of the string.
79 String s0;
80 if (result.length() == 1) {
81 s0 = String.valueOf(charBuffer.get());
82 } else {
83 // Don't know under what circumstances this will be called and may not be the
84 // correct thing to do when it does happen.
85 StringBuilder sb = new StringBuilder();
86 for (int i = 0; i < result.length(); i++)
87 sb.append(charBuffer.get());
88
89 s0 = sb.toString();
90 }
91
92 String s = transliterator.transliterate(s0);
93
94 // Make sure that there is enough space for the transliterated string
95 while (outBuf.limit() < outBuf.position() + s.length())
96 outBuf = reallocBuf(outBuf);
97
98 if (s.equals(s0)) {
99 // string is still unmappable
100 outBuf.put(encoder.replacement()); //typically '?'
101 } else {
102 for (int i = 0; i < s.length(); i++) {
103 outBuf.put((byte) s.charAt(i));
104 }
105 }
106
107 } else if (result == CoderResult.OVERFLOW) {
108 // Ran out of space in the output
109 outBuf = reallocBuf(outBuf);
110 } else if (result.isMalformed()) {
111 break;
112 }
113 } while (result != CoderResult.UNDERFLOW);
114
115 // We need it to be null terminated but also to trim any extra memory from the allocated
116 // buffer.
117 byte[] res = Arrays.copyOf(outBuf.array(), outBuf.position() + 1);
118 // no trailing zero in char array
119 char[] cres = new char[outBuf.position()];
120 for (int i = 0; i < outBuf.position(); i++)
121 cres[i] = (char) (res[i] & 0xff);
122 return new EncodedText(res, res.length, cres);
123 }
124
125 /**
126 * Allocate a new byte buffer that has more space.
127 *
128 * It will have the same contents as the existing one and the same position, so you can
129 * continue writing to it.
130 *
131 * @param bb The original byte buffer.
132 * @return A new byte buffer with the same contents with more space that you can continue
133 * writing to.
134 */
135 private ByteBuffer reallocBuf(ByteBuffer bb) {
136 byte[] newbuf = Arrays.copyOf(bb.array(), bb.capacity() * 2);
137 return ByteBuffer.wrap(newbuf, bb.position(), newbuf.length - bb.position());
138 }
139
140 public void setUpperCase(boolean upperCase) {
141 super.setUpperCase(upperCase);
142 transliterator.forceUppercase(upperCase);
143 }
144 }