1 /*
   2  * Copyright (c) 2001, 2018, 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 package java.nio.charset;
  27 
  28 import java.lang.ref.WeakReference;
  29 import java.nio.*;
  30 import java.util.concurrent.ConcurrentHashMap;
  31 import java.util.Map;
  32 
  33 /**
  34  * A description of the result state of a coder.
  35  *
  36  * <p> A charset coder, that is, either a decoder or an encoder, consumes bytes
  37  * (or characters) from an input buffer, translates them, and writes the
  38  * resulting characters (or bytes) to an output buffer.  A coding process
  39  * terminates for one of four categories of reasons, which are described by
  40  * instances of this class:
  41  *
  42  * <ul>
  43  *
  44  *   <li><p> <i>Underflow</i> is reported when there is no more input to be
  45  *   processed, or there is insufficient input and additional input is
  46  *   required.  This condition is represented by the unique result object
  47  *   {@link #UNDERFLOW}, whose {@link #isUnderflow() isUnderflow} method
  48  *   returns {@code true}.  </p></li>
  49  *
  50  *   <li><p> <i>Overflow</i> is reported when there is insufficient room
  51  *   remaining in the output buffer.  This condition is represented by the
  52  *   unique result object {@link #OVERFLOW}, whose {@link #isOverflow()
  53  *   isOverflow} method returns {@code true}.  </p></li>
  54  *
  55  *   <li><p> A <i>malformed-input error</i> is reported when a sequence of
  56  *   input units is not well-formed.  Such errors are described by instances of
  57  *   this class whose {@link #isMalformed() isMalformed} method returns
  58  *   {@code true} and whose {@link #length() length} method returns the length
  59  *   of the malformed sequence.  There is one unique instance of this class for
  60  *   all malformed-input errors of a given length.  </p></li>
  61  *
  62  *   <li><p> An <i>unmappable-character error</i> is reported when a sequence
  63  *   of input units denotes a character that cannot be represented in the
  64  *   output charset.  Such errors are described by instances of this class
  65  *   whose {@link #isUnmappable() isUnmappable} method returns {@code true} and
  66  *   whose {@link #length() length} method returns the length of the input
  67  *   sequence denoting the unmappable character.  There is one unique instance
  68  *   of this class for all unmappable-character errors of a given length.
  69  *   </p></li>
  70  *
  71  * </ul>
  72  *
  73  * <p> For convenience, the {@link #isError() isError} method returns {@code true}
  74  * for result objects that describe malformed-input and unmappable-character
  75  * errors but {@code false} for those that describe underflow or overflow
  76  * conditions.  </p>
  77  *
  78  *
  79  * @author Mark Reinhold
  80  * @author JSR-51 Expert Group
  81  * @since 1.4
  82  */
  83 
  84 public class CoderResult {
  85 
  86     private static final int CR_UNDERFLOW  = 0;
  87     private static final int CR_OVERFLOW   = 1;
  88     private static final int CR_ERROR_MIN  = 2;
  89     private static final int CR_MALFORMED  = 2;
  90     private static final int CR_UNMAPPABLE = 3;
  91 
  92     private static final String[] names
  93         = { "UNDERFLOW", "OVERFLOW", "MALFORMED", "UNMAPPABLE" };
  94 
  95     private final int type;
  96     private final int length;
  97 
  98     private CoderResult(int type, int length) {
  99         this.type = type;
 100         this.length = length;
 101     }
 102 
 103     /**
 104      * Returns a string describing this coder result.
 105      *
 106      * @return  A descriptive string
 107      */
 108     public String toString() {
 109         String nm = names[type];
 110         return isError() ? nm + "[" + length + "]" : nm;
 111     }
 112 
 113     /**
 114      * Tells whether or not this object describes an underflow condition.
 115      *
 116      * @return  {@code true} if, and only if, this object denotes underflow
 117      */
 118     public boolean isUnderflow() {
 119         return (type == CR_UNDERFLOW);
 120     }
 121 
 122     /**
 123      * Tells whether or not this object describes an overflow condition.
 124      *
 125      * @return  {@code true} if, and only if, this object denotes overflow
 126      */
 127     public boolean isOverflow() {
 128         return (type == CR_OVERFLOW);
 129     }
 130 
 131     /**
 132      * Tells whether or not this object describes an error condition.
 133      *
 134      * @return  {@code true} if, and only if, this object denotes either a
 135      *          malformed-input error or an unmappable-character error
 136      */
 137     public boolean isError() {
 138         return (type >= CR_ERROR_MIN);
 139     }
 140 
 141     /**
 142      * Tells whether or not this object describes a malformed-input error.
 143      *
 144      * @return  {@code true} if, and only if, this object denotes a
 145      *          malformed-input error
 146      */
 147     public boolean isMalformed() {
 148         return (type == CR_MALFORMED);
 149     }
 150 
 151     /**
 152      * Tells whether or not this object describes an unmappable-character
 153      * error.
 154      *
 155      * @return  {@code true} if, and only if, this object denotes an
 156      *          unmappable-character error
 157      */
 158     public boolean isUnmappable() {
 159         return (type == CR_UNMAPPABLE);
 160     }
 161 
 162     /**
 163      * Returns the length of the erroneous input described by this
 164      * object&nbsp;&nbsp;<i>(optional operation)</i>.
 165      *
 166      * @return  The length of the erroneous input, a positive integer
 167      *
 168      * @throws  UnsupportedOperationException
 169      *          If this object does not describe an error condition, that is,
 170      *          if the {@link #isError() isError} does not return {@code true}
 171      */
 172     public int length() {
 173         if (!isError())
 174             throw new UnsupportedOperationException();
 175         return length;
 176     }
 177 
 178     /**
 179      * Result object indicating underflow, meaning that either the input buffer
 180      * has been completely consumed or, if the input buffer is not yet empty,
 181      * that additional input is required.
 182      */
 183     public static final CoderResult UNDERFLOW
 184         = new CoderResult(CR_UNDERFLOW, 0);
 185 
 186     /**
 187      * Result object indicating overflow, meaning that there is insufficient
 188      * room in the output buffer.
 189      */
 190     public static final CoderResult OVERFLOW
 191         = new CoderResult(CR_OVERFLOW, 0);
 192 
 193     private abstract static class Cache {
 194 
 195         private Map<Integer,WeakReference<CoderResult>> cache = null;
 196 
 197         protected abstract CoderResult create(int len);
 198 
 199         private CoderResult get(int len) {
 200             Integer k = len;
 201             WeakReference<CoderResult> w;
 202             CoderResult e = null;
 203             if (cache == null) {
 204                 cache = new ConcurrentHashMap<>();
 205             } else if ((w = cache.get(k)) != null) {
 206                 e = w.get();
 207             }
 208             if (e == null) {
 209                 e = create(len);
 210                 cache.put(k, new WeakReference<>(e));
 211             }
 212             return e;
 213         }
 214     }
 215 
 216     private static final Cache malformedCache
 217         = new Cache() {
 218                 public CoderResult create(int len) {
 219                     return new CoderResult(CR_MALFORMED, len);
 220                 }};
 221 
 222     private static final CoderResult[] malformed4 = new CoderResult[] {
 223         new CoderResult(CR_MALFORMED, 1),
 224         new CoderResult(CR_MALFORMED, 2),
 225         new CoderResult(CR_MALFORMED, 3),
 226         new CoderResult(CR_MALFORMED, 4),
 227     };
 228 
 229     /**
 230      * Static factory method that returns the unique object describing a
 231      * malformed-input error of the given length.
 232      *
 233      * @param   length
 234      *          The given length
 235      *
 236      * @return  The requested coder-result object
 237      */
 238     public static CoderResult malformedForLength(int length) {
 239         if (length <= 0)
 240             throw new IllegalArgumentException("Non-positive length");
 241         if (length <= 4)
 242             return malformed4[length - 1];
 243         return malformedCache.get(length);
 244     }
 245 
 246     private static final Cache unmappableCache
 247         = new Cache() {
 248                 public CoderResult create(int len) {
 249                     return new CoderResult(CR_UNMAPPABLE, len);
 250                 }};
 251 
 252     private static final CoderResult[] unmappable4 = new CoderResult[] {
 253         new CoderResult(CR_UNMAPPABLE, 1),
 254         new CoderResult(CR_UNMAPPABLE, 2),
 255         new CoderResult(CR_UNMAPPABLE, 3),
 256         new CoderResult(CR_UNMAPPABLE, 4),
 257     };
 258 
 259     /**
 260      * Static factory method that returns the unique result object describing
 261      * an unmappable-character error of the given length.
 262      *
 263      * @param   length
 264      *          The given length
 265      *
 266      * @return  The requested coder-result object
 267      */
 268     public static CoderResult unmappableForLength(int length) {
 269         if (length <= 0)
 270             throw new IllegalArgumentException("Non-positive length");
 271         if (length <= 4)
 272             return unmappable4[length - 1];
 273         return unmappableCache.get(length);
 274     }
 275 
 276     /**
 277      * Throws an exception appropriate to the result described by this object.
 278      *
 279      * @throws  BufferUnderflowException
 280      *          If this object is {@link #UNDERFLOW}
 281      *
 282      * @throws  BufferOverflowException
 283      *          If this object is {@link #OVERFLOW}
 284      *
 285      * @throws  MalformedInputException
 286      *          If this object represents a malformed-input error; the
 287      *          exception's length value will be that of this object
 288      *
 289      * @throws  UnmappableCharacterException
 290      *          If this object represents an unmappable-character error; the
 291      *          exceptions length value will be that of this object
 292      */
 293     public void throwException()
 294         throws CharacterCodingException
 295     {
 296         switch (type) {
 297         case CR_UNDERFLOW:   throw new BufferUnderflowException();
 298         case CR_OVERFLOW:    throw new BufferOverflowException();
 299         case CR_MALFORMED:   throw new MalformedInputException(length);
 300         case CR_UNMAPPABLE:  throw new UnmappableCharacterException(length);
 301         default:
 302             assert false;
 303         }
 304     }
 305 
 306 }