Debian Codegraph @

net/sf/saxon/serialize/UTF8Writer.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.serialize;
9
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.io.Writer;
13
14 /**
15 * Specialized buffering UTF-8 writer.
16 * The main reason for custom version is to allow for efficient
17 * buffer recycling; the second benefit is that encoder has less
18 * overhead for short content encoding (compared to JDK default
19 * codecs).
20 *
21 * @author Tatu Saloranta
22 */
23 public final class UTF8Writer
24 extends Writer {
25 private final static int MIN_BUF_LEN = 32;
26 private final static int DEFAULT_BUF_LEN = 4000;
27
28 final static int SURR1_FIRST = 0xD800;
29 final static int SURR1_LAST = 0xDBFF;
30 final static int SURR2_FIRST = 0xDC00;
31 final static int SURR2_LAST = 0xDFFF;
32
33 /*@Nullable*/ protected OutputStream _out;
34
35 protected byte[] _outBuffer;
36
37 final protected int _outBufferLast;
38
39 protected int _outPtr;
40
41 /**
42 * When outputting chars from BMP, surrogate pairs need to be coalesced.
43 * To do this, both pairs must be known first; and since it is possible
44 * pairs may be split, we need temporary storage for the first half
45 */
46 int _surrogate = 0;
47
48 public UTF8Writer(OutputStream out) {
49 this(out, DEFAULT_BUF_LEN);
50 }
51
52 public UTF8Writer(OutputStream out, int bufferLength) {
53 if (bufferLength < MIN_BUF_LEN) {
54 bufferLength = MIN_BUF_LEN;
55 }
56 _out = out;
57 _outBuffer = new byte[bufferLength];
58 /* Max. expansion for a single Unicode code point is 4 bytes when
59 * recombining UCS-2 surrogate pairs, so:
60 */
61 _outBufferLast = bufferLength - 4;
62 _outPtr = 0;
63 }
64
65 /*
66 ////////////////////////////////////////////////////////
67 // java.io.Writer implementation
68 ////////////////////////////////////////////////////////
69 */
70
71 /* Due to co-variance between Appendable and
72 * Writer, this would not compile with javac 1.5, in 1.4 mode
73 * (source and target set to "1.4". Not a huge deal, but since
74 * the base impl is just fine, no point in overriding it.
75 */
76 /*
77 public Writer append(char c) throws IOException {
78 // note: this is a JDK 1.5 method
79 write(c);
80 return this;
81 }
82 */
83
84 public void close() throws IOException {
85 if (_out != null) {
86 _flushBuffer();
87 _outBuffer = null;
88 _out.close();
89 _out = null;
90
91 /* If we are left with partial surrogate we have a problem, but
92 * let's not let it prevent closure of the underlying stream
93 */
94 if (_surrogate != 0) {
95 int code = _surrogate;
96 // but let's clear it, to get just one problem?
97 _surrogate = 0;
98 throwIllegal(code);
99 }
100 }
101 }
102
103 public void flush() throws IOException {
104 _flushBuffer();
105 _out.flush();
106 }
107
108 public void write(char[] cbuf) throws IOException {
109 write(cbuf, 0, cbuf.length);
110 }
111
112 public void write(char[] cbuf, int off, int len)
113 throws IOException {
114 if (len < 2) {
115 if (len == 1) {
116 write(cbuf[off]);
117 }
118 return;
119 }
120
121 // First: do we have a leftover surrogate to deal with?
122 if (_surrogate > 0) {
123 char second = cbuf[off++];
124 --len;
125 write(_convertSurrogate(second));
126 // will have at least one more char
127 }
128
129 int outPtr = _outPtr;
130 byte[] outBuf = _outBuffer;
131 int outBufLast = _outBufferLast; // has 4 'spare' bytes
132
133 // All right; can just loop it nice and easy now:
134 len += off; // len will now be the end of input buffer
135
136 output_loop:
137 for (; off < len; ) {
138 /* First, let's ensure we can output at least 4 bytes
139 * (longest UTF-8 encoded codepoint):
140 */
141 if (outPtr >= outBufLast) {
142 _out.write(outBuf, 0, outPtr);
143 outPtr = 0;
144 }
145
146 int c = cbuf[off++];
147 // And then see if we have an Ascii char:
148 if (c < 0x80) { // If so, can do a tight inner loop:
149 outBuf[outPtr++] = (byte) c;
150 // Let's calc how many ascii chars we can copy at most:
151 int maxInCount = (len - off);
152 int maxOutCount = (outBufLast - outPtr);
153
154 if (maxInCount > maxOutCount) {
155 maxInCount = maxOutCount;
156 }
157 maxInCount += off;
158 ascii_loop:
159 while (true) {
160 if (off >= maxInCount) { // done with max. ascii seq
161 continue output_loop;
162 }
163 c = cbuf[off++];
164 if (c >= 0x80) {
165 break ascii_loop;
166 }
167 outBuf[outPtr++] = (byte) c;
168 }
169 }
170
171 // Nope, multi-byte:
172 if (c < 0x800) { // 2-byte
173 outBuf[outPtr++] = (byte) (0xc0 | (c >> 6));
174 outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f));
175 } else { // 3 or 4 bytes
176 // Surrogates?
177 if (c < SURR1_FIRST || c > SURR2_LAST) {
178 outBuf[outPtr++] = (byte) (0xe0 | (c >> 12));
179 outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
180 outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f));
181 continue;
182 }
183 // Yup, a surrogate:
184 if (c > SURR1_LAST) { // must be from first range
185 _outPtr = outPtr;
186 throwIllegal(c);
187 }
188 _surrogate = c;
189 // and if so, followed by another from next range
190 if (off >= len) { // unless we hit the end?
191 break;
192 }
193 c = _convertSurrogate(cbuf[off++]);
194 if (c > 0x10FFFF) { // illegal, as per RFC 3629
195 _outPtr = outPtr;
196 throwIllegal(c);
197 }
198 outBuf[outPtr++] = (byte) (0xf0 | (c >> 18));
199 outBuf[outPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f));
200 outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
201 outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f));
202 }
203 }
204 _outPtr = outPtr;
205 }
206
207 public void write(int c)
208 throws IOException {
209 // First; do we have a left over surrogate?
210 if (_surrogate > 0) {
211 c = _convertSurrogate(c);
212 // If not, do we start with a surrogate?
213 } else if (c >= SURR1_FIRST && c <= SURR2_LAST) {
214 // Illegal to get second part without first:
215 if (c > SURR1_LAST) {
216 throwIllegal(c);
217 }
218 // First part just needs to be held for now
219 _surrogate = c;
220 return;
221 }
222
223 if (_outPtr >= _outBufferLast) { // let's require enough room, first
224 _flushBuffer();
225 }
226
227 if (c < 0x80) { // ascii
228 _outBuffer[_outPtr++] = (byte) c;
229 } else {
230 int ptr = _outPtr;
231 if (c < 0x800) { // 2-byte
232 _outBuffer[ptr++] = (byte) (0xc0 | (c >> 6));
233 _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f));
234 } else if (c <= 0xFFFF) { // 3 bytes
235 _outBuffer[ptr++] = (byte) (0xe0 | (c >> 12));
236 _outBuffer[ptr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
237 _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f));
238 } else { // 4 bytes
239 if (c > 0x10FFFF) { // illegal, as per RFC 3629
240 throwIllegal(c);
241 }
242 _outBuffer[ptr++] = (byte) (0xf0 | (c >> 18));
243 _outBuffer[ptr++] = (byte) (0x80 | ((c >> 12) & 0x3f));
244 _outBuffer[ptr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
245 _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f));
246 }
247 _outPtr = ptr;
248 }
249 }
250
251 public void write(String str)
252 throws IOException {
253 write(str, 0, str.length());
254 }
255
256 public void write(String str, int off, int len)
257 throws IOException {
258 if (len < 2) {
259 if (len == 1) {
260 write(str.charAt(off));
261 }
262 return;
263 }
264
265 // First: do we have a leftover surrogate to deal with?
266 if (_surrogate > 0) {
267 char second = str.charAt(off++);
268 --len;
269 write(_convertSurrogate(second));
270 // will have at least one more char (case of 1 char was checked earlier on)
271 }
272
273 int outPtr = _outPtr;
274 byte[] outBuf = _outBuffer;
275 int outBufLast = _outBufferLast; // has 4 'spare' bytes
276
277 // All right; can just loop it nice and easy now:
278 len += off; // len will now be the end of input buffer
279
280 output_loop:
281 for (; off < len; ) {
282 // First, let's ensure we can output at least 4 bytes
283 // (longest UTF-8 encoded codepoint):
284 if (outPtr >= outBufLast) {
285 _out.write(outBuf, 0, outPtr);
286 outPtr = 0;
287 }
288
289 int c = str.charAt(off++);
290 // And then see if we have an Ascii char:
291 if (c < 0x80) { // If so, can do a tight inner loop:
292 outBuf[outPtr++] = (byte) c;
293 // Let's calc how many ascii chars we can copy at most:
294 int maxInCount = (len - off);
295 int maxOutCount = (outBufLast - outPtr);
296
297 if (maxInCount > maxOutCount) {
298 maxInCount = maxOutCount;
299 }
300 maxInCount += off;
301 ascii_loop:
302 while (true) {
303 if (off >= maxInCount) { // done with max. ascii seq
304 continue output_loop;
305 }
306 c = str.charAt(off++);
307 if (c >= 0x80) {
308 break ascii_loop;
309 }
310 outBuf[outPtr++] = (byte) c;
311 }
312 }
313
314 // Nope, multi-byte:
315 if (c < 0x800) { // 2-byte
316 outBuf[outPtr++] = (byte) (0xc0 | (c >> 6));
317 outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f));
318 } else { // 3 or 4 bytes
319 // Surrogates?
320 if (c < SURR1_FIRST || c > SURR2_LAST) {
321 outBuf[outPtr++] = (byte) (0xe0 | (c >> 12));
322 outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
323 outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f));
324 continue;
325 }
326 // Yup, a surrogate:
327 if (c > SURR1_LAST) { // must be from first range
328 _outPtr = outPtr;
329 throwIllegal(c);
330 }
331 _surrogate = c;
332 // and if so, followed by another from next range
333 if (off >= len) { // unless we hit the end?
334 break;
335 }
336 c = _convertSurrogate(str.charAt(off++));
337 if (c > 0x10FFFF) { // illegal, as per RFC 3629
338 _outPtr = outPtr;
339 throwIllegal(c);
340 }
341 outBuf[outPtr++] = (byte) (0xf0 | (c >> 18));
342 outBuf[outPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f));
343 outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
344 outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f));
345 }
346 }
347 _outPtr = outPtr;
348 }
349
350 /*
351 ////////////////////////////////////////////////////////////
352 // Internal methods
353 ////////////////////////////////////////////////////////////
354 */
355
356 private void _flushBuffer() throws IOException {
357 if (_outPtr > 0 && _outBuffer != null) {
358 _out.write(_outBuffer, 0, _outPtr);
359 _outPtr = 0;
360 }
361 }
362
363 /**
364 * Method called to calculate UTF codepoint, from a surrogate pair.
365 */
366 private final int _convertSurrogate(int secondPart)
367 throws IOException {
368 int firstPart = _surrogate;
369 _surrogate = 0;
370
371 // Ok, then, is the second part valid?
372 if (secondPart < SURR2_FIRST || secondPart > SURR2_LAST) {
373 throw new IOException("Broken surrogate pair: first char 0x" + Integer.toHexString(firstPart) + ", second 0x" + Integer.toHexString(secondPart) + "; illegal combination");
374 }
375 return 0x10000 + ((firstPart - SURR1_FIRST) << 10) + (secondPart - SURR2_FIRST);
376 }
377
378 private void throwIllegal(int code)
379 throws IOException {
380 if (code > 0x10FFFF) { // over max?
381 throw new IOException("Illegal character point (0x" + Integer.toHexString(code) + ") to output; max is 0x10FFFF as per RFC 3629");
382 }
383 if (code >= SURR1_FIRST) {
384 if (code <= SURR1_LAST) { // Unmatched first part (closing without second part?)
385 throw new IOException("Unmatched first part of surrogate pair (0x" + Integer.toHexString(code) + ")");
386 }
387 throw new IOException("Unmatched second part of surrogate pair (0x" + Integer.toHexString(code) + ")");
388 }
389
390 // should we ever get this?
391 throw new IOException("Illegal character point (0x" + Integer.toHexString(code) + ") to output");
392 }
393 }
394