1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
|
package com.android.internal.util;
import android.util.Printer;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
public class FastPrintWriter extends PrintWriter {
private static class DummyWriter extends Writer {
@Override
public void close() throws IOException {
UnsupportedOperationException ex
= new UnsupportedOperationException("Shouldn't be here");
throw ex;
}
@Override
public void flush() throws IOException {
close();
}
@Override
public void write(char[] buf, int offset, int count) throws IOException {
close();
}
};
private final int mBufferLen;
private final char[] mText;
private int mPos;
final private OutputStream mOutputStream;
final private boolean mAutoFlush;
final private String mSeparator;
final private Writer mWriter;
final private Printer mPrinter;
private CharsetEncoder mCharset;
final private ByteBuffer mBytes;
private boolean mIoError;
/**
* Constructs a new {@code PrintWriter} with {@code out} as its target
* stream. By default, the new print writer does not automatically flush its
* contents to the target stream when a newline is encountered.
*
* @param out
* the target output stream.
* @throws NullPointerException
* if {@code out} is {@code null}.
*/
public FastPrintWriter(OutputStream out) {
this(out, false, 8192);
}
/**
* Constructs a new {@code PrintWriter} with {@code out} as its target
* stream. The parameter {@code autoFlush} determines if the print writer
* automatically flushes its contents to the target stream when a newline is
* encountered.
*
* @param out
* the target output stream.
* @param autoFlush
* indicates whether contents are flushed upon encountering a
* newline sequence.
* @throws NullPointerException
* if {@code out} is {@code null}.
*/
public FastPrintWriter(OutputStream out, boolean autoFlush) {
this(out, autoFlush, 8192);
}
/**
* Constructs a new {@code PrintWriter} with {@code out} as its target
* stream and a custom buffer size. The parameter {@code autoFlush} determines
* if the print writer automatically flushes its contents to the target stream
* when a newline is encountered.
*
* @param out
* the target output stream.
* @param autoFlush
* indicates whether contents are flushed upon encountering a
* newline sequence.
* @param bufferLen
* specifies the size of the FastPrintWriter's internal buffer; the
* default is 8192.
* @throws NullPointerException
* if {@code out} is {@code null}.
*/
public FastPrintWriter(OutputStream out, boolean autoFlush, int bufferLen) {
super(new DummyWriter(), autoFlush);
if (out == null) {
throw new NullPointerException("out is null");
}
mBufferLen = bufferLen;
mText = new char[bufferLen];
mBytes = ByteBuffer.allocate(mBufferLen);
mOutputStream = out;
mWriter = null;
mPrinter = null;
mAutoFlush = autoFlush;
mSeparator = System.lineSeparator();
initDefaultEncoder();
}
/**
* Constructs a new {@code PrintWriter} with {@code wr} as its target
* writer. By default, the new print writer does not automatically flush its
* contents to the target writer when a newline is encountered.
*
* <p>NOTE: Unlike PrintWriter, this version will still do buffering inside of
* FastPrintWriter before sending data to the Writer. This means you must call
* flush() before retrieving any data from the Writer.</p>
*
* @param wr
* the target writer.
* @throws NullPointerException
* if {@code wr} is {@code null}.
*/
public FastPrintWriter(Writer wr) {
this(wr, false, 8192);
}
/**
* Constructs a new {@code PrintWriter} with {@code wr} as its target
* writer. The parameter {@code autoFlush} determines if the print writer
* automatically flushes its contents to the target writer when a newline is
* encountered.
*
* @param wr
* the target writer.
* @param autoFlush
* indicates whether to flush contents upon encountering a
* newline sequence.
* @throws NullPointerException
* if {@code out} is {@code null}.
*/
public FastPrintWriter(Writer wr, boolean autoFlush) {
this(wr, autoFlush, 8192);
}
/**
* Constructs a new {@code PrintWriter} with {@code wr} as its target
* writer and a custom buffer size. The parameter {@code autoFlush} determines
* if the print writer automatically flushes its contents to the target writer
* when a newline is encountered.
*
* @param wr
* the target writer.
* @param autoFlush
* indicates whether to flush contents upon encountering a
* newline sequence.
* @param bufferLen
* specifies the size of the FastPrintWriter's internal buffer; the
* default is 8192.
* @throws NullPointerException
* if {@code wr} is {@code null}.
*/
public FastPrintWriter(Writer wr, boolean autoFlush, int bufferLen) {
super(new DummyWriter(), autoFlush);
if (wr == null) {
throw new NullPointerException("wr is null");
}
mBufferLen = bufferLen;
mText = new char[bufferLen];
mBytes = null;
mOutputStream = null;
mWriter = wr;
mPrinter = null;
mAutoFlush = autoFlush;
mSeparator = System.lineSeparator();
initDefaultEncoder();
}
/**
* Constructs a new {@code PrintWriter} with {@code pr} as its target
* printer and the default buffer size. Because a {@link Printer} is line-base,
* autoflush is always enabled.
*
* @param pr
* the target writer.
* @throws NullPointerException
* if {@code pr} is {@code null}.
*/
public FastPrintWriter(Printer pr) {
this(pr, 512);
}
/**
* Constructs a new {@code PrintWriter} with {@code pr} as its target
* printer and a custom buffer size. Because a {@link Printer} is line-base,
* autoflush is always enabled.
*
* @param pr
* the target writer.
* @param bufferLen
* specifies the size of the FastPrintWriter's internal buffer; the
* default is 512.
* @throws NullPointerException
* if {@code pr} is {@code null}.
*/
public FastPrintWriter(Printer pr, int bufferLen) {
super(new DummyWriter(), true);
if (pr == null) {
throw new NullPointerException("pr is null");
}
mBufferLen = bufferLen;
mText = new char[bufferLen];
mBytes = null;
mOutputStream = null;
mWriter = null;
mPrinter = pr;
mAutoFlush = true;
mSeparator = System.lineSeparator();
initDefaultEncoder();
}
private final void initEncoder(String csn) throws UnsupportedEncodingException {
try {
mCharset = Charset.forName(csn).newEncoder();
} catch (Exception e) {
throw new UnsupportedEncodingException(csn);
}
mCharset.onMalformedInput(CodingErrorAction.REPLACE);
mCharset.onUnmappableCharacter(CodingErrorAction.REPLACE);
}
/**
* Flushes this writer and returns the value of the error flag.
*
* @return {@code true} if either an {@code IOException} has been thrown
* previously or if {@code setError()} has been called;
* {@code false} otherwise.
* @see #setError()
*/
public boolean checkError() {
flush();
synchronized (lock) {
return mIoError;
}
}
/**
* Sets the error state of the stream to false.
* @since 1.6
*/
protected void clearError() {
synchronized (lock) {
mIoError = false;
}
}
/**
* Sets the error flag of this writer to true.
*/
protected void setError() {
synchronized (lock) {
mIoError = true;
}
}
private final void initDefaultEncoder() {
mCharset = Charset.defaultCharset().newEncoder();
mCharset.onMalformedInput(CodingErrorAction.REPLACE);
mCharset.onUnmappableCharacter(CodingErrorAction.REPLACE);
}
private void appendLocked(char c) throws IOException {
int pos = mPos;
if (pos >= (mBufferLen-1)) {
flushLocked();
pos = mPos;
}
mText[pos] = c;
mPos = pos+1;
}
private void appendLocked(String str, int i, final int length) throws IOException {
final int BUFFER_LEN = mBufferLen;
if (length > BUFFER_LEN) {
final int end = i + length;
while (i < end) {
int next = i + BUFFER_LEN;
appendLocked(str, i, next < end ? BUFFER_LEN : (end - i));
i = next;
}
return;
}
int pos = mPos;
if ((pos+length) > BUFFER_LEN) {
flushLocked();
pos = mPos;
}
str.getChars(i, i + length, mText, pos);
mPos = pos + length;
}
private void appendLocked(char[] buf, int i, final int length) throws IOException {
final int BUFFER_LEN = mBufferLen;
if (length > BUFFER_LEN) {
final int end = i + length;
while (i < end) {
int next = i + BUFFER_LEN;
appendLocked(buf, i, next < end ? BUFFER_LEN : (end - i));
i = next;
}
return;
}
int pos = mPos;
if ((pos+length) > BUFFER_LEN) {
flushLocked();
pos = mPos;
}
System.arraycopy(buf, i, mText, pos, length);
mPos = pos + length;
}
private void flushBytesLocked() throws IOException {
int position;
if ((position = mBytes.position()) > 0) {
mBytes.flip();
mOutputStream.write(mBytes.array(), 0, position);
mBytes.clear();
}
}
private void flushLocked() throws IOException {
//Log.i("PackageManager", "flush mPos=" + mPos);
if (mPos > 0) {
if (mOutputStream != null) {
CharBuffer charBuffer = CharBuffer.wrap(mText, 0, mPos);
CoderResult result = mCharset.encode(charBuffer, mBytes, true);
while (true) {
if (result.isError()) {
throw new IOException(result.toString());
} else if (result.isOverflow()) {
flushBytesLocked();
result = mCharset.encode(charBuffer, mBytes, true);
continue;
}
break;
}
flushBytesLocked();
mOutputStream.flush();
} else if (mWriter != null) {
mWriter.write(mText, 0, mPos);
mWriter.flush();
} else {
int nonEolOff = 0;
final int sepLen = mSeparator.length();
final int len = sepLen < mPos ? sepLen : mPos;
while (nonEolOff < len && mText[mPos-1-nonEolOff]
== mSeparator.charAt(mSeparator.length()-1-nonEolOff)) {
nonEolOff++;
}
if (nonEolOff >= mPos) {
mPrinter.println("");
} else {
mPrinter.println(new String(mText, 0, mPos-nonEolOff));
}
}
mPos = 0;
}
}
/**
* Ensures that all pending data is sent out to the target. It also
* flushes the target. If an I/O error occurs, this writer's error
* state is set to {@code true}.
*/
@Override
public void flush() {
synchronized (lock) {
try {
flushLocked();
if (mOutputStream != null) {
mOutputStream.flush();
} else if (mWriter != null) {
mWriter.flush();
}
} catch (IOException e) {
setError();
}
}
}
@Override
public void close() {
synchronized (lock) {
try {
flushLocked();
if (mOutputStream != null) {
mOutputStream.close();
} else if (mWriter != null) {
mWriter.close();
}
} catch (IOException e) {
setError();
}
}
}
/**
* Prints the string representation of the specified character array
* to the target.
*
* @param charArray
* the character array to print to the target.
* @see #print(String)
*/
public void print(char[] charArray) {
synchronized (lock) {
try {
appendLocked(charArray, 0, charArray.length);
} catch (IOException e) {
}
}
}
/**
* Prints the string representation of the specified character to the
* target.
*
* @param ch
* the character to print to the target.
* @see #print(String)
*/
public void print(char ch) {
synchronized (lock) {
try {
appendLocked(ch);
} catch (IOException e) {
}
}
}
/**
* Prints a string to the target. The string is converted to an array of
* bytes using the encoding chosen during the construction of this writer.
* The bytes are then written to the target with {@code write(int)}.
* <p>
* If an I/O error occurs, this writer's error flag is set to {@code true}.
*
* @param str
* the string to print to the target.
* @see #write(int)
*/
public void print(String str) {
if (str == null) {
str = String.valueOf((Object) null);
}
synchronized (lock) {
try {
appendLocked(str, 0, str.length());
} catch (IOException e) {
setError();
}
}
}
@Override
public void print(int inum) {
if (inum == 0) {
print("0");
} else {
super.print(inum);
}
}
@Override
public void print(long lnum) {
if (lnum == 0) {
print("0");
} else {
super.print(lnum);
}
}
/**
* Prints a newline. Flushes this writer if the autoFlush flag is set to {@code true}.
*/
public void println() {
synchronized (lock) {
try {
appendLocked(mSeparator, 0, mSeparator.length());
if (mAutoFlush) {
flushLocked();
}
} catch (IOException e) {
setError();
}
}
}
@Override
public void println(int inum) {
if (inum == 0) {
println("0");
} else {
super.println(inum);
}
}
@Override
public void println(long lnum) {
if (lnum == 0) {
println("0");
} else {
super.println(lnum);
}
}
/**
* Prints the string representation of the character array {@code chars} followed by a newline.
* Flushes this writer if the autoFlush flag is set to {@code true}.
*/
public void println(char[] chars) {
print(chars);
println();
}
/**
* Prints the string representation of the char {@code c} followed by a newline.
* Flushes this writer if the autoFlush flag is set to {@code true}.
*/
public void println(char c) {
print(c);
println();
}
/**
* Writes {@code count} characters from {@code buffer} starting at {@code
* offset} to the target.
* <p>
* This writer's error flag is set to {@code true} if this writer is closed
* or an I/O error occurs.
*
* @param buf
* the buffer to write to the target.
* @param offset
* the index of the first character in {@code buffer} to write.
* @param count
* the number of characters in {@code buffer} to write.
* @throws IndexOutOfBoundsException
* if {@code offset < 0} or {@code count < 0}, or if {@code
* offset + count} is greater than the length of {@code buf}.
*/
@Override
public void write(char[] buf, int offset, int count) {
synchronized (lock) {
try {
appendLocked(buf, offset, count);
} catch (IOException e) {
}
}
}
/**
* Writes one character to the target. Only the two least significant bytes
* of the integer {@code oneChar} are written.
* <p>
* This writer's error flag is set to {@code true} if this writer is closed
* or an I/O error occurs.
*
* @param oneChar
* the character to write to the target.
*/
@Override
public void write(int oneChar) {
synchronized (lock) {
try {
appendLocked((char) oneChar);
} catch (IOException e) {
}
}
}
/**
* Writes the characters from the specified string to the target.
*
* @param str
* the non-null string containing the characters to write.
*/
@Override
public void write(String str) {
synchronized (lock) {
try {
appendLocked(str, 0, str.length());
} catch (IOException e) {
}
}
}
/**
* Writes {@code count} characters from {@code str} starting at {@code
* offset} to the target.
*
* @param str
* the non-null string containing the characters to write.
* @param offset
* the index of the first character in {@code str} to write.
* @param count
* the number of characters from {@code str} to write.
* @throws IndexOutOfBoundsException
* if {@code offset < 0} or {@code count < 0}, or if {@code
* offset + count} is greater than the length of {@code str}.
*/
@Override
public void write(String str, int offset, int count) {
synchronized (lock) {
try {
appendLocked(str, offset, count);
} catch (IOException e) {
}
}
}
/**
* Appends a subsequence of the character sequence {@code csq} to the
* target. This method works the same way as {@code
* PrintWriter.print(csq.subsequence(start, end).toString())}. If {@code
* csq} is {@code null}, then the specified subsequence of the string "null"
* will be written to the target.
*
* @param csq
* the character sequence appended to the target.
* @param start
* the index of the first char in the character sequence appended
* to the target.
* @param end
* the index of the character following the last character of the
* subsequence appended to the target.
* @return this writer.
* @throws StringIndexOutOfBoundsException
* if {@code start > end}, {@code start < 0}, {@code end < 0} or
* either {@code start} or {@code end} are greater or equal than
* the length of {@code csq}.
*/
@Override
public PrintWriter append(CharSequence csq, int start, int end) {
if (csq == null) {
csq = "null";
}
String output = csq.subSequence(start, end).toString();
write(output, 0, output.length());
return this;
}
}
|