1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 // -- This file was mechanically generated: Do not edit! -- //
28 
29 package java.nio.charset;
30 
31 import java.nio.Buffer;
32 import java.nio.ByteBuffer;
33 import java.nio.CharBuffer;
34 import java.nio.BufferOverflowException;
35 import java.nio.BufferUnderflowException;
36 import java.lang.ref.WeakReference;
37 import java.nio.charset.CoderMalfunctionError;                  // javadoc
38 import java.util.Arrays;
39 import java.util.Objects;
40 
41 
42 /**
43  * An engine that can transform a sequence of sixteen-bit Unicode characters into a sequence of
44  * bytes in a specific charset.
45  *
46  * <a id="steps"></a>
47  *
48  * <p> The input character sequence is provided in a character buffer or a series
49  * of such buffers.  The output byte sequence is written to a byte buffer
50  * or a series of such buffers.  An encoder should always be used by making
51  * the following sequence of method invocations, hereinafter referred to as an
52  * <i>encoding operation</i>:
53  *
54  * <ol>
55  *
56  *   <li><p> Reset the encoder via the {@link #reset reset} method, unless it
57  *   has not been used before; </p></li>
58  *
59  *   <li><p> Invoke the {@link #encode encode} method zero or more times, as
60  *   long as additional input may be available, passing {@code false} for the
61  *   {@code endOfInput} argument and filling the input buffer and flushing the
62  *   output buffer between invocations; </p></li>
63  *
64  *   <li><p> Invoke the {@link #encode encode} method one final time, passing
65  *   {@code true} for the {@code endOfInput} argument; and then </p></li>
66  *
67  *   <li><p> Invoke the {@link #flush flush} method so that the encoder can
68  *   flush any internal state to the output buffer. </p></li>
69  *
70  * </ol>
71  *
72  * Each invocation of the {@link #encode encode} method will encode as many
73  * characters as possible from the input buffer, writing the resulting bytes
74  * to the output buffer.  The {@link #encode encode} method returns when more
75  * input is required, when there is not enough room in the output buffer, or
76  * when an encoding error has occurred.  In each case a {@link CoderResult}
77  * object is returned to describe the reason for termination.  An invoker can
78  * examine this object and fill the input buffer, flush the output buffer, or
79  * attempt to recover from an encoding error, as appropriate, and try again.
80  *
81  * <a id="ce"></a>
82  *
83  * <p> There are two general types of encoding errors.  If the input character
84  * sequence is not a legal sixteen-bit Unicode sequence then the input is considered <i>malformed</i>.  If
85  * the input character sequence is legal but cannot be mapped to a valid
86  * byte sequence in the given charset then an <i>unmappable character</i> has been encountered.
87  *
88  * <a id="cae"></a>
89  *
90  * <p> How an encoding error is handled depends upon the action requested for
91  * that type of error, which is described by an instance of the {@link
92  * CodingErrorAction} class.  The possible error actions are to {@linkplain
93  * CodingErrorAction#IGNORE ignore} the erroneous input, {@linkplain
94  * CodingErrorAction#REPORT report} the error to the invoker via
95  * the returned {@link CoderResult} object, or {@linkplain CodingErrorAction#REPLACE
96  * replace} the erroneous input with the current value of the
97  * replacement byte array.  The replacement
98  *
99 
100  * is initially set to the encoder's default replacement, which often
101  * (but not always) has the initial value&nbsp;<code>{</code>&nbsp;<code>(byte)'?'</code>&nbsp;<code>}</code>;
102 
103 
104 
105 
106  *
107  * its value may be changed via the {@link #replaceWith(byte[])
108  * replaceWith} method.
109  *
110  * <p> The default action for malformed-input and unmappable-character errors
111  * is to {@linkplain CodingErrorAction#REPORT report} them.  The
112  * malformed-input error action may be changed via the {@link
113  * #onMalformedInput(CodingErrorAction) onMalformedInput} method; the
114  * unmappable-character action may be changed via the {@link
115  * #onUnmappableCharacter(CodingErrorAction) onUnmappableCharacter} method.
116  *
117  * <p> This class is designed to handle many of the details of the encoding
118  * process, including the implementation of error actions.  An encoder for a
119  * specific charset, which is a concrete subclass of this class, need only
120  * implement the abstract {@link #encodeLoop encodeLoop} method, which
121  * encapsulates the basic encoding loop.  A subclass that maintains internal
122  * state should, additionally, override the {@link #implFlush implFlush} and
123  * {@link #implReset implReset} methods.
124  *
125  * <p> Instances of this class are not safe for use by multiple concurrent
126  * threads.  </p>
127  *
128  *
129  * @author Mark Reinhold
130  * @author JSR-51 Expert Group
131  * @since 1.4
132  *
133  * @see ByteBuffer
134  * @see CharBuffer
135  * @see Charset
136  * @see CharsetDecoder
137  */
138 
139 public abstract class CharsetEncoder {
140 
141     private final Charset charset;
142     private final float averageBytesPerChar;
143     private final float maxBytesPerChar;
144 
145     private byte[] replacement;
146     private CodingErrorAction malformedInputAction
147         = CodingErrorAction.REPORT;
148     private CodingErrorAction unmappableCharacterAction
149         = CodingErrorAction.REPORT;
150 
151     // Internal states
152     //
153     private static final int ST_RESET   = 0;
154     private static final int ST_CODING  = 1;
155     private static final int ST_END     = 2;
156     private static final int ST_FLUSHED = 3;
157 
158     private int state = ST_RESET;
159 
160     private static String stateNames[]
161         = { "RESET", "CODING", "CODING_END", "FLUSHED" };
162 
163 
164     /**
165      * Initializes a new encoder.  The new encoder will have the given
166      * bytes-per-char and replacement values.
167      *
168      * @param  cs
169      *         The charset that created this encoder
170      *
171      * @param  averageBytesPerChar
172      *         A positive float value indicating the expected number of
173      *         bytes that will be produced for each input character
174      *
175      * @param  maxBytesPerChar
176      *         A positive float value indicating the maximum number of
177      *         bytes that will be produced for each input character
178      *
179      * @param  replacement
180      *         The initial replacement; must not be {@code null}, must have
181      *         non-zero length, must not be longer than maxBytesPerChar,
182      *         and must be {@linkplain #isLegalReplacement legal}
183      *
184      * @throws  IllegalArgumentException
185      *          If the preconditions on the parameters do not hold
186      */
187     protected
CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement)188     CharsetEncoder(Charset cs,
189                    float averageBytesPerChar,
190                    float maxBytesPerChar,
191                    byte[] replacement)
192     {
193 
194         // BEGIN Android-added: A hidden constructor for the CharsetEncoderICU subclass.
195         this(cs, averageBytesPerChar, maxBytesPerChar, replacement, false);
196     }
197 
198     /**
199      * This constructor is for subclasses to specify whether {@code replacement} can be used as it
200      * is ("trusted"). If it is trusted, {@link #replaceWith(byte[])} and
201      * {@link #implReplaceWith(byte[])} will not be called.
202      * @hide
203      */
CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement, boolean trusted)204     protected CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement,
205             boolean trusted)
206     {
207         // END Android-added: A hidden constructor for the CharsetEncoderICU subclass.
208 
209         this.charset = cs;
210         // Use !(a > 0.0f) rather than (a <= 0.0f) to exclude NaN values
211         if (!(averageBytesPerChar > 0.0f))
212             throw new IllegalArgumentException("Non-positive "
213                                                + "averageBytesPerChar");
214         // Use !(a > 0.0f) rather than (a <= 0.0f) to exclude NaN values
215         if (!(maxBytesPerChar > 0.0f))
216             throw new IllegalArgumentException("Non-positive "
217                                                + "maxBytesPerChar");
218         if (averageBytesPerChar > maxBytesPerChar)
219             throw new IllegalArgumentException("averageBytesPerChar"
220                                                + " exceeds "
221                                                + "maxBytesPerChar");
222         this.replacement = replacement;
223         this.averageBytesPerChar = averageBytesPerChar;
224         this.maxBytesPerChar = maxBytesPerChar;
225 
226 
227 
228 
229 
230 
231         // BEGIN Android-changed: Avoid calling replaceWith() for trusted subclasses.
232         // replaceWith(replacement);
233         if (!trusted) {
234             replaceWith(replacement);
235         }
236         // END Android-changed: Avoid calling replaceWith() for trusted subclasses.
237 
238     }
239 
240     /**
241      * Initializes a new encoder.  The new encoder will have the given
242      * bytes-per-char values and its replacement will be the
243      * byte array <code>{</code>&nbsp;<code>(byte)'?'</code>&nbsp;<code>}</code>.
244      *
245      * @param  cs
246      *         The charset that created this encoder
247      *
248      * @param  averageBytesPerChar
249      *         A positive float value indicating the expected number of
250      *         bytes that will be produced for each input character
251      *
252      * @param  maxBytesPerChar
253      *         A positive float value indicating the maximum number of
254      *         bytes that will be produced for each input character
255      *
256      * @throws  IllegalArgumentException
257      *          If the preconditions on the parameters do not hold
258      */
CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar)259     protected CharsetEncoder(Charset cs,
260                              float averageBytesPerChar,
261                              float maxBytesPerChar)
262     {
263         this(cs,
264              averageBytesPerChar, maxBytesPerChar,
265              new byte[] { (byte)'?' });
266     }
267 
268     /**
269      * Returns the charset that created this encoder.
270      *
271      * @return  This encoder's charset
272      */
charset()273     public final Charset charset() {
274         return charset;
275     }
276 
277     /**
278      * Returns this encoder's replacement value.
279      *
280      * @return  This encoder's current replacement,
281      *          which is never {@code null} and is never empty
282      */
replacement()283     public final byte[] replacement() {
284 
285 
286 
287 
288         return Arrays.copyOf(replacement, replacement.length);
289 
290     }
291 
292     /**
293      * Changes this encoder's replacement value.
294      *
295      * <p> This method invokes the {@link #implReplaceWith implReplaceWith}
296      * method, passing the new replacement, after checking that the new
297      * replacement is acceptable.  </p>
298      *
299      * @param  newReplacement  The new replacement; must not be
300      *         {@code null}, must have non-zero length,
301 
302 
303 
304 
305 
306      *         must not be longer than the value returned by the
307      *         {@link #maxBytesPerChar() maxBytesPerChar} method, and
308      *         must be {@link #isLegalReplacement legal}
309 
310      *
311      * @return  This encoder
312      *
313      * @throws  IllegalArgumentException
314      *          If the preconditions on the parameter do not hold
315      */
replaceWith(byte[] newReplacement)316     public final CharsetEncoder replaceWith(byte[] newReplacement) {
317         if (newReplacement == null)
318             throw new IllegalArgumentException("Null replacement");
319         int len = newReplacement.length;
320         if (len == 0)
321             throw new IllegalArgumentException("Empty replacement");
322         if (len > maxBytesPerChar)
323             throw new IllegalArgumentException("Replacement too long");
324 
325 
326 
327 
328         if (!isLegalReplacement(newReplacement))
329             throw new IllegalArgumentException("Illegal replacement");
330         this.replacement = Arrays.copyOf(newReplacement, newReplacement.length);
331 
332         implReplaceWith(this.replacement);
333         return this;
334     }
335 
336     /**
337      * Reports a change to this encoder's replacement value.
338      *
339      * <p> The default implementation of this method does nothing.  This method
340      * should be overridden by encoders that require notification of changes to
341      * the replacement.  </p>
342      *
343      * @param  newReplacement    The replacement value
344      */
implReplaceWith(byte[] newReplacement)345     protected void implReplaceWith(byte[] newReplacement) {
346     }
347 
348 
349 
350     private WeakReference<CharsetDecoder> cachedDecoder = null;
351 
352     /**
353      * Tells whether or not the given byte array is a legal replacement value
354      * for this encoder.
355      *
356      * <p> A replacement is legal if, and only if, it is a legal sequence of
357      * bytes in this encoder's charset; that is, it must be possible to decode
358      * the replacement into one or more sixteen-bit Unicode characters.
359      *
360      * <p> The default implementation of this method is not very efficient; it
361      * should generally be overridden to improve performance.  </p>
362      *
363      * @param  repl  The byte array to be tested
364      *
365      * @return  {@code true} if, and only if, the given byte array
366      *          is a legal replacement value for this encoder
367      */
isLegalReplacement(byte[] repl)368     public boolean isLegalReplacement(byte[] repl) {
369         WeakReference<CharsetDecoder> wr = cachedDecoder;
370         CharsetDecoder dec = null;
371         if ((wr == null) || ((dec = wr.get()) == null)) {
372             dec = charset().newDecoder();
373             dec.onMalformedInput(CodingErrorAction.REPORT);
374             dec.onUnmappableCharacter(CodingErrorAction.REPORT);
375             cachedDecoder = new WeakReference<CharsetDecoder>(dec);
376         } else {
377             dec.reset();
378         }
379         ByteBuffer bb = ByteBuffer.wrap(repl);
380         CharBuffer cb = CharBuffer.allocate((int)(bb.remaining()
381                                                   * dec.maxCharsPerByte()));
382         CoderResult cr = dec.decode(bb, cb, true);
383         return !cr.isError();
384     }
385 
386 
387 
388     /**
389      * Returns this encoder's current action for malformed-input errors.
390      *
391      * @return The current malformed-input action, which is never {@code null}
392      */
malformedInputAction()393     public CodingErrorAction malformedInputAction() {
394         return malformedInputAction;
395     }
396 
397     /**
398      * Changes this encoder's action for malformed-input errors.
399      *
400      * <p> This method invokes the {@link #implOnMalformedInput
401      * implOnMalformedInput} method, passing the new action.  </p>
402      *
403      * @param  newAction  The new action; must not be {@code null}
404      *
405      * @return  This encoder
406      *
407      * @throws IllegalArgumentException
408      *         If the precondition on the parameter does not hold
409      */
onMalformedInput(CodingErrorAction newAction)410     public final CharsetEncoder onMalformedInput(CodingErrorAction newAction) {
411         if (newAction == null)
412             throw new IllegalArgumentException("Null action");
413         malformedInputAction = newAction;
414         implOnMalformedInput(newAction);
415         return this;
416     }
417 
418     /**
419      * Reports a change to this encoder's malformed-input action.
420      *
421      * <p> The default implementation of this method does nothing.  This method
422      * should be overridden by encoders that require notification of changes to
423      * the malformed-input action.  </p>
424      *
425      * @param  newAction  The new action
426      */
implOnMalformedInput(CodingErrorAction newAction)427     protected void implOnMalformedInput(CodingErrorAction newAction) { }
428 
429     /**
430      * Returns this encoder's current action for unmappable-character errors.
431      *
432      * @return The current unmappable-character action, which is never
433      *         {@code null}
434      */
unmappableCharacterAction()435     public CodingErrorAction unmappableCharacterAction() {
436         return unmappableCharacterAction;
437     }
438 
439     /**
440      * Changes this encoder's action for unmappable-character errors.
441      *
442      * <p> This method invokes the {@link #implOnUnmappableCharacter
443      * implOnUnmappableCharacter} method, passing the new action.  </p>
444      *
445      * @param  newAction  The new action; must not be {@code null}
446      *
447      * @return  This encoder
448      *
449      * @throws IllegalArgumentException
450      *         If the precondition on the parameter does not hold
451      */
onUnmappableCharacter(CodingErrorAction newAction)452     public final CharsetEncoder onUnmappableCharacter(CodingErrorAction
453                                                       newAction)
454     {
455         if (newAction == null)
456             throw new IllegalArgumentException("Null action");
457         unmappableCharacterAction = newAction;
458         implOnUnmappableCharacter(newAction);
459         return this;
460     }
461 
462     /**
463      * Reports a change to this encoder's unmappable-character action.
464      *
465      * <p> The default implementation of this method does nothing.  This method
466      * should be overridden by encoders that require notification of changes to
467      * the unmappable-character action.  </p>
468      *
469      * @param  newAction  The new action
470      */
implOnUnmappableCharacter(CodingErrorAction newAction)471     protected void implOnUnmappableCharacter(CodingErrorAction newAction) { }
472 
473     /**
474      * Returns the average number of bytes that will be produced for each
475      * character of input.  This heuristic value may be used to estimate the size
476      * of the output buffer required for a given input sequence.
477      *
478      * @return  The average number of bytes produced
479      *          per character of input
480      */
averageBytesPerChar()481     public final float averageBytesPerChar() {
482         return averageBytesPerChar;
483     }
484 
485     /**
486      * Returns the maximum number of bytes that will be produced for each
487      * character of input.  This value may be used to compute the worst-case size
488      * of the output buffer required for a given input sequence. This value
489      * accounts for any necessary content-independent prefix or suffix
490 
491      * bytes, such as byte-order marks.
492 
493 
494 
495 
496      *
497      * @return  The maximum number of bytes that will be produced per
498      *          character of input
499      */
maxBytesPerChar()500     public final float maxBytesPerChar() {
501         return maxBytesPerChar;
502     }
503 
504     // Android-changed: Keep compat behavior. Document NPE thrown for null arguments.
505     /**
506      * Encodes as many characters as possible from the given input buffer,
507      * writing the results to the given output buffer.
508      *
509      * <p> The buffers are read from, and written to, starting at their current
510      * positions.  At most {@link Buffer#remaining in.remaining()} characters
511      * will be read and at most {@link Buffer#remaining out.remaining()}
512      * bytes will be written.  The buffers' positions will be advanced to
513      * reflect the characters read and the bytes written, but their marks and
514      * limits will not be modified.
515      *
516      * <p> In addition to reading characters from the input buffer and writing
517      * bytes to the output buffer, this method returns a {@link CoderResult}
518      * object to describe its reason for termination:
519      *
520      * <ul>
521      *
522      *   <li><p> {@link CoderResult#UNDERFLOW} indicates that as much of the
523      *   input buffer as possible has been encoded.  If there is no further
524      *   input then the invoker can proceed to the next step of the
525      *   <a href="#steps">encoding operation</a>.  Otherwise this method
526      *   should be invoked again with further input.  </p></li>
527      *
528      *   <li><p> {@link CoderResult#OVERFLOW} indicates that there is
529      *   insufficient space in the output buffer to encode any more characters.
530      *   This method should be invoked again with an output buffer that has
531      *   more {@linkplain Buffer#remaining remaining} bytes. This is
532      *   typically done by draining any encoded bytes from the output
533      *   buffer.  </p></li>
534      *
535      *   <li><p> A {@linkplain CoderResult#malformedForLength
536      *   malformed-input} result indicates that a malformed-input
537      *   error has been detected.  The malformed characters begin at the input
538      *   buffer's (possibly incremented) position; the number of malformed
539      *   characters may be determined by invoking the result object's {@link
540      *   CoderResult#length() length} method.  This case applies only if the
541      *   {@linkplain #onMalformedInput malformed action} of this encoder
542      *   is {@link CodingErrorAction#REPORT}; otherwise the malformed input
543      *   will be ignored or replaced, as requested.  </p></li>
544      *
545      *   <li><p> An {@linkplain CoderResult#unmappableForLength
546      *   unmappable-character} result indicates that an
547      *   unmappable-character error has been detected.  The characters that
548      *   encode the unmappable character begin at the input buffer's (possibly
549      *   incremented) position; the number of such characters may be determined
550      *   by invoking the result object's {@link CoderResult#length() length}
551      *   method.  This case applies only if the {@linkplain #onUnmappableCharacter
552      *   unmappable action} of this encoder is {@link
553      *   CodingErrorAction#REPORT}; otherwise the unmappable character will be
554      *   ignored or replaced, as requested.  </p></li>
555      *
556      * </ul>
557      *
558      * In any case, if this method is to be reinvoked in the same encoding
559      * operation then care should be taken to preserve any characters remaining
560      * in the input buffer so that they are available to the next invocation.
561      *
562      * <p> The {@code endOfInput} parameter advises this method as to whether
563      * the invoker can provide further input beyond that contained in the given
564      * input buffer.  If there is a possibility of providing additional input
565      * then the invoker should pass {@code false} for this parameter; if there
566      * is no possibility of providing further input then the invoker should
567      * pass {@code true}.  It is not erroneous, and in fact it is quite
568      * common, to pass {@code false} in one invocation and later discover that
569      * no further input was actually available.  It is critical, however, that
570      * the final invocation of this method in a sequence of invocations always
571      * pass {@code true} so that any remaining unencoded input will be treated
572      * as being malformed.
573      *
574      * <p> This method works by invoking the {@link #encodeLoop encodeLoop}
575      * method, interpreting its results, handling error conditions, and
576      * reinvoking it as necessary.  </p>
577      *
578      *
579      * @param  in
580      *         The input character buffer
581      *
582      * @param  out
583      *         The output byte buffer
584      *
585      * @param  endOfInput
586      *         {@code true} if, and only if, the invoker can provide no
587      *         additional input characters beyond those in the given buffer
588      *
589      * @return  A coder-result object describing the reason for termination
590      *
591      * @throws  IllegalStateException
592      *          If an encoding operation is already in progress and the previous
593      *          step was an invocation neither of the {@link #reset reset}
594      *          method, nor of this method with a value of {@code false} for
595      *          the {@code endOfInput} parameter, nor of this method with a
596      *          value of {@code true} for the {@code endOfInput} parameter
597      *          but a return value indicating an incomplete encoding operation
598      *
599      * @throws  CoderMalfunctionError
600      *          If an invocation of the encodeLoop method threw
601      *          an unexpected exception
602      *
603      * @throws  NullPointerException if input or output buffer is null
604      */
encode(CharBuffer in, ByteBuffer out, boolean endOfInput)605     public final CoderResult encode(CharBuffer in, ByteBuffer out,
606                                     boolean endOfInput)
607     {
608         // Android-added: Keep compat behavior. libcore throws NPE for null arguments.
609         Objects.requireNonNull(in, "in");
610         Objects.requireNonNull(out, "out");
611 
612         int newState = endOfInput ? ST_END : ST_CODING;
613         if ((state != ST_RESET) && (state != ST_CODING)
614             && !(endOfInput && (state == ST_END)))
615             throwIllegalStateException(state, newState);
616         state = newState;
617 
618         for (;;) {
619 
620             CoderResult cr;
621             try {
622                 cr = encodeLoop(in, out);
623             } catch (RuntimeException x) {
624                 throw new CoderMalfunctionError(x);
625             }
626 
627             if (cr.isOverflow())
628                 return cr;
629 
630             if (cr.isUnderflow()) {
631                 if (endOfInput && in.hasRemaining()) {
632                     cr = CoderResult.malformedForLength(in.remaining());
633                     // Fall through to malformed-input case
634                 } else {
635                     return cr;
636                 }
637             }
638 
639             CodingErrorAction action = null;
640             if (cr.isMalformed())
641                 action = malformedInputAction;
642             else if (cr.isUnmappable())
643                 action = unmappableCharacterAction;
644             else
645                 assert false : cr.toString();
646 
647             if (action == CodingErrorAction.REPORT)
648                 return cr;
649 
650             if (action == CodingErrorAction.REPLACE) {
651                 if (out.remaining() < replacement.length)
652                     return CoderResult.OVERFLOW;
653                 out.put(replacement);
654             }
655 
656             if ((action == CodingErrorAction.IGNORE)
657                 || (action == CodingErrorAction.REPLACE)) {
658                 // Skip erroneous input either way
659                 in.position(in.position() + cr.length());
660                 continue;
661             }
662 
663             assert false;
664         }
665 
666     }
667 
668     /**
669      * Flushes this encoder.
670      *
671      * <p> Some encoders maintain internal state and may need to write some
672      * final bytes to the output buffer once the overall input sequence has
673      * been read.
674      *
675      * <p> Any additional output is written to the output buffer beginning at
676      * its current position.  At most {@link Buffer#remaining out.remaining()}
677      * bytes will be written.  The buffer's position will be advanced
678      * appropriately, but its mark and limit will not be modified.
679      *
680      * <p> If this method completes successfully then it returns {@link
681      * CoderResult#UNDERFLOW}.  If there is insufficient room in the output
682      * buffer then it returns {@link CoderResult#OVERFLOW}.  If this happens
683      * then this method must be invoked again, with an output buffer that has
684      * more room, in order to complete the current <a href="#steps">encoding
685      * operation</a>.
686      *
687      * <p> If this encoder has already been flushed then invoking this method
688      * has no effect.
689      *
690      * <p> This method invokes the {@link #implFlush implFlush} method to
691      * perform the actual flushing operation.  </p>
692      *
693      * @param  out
694      *         The output byte buffer
695      *
696      * @return  A coder-result object, either {@link CoderResult#UNDERFLOW} or
697      *          {@link CoderResult#OVERFLOW}
698      *
699      * @throws  IllegalStateException
700      *          If the previous step of the current encoding operation was an
701      *          invocation neither of the {@link #flush flush} method nor of
702      *          the three-argument {@link
703      *          #encode(CharBuffer,ByteBuffer,boolean) encode} method
704      *          with a value of {@code true} for the {@code endOfInput}
705      *          parameter
706      */
flush(ByteBuffer out)707     public final CoderResult flush(ByteBuffer out) {
708         if (state == ST_END) {
709             CoderResult cr = implFlush(out);
710             if (cr.isUnderflow())
711                 state = ST_FLUSHED;
712             return cr;
713         }
714 
715         if (state != ST_FLUSHED)
716             throwIllegalStateException(state, ST_FLUSHED);
717 
718         return CoderResult.UNDERFLOW; // Already flushed
719     }
720 
721     /**
722      * Flushes this encoder.
723      *
724      * <p> The default implementation of this method does nothing, and always
725      * returns {@link CoderResult#UNDERFLOW}.  This method should be overridden
726      * by encoders that may need to write final bytes to the output buffer
727      * once the entire input sequence has been read. </p>
728      *
729      * @param  out
730      *         The output byte buffer
731      *
732      * @return  A coder-result object, either {@link CoderResult#UNDERFLOW} or
733      *          {@link CoderResult#OVERFLOW}
734      */
implFlush(ByteBuffer out)735     protected CoderResult implFlush(ByteBuffer out) {
736         return CoderResult.UNDERFLOW;
737     }
738 
739     /**
740      * Resets this encoder, clearing any internal state.
741      *
742      * <p> This method resets charset-independent state and also invokes the
743      * {@link #implReset() implReset} method in order to perform any
744      * charset-specific reset actions.  </p>
745      *
746      * @return  This encoder
747      *
748      */
reset()749     public final CharsetEncoder reset() {
750         implReset();
751         state = ST_RESET;
752         return this;
753     }
754 
755     /**
756      * Resets this encoder, clearing any charset-specific internal state.
757      *
758      * <p> The default implementation of this method does nothing.  This method
759      * should be overridden by encoders that maintain internal state.  </p>
760      */
implReset()761     protected void implReset() { }
762 
763     /**
764      * Encodes one or more characters into one or more bytes.
765      *
766      * <p> This method encapsulates the basic encoding loop, encoding as many
767      * characters as possible until it either runs out of input, runs out of room
768      * in the output buffer, or encounters an encoding error.  This method is
769      * invoked by the {@link #encode encode} method, which handles result
770      * interpretation and error recovery.
771      *
772      * <p> The buffers are read from, and written to, starting at their current
773      * positions.  At most {@link Buffer#remaining in.remaining()} characters
774      * will be read, and at most {@link Buffer#remaining out.remaining()}
775      * bytes will be written.  The buffers' positions will be advanced to
776      * reflect the characters read and the bytes written, but their marks and
777      * limits will not be modified.
778      *
779      * <p> This method returns a {@link CoderResult} object to describe its
780      * reason for termination, in the same manner as the {@link #encode encode}
781      * method.  Most implementations of this method will handle encoding errors
782      * by returning an appropriate result object for interpretation by the
783      * {@link #encode encode} method.  An optimized implementation may instead
784      * examine the relevant error action and implement that action itself.
785      *
786      * <p> An implementation of this method may perform arbitrary lookahead by
787      * returning {@link CoderResult#UNDERFLOW} until it receives sufficient
788      * input.  </p>
789      *
790      * @param  in
791      *         The input character buffer
792      *
793      * @param  out
794      *         The output byte buffer
795      *
796      * @return  A coder-result object describing the reason for termination
797      */
encodeLoop(CharBuffer in, ByteBuffer out)798     protected abstract CoderResult encodeLoop(CharBuffer in,
799                                               ByteBuffer out);
800 
801     // Android-changed: Document CoderMalfunctionError and NPE thrown for null input buffer.
802     /**
803      * Convenience method that encodes the remaining content of a single input
804      * character buffer into a newly-allocated byte buffer.
805      *
806      * <p> This method implements an entire <a href="#steps">encoding
807      * operation</a>; that is, it resets this encoder, then it encodes the
808      * characters in the given character buffer, and finally it flushes this
809      * encoder.  This method should therefore not be invoked if an encoding
810      * operation is already in progress.  </p>
811      *
812      * @param  in
813      *         The input character buffer
814      *
815      * @return A newly-allocated byte buffer containing the result of the
816      *         encoding operation.  The buffer's position will be zero and its
817      *         limit will follow the last byte written.
818      *
819      * @throws  IllegalStateException
820      *          If an encoding operation is already in progress
821      *
822      * @throws  MalformedInputException
823      *          If the character sequence starting at the input buffer's current
824      *          position is not a legal sixteen-bit Unicode sequence and the current malformed-input action
825      *          is {@link CodingErrorAction#REPORT}
826      *
827      * @throws  UnmappableCharacterException
828      *          If the character sequence starting at the input buffer's current
829      *          position cannot be mapped to an equivalent byte sequence and
830      *          the current unmappable-character action is {@link
831      *          CodingErrorAction#REPORT}
832      *
833      * @throws  CoderMalfunctionError
834      *          If an invocation of the encodeLoop method threw
835      *          an unexpected exception
836      *
837      * @throws  NullPointerException if input buffer is null
838      */
encode(CharBuffer in)839     public final ByteBuffer encode(CharBuffer in)
840         throws CharacterCodingException
841     {
842         int n = (int)(in.remaining() * averageBytesPerChar());
843         ByteBuffer out = ByteBuffer.allocate(n);
844 
845         if ((n == 0) && (in.remaining() == 0))
846             return out;
847         reset();
848         for (;;) {
849             CoderResult cr = in.hasRemaining() ?
850                 encode(in, out, true) : CoderResult.UNDERFLOW;
851             if (cr.isUnderflow())
852                 cr = flush(out);
853 
854             if (cr.isUnderflow())
855                 break;
856             if (cr.isOverflow()) {
857                 n = 2*n + 1;    // Ensure progress; n might be 0!
858                 ByteBuffer o = ByteBuffer.allocate(n);
859                 out.flip();
860                 o.put(out);
861                 out = o;
862                 continue;
863             }
864             cr.throwException();
865         }
866         out.flip();
867         return out;
868     }
869 
870 
871 
872 
873 
874 
875 
876 
877 
878 
879 
880 
881 
882 
883 
884 
885 
886 
887 
888 
889 
890 
891 
892 
893 
894 
895 
896 
897 
898 
899 
900 
901 
902 
903 
904 
905 
906 
907 
908 
909 
910 
911 
912 
913 
914 
915 
916 
917 
918 
919 
920 
921 
922 
923 
924 
925 
926 
927 
928 
929 
930 
931 
932 
933 
934 
935 
936 
937 
938 
939 
940 
941 
942 
943 
944 
945 
946 
947 
canEncode(CharBuffer cb)948     private boolean canEncode(CharBuffer cb) {
949         if (state == ST_FLUSHED)
950             reset();
951         else if (state != ST_RESET)
952             throwIllegalStateException(state, ST_CODING);
953 
954         // BEGIN Android-added: Fast path handling for empty buffers.
955         // Empty buffers can always be "encoded".
956         if (!cb.hasRemaining()) {
957             return true;
958         }
959         // END Android-added: Fast path handling for empty buffers.
960 
961         CodingErrorAction ma = malformedInputAction();
962         CodingErrorAction ua = unmappableCharacterAction();
963         try {
964             onMalformedInput(CodingErrorAction.REPORT);
965             onUnmappableCharacter(CodingErrorAction.REPORT);
966             encode(cb);
967         } catch (CharacterCodingException x) {
968             return false;
969         } finally {
970             onMalformedInput(ma);
971             onUnmappableCharacter(ua);
972             reset();
973         }
974         return true;
975     }
976 
977     /**
978      * Tells whether or not this encoder can encode the given character.
979      *
980      * <p> This method returns {@code false} if the given character is a
981      * surrogate character; such characters can be interpreted only when they
982      * are members of a pair consisting of a high surrogate followed by a low
983      * surrogate.  The {@link #canEncode(java.lang.CharSequence)
984      * canEncode(CharSequence)} method may be used to test whether or not a
985      * character sequence can be encoded.
986      *
987      * <p> This method may modify this encoder's state; it should therefore not
988      * be invoked if an <a href="#steps">encoding operation</a> is already in
989      * progress.
990      *
991      * <p> The default implementation of this method is not very efficient; it
992      * should generally be overridden to improve performance.  </p>
993      *
994      * @param   c
995      *          The given character
996      *
997      * @return  {@code true} if, and only if, this encoder can encode
998      *          the given character
999      *
1000      * @throws  IllegalStateException
1001      *          If an encoding operation is already in progress
1002      */
canEncode(char c)1003     public boolean canEncode(char c) {
1004         CharBuffer cb = CharBuffer.allocate(1);
1005         cb.put(c);
1006         cb.flip();
1007         return canEncode(cb);
1008     }
1009 
1010     /**
1011      * Tells whether or not this encoder can encode the given character
1012      * sequence.
1013      *
1014      * <p> If this method returns {@code false} for a particular character
1015      * sequence then more information about why the sequence cannot be encoded
1016      * may be obtained by performing a full <a href="#steps">encoding
1017      * operation</a>.
1018      *
1019      * <p> This method may modify this encoder's state; it should therefore not
1020      * be invoked if an encoding operation is already in progress.
1021      *
1022      * <p> The default implementation of this method is not very efficient; it
1023      * should generally be overridden to improve performance.  </p>
1024      *
1025      * @param   cs
1026      *          The given character sequence
1027      *
1028      * @return  {@code true} if, and only if, this encoder can encode
1029      *          the given character without throwing any exceptions and without
1030      *          performing any replacements
1031      *
1032      * @throws  IllegalStateException
1033      *          If an encoding operation is already in progress
1034      */
canEncode(CharSequence cs)1035     public boolean canEncode(CharSequence cs) {
1036         CharBuffer cb;
1037         if (cs instanceof CharBuffer)
1038             cb = ((CharBuffer)cs).duplicate();
1039         else
1040             // Android-removed: An unnecessary call to toString().
1041             // cb = CharBuffer.wrap(cs.toString());
1042             cb = CharBuffer.wrap(cs);
1043 
1044         return canEncode(cb);
1045     }
1046 
1047 
1048 
1049 
throwIllegalStateException(int from, int to)1050     private void throwIllegalStateException(int from, int to) {
1051         throw new IllegalStateException("Current state = " + stateNames[from]
1052                                         + ", new state = " + stateNames[to]);
1053     }
1054 
1055 }
1056