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