1 /*
   2  * Copyright (c) 2018, 2019, 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 package java.text;
  26 
  27 import java.io.IOException;
  28 import java.io.InvalidObjectException;
  29 import java.io.ObjectInputStream;
  30 import java.math.BigDecimal;
  31 import java.math.BigInteger;
  32 import java.math.RoundingMode;
  33 import java.util.ArrayList;
  34 import java.util.Arrays;
  35 import java.util.List;
  36 import java.util.Locale;
  37 import java.util.Objects;
  38 import java.util.concurrent.atomic.AtomicInteger;
  39 import java.util.concurrent.atomic.AtomicLong;
  40 
  41 
  42 /**
  43  * <p>
  44  * {@code CompactNumberFormat} is a concrete subclass of {@code NumberFormat}
  45  * that formats a decimal number in its compact form.
  46  *
  47  * The compact number formatting is designed for the environment where the space
  48  * is limited, and the formatted string can be displayed in that limited space.
  49  * It is defined by LDML's specification for
  50  * <a href = "http://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats">
  51  * Compact Number Formats</a>. A compact number formatting refers
  52  * to the representation of a number in a shorter form, based on the patterns
  53  * provided for a given locale.
  54  *
  55  * <p>
  56  * For example:
  57  * <br>In the {@link java.util.Locale#US US locale}, {@code 1000} can be formatted
  58  * as {@code "1K"}, and {@code 1000000} as {@code "1M"}, depending upon the
  59  * <a href = "#compact_number_style" >style</a> used.
  60  * <br>In the {@code "hi_IN"} locale, {@code 1000} can be formatted as
  61  * "1 \u0939\u091C\u093C\u093E\u0930", and {@code 50000000} as "5 \u0915.",
  62  * depending upon the <a href = "#compact_number_style" >style</a> used.
  63  *
  64  * <p>
  65  * To obtain a {@code CompactNumberFormat} for a locale, use one
  66  * of the factory methods given by {@code NumberFormat} for compact number
  67  * formatting. For example,
  68  * {@link NumberFormat#getCompactNumberInstance(Locale, Style)}.
  69  *
  70  * <blockquote><pre>
  71  * NumberFormat fmt = NumberFormat.getCompactNumberInstance(
  72  *                             new Locale("hi", "IN"), NumberFormat.Style.SHORT);
  73  * String result = fmt.format(1000);
  74  * </pre></blockquote>
  75  *
  76  * <h3><a id="compact_number_style">Style</a></h3>
  77  * <p>
  78  * A number can be formatted in the compact forms with two different
  79  * styles, {@link NumberFormat.Style#SHORT SHORT}
  80  * and {@link NumberFormat.Style#LONG LONG}. Use
  81  * {@link NumberFormat#getCompactNumberInstance(Locale, Style)} for formatting and
  82  * parsing a number in {@link NumberFormat.Style#SHORT SHORT} or
  83  * {@link NumberFormat.Style#LONG LONG} compact form,
  84  * where the given {@code Style} parameter requests the desired
  85  * format. A {@link NumberFormat.Style#SHORT SHORT} style
  86  * compact number instance in the {@link java.util.Locale#US US locale} formats
  87  * {@code 10000} as {@code "10K"}. However, a
  88  * {@link NumberFormat.Style#LONG LONG} style instance in same locale
  89  * formats {@code 10000} as {@code "10 thousand"}.
  90  *
  91  * <h3><a id="compact_number_patterns">Compact Number Patterns</a></h3>
  92  * <p>
  93  * The compact number patterns are represented in a series of patterns where each
  94  * pattern is used to format a range of numbers. An example of
  95  * {@link NumberFormat.Style#SHORT SHORT} styled compact number patterns
  96  * for the {@link java.util.Locale#US US locale} is {@code {"", "", "", "0K",
  97  * "00K", "000K", "0M", "00M", "000M", "0B", "00B", "000B", "0T", "00T", "000T"}},
  98  * ranging from {@code 10}<sup>{@code 0}</sup> to {@code 10}<sup>{@code 14}</sup>.
  99  * There can be any number of patterns and they are
 100  * strictly index based starting from the range {@code 10}<sup>{@code 0}</sup>.
 101  * For example, in the above patterns, pattern at index 3
 102  * ({@code "0K"}) is used for formatting {@code number >= 1000 and number < 10000},
 103  * pattern at index 4 ({@code "00K"}) is used for formatting
 104  * {@code number >= 10000 and number < 100000} and so on. In most of the locales,
 105  * patterns with the range
 106  * {@code 10}<sup>{@code 0}</sup>-{@code 10}<sup>{@code 2}</sup> are empty
 107  * strings, which implicitly means a special pattern {@code "0"}.
 108  * A special pattern {@code "0"} is used for any range which does not contain
 109  * a compact pattern. This special pattern can appear explicitly for any specific
 110  * range, or considered as a default pattern for an empty string.
 111  * <p>
 112  * A compact pattern has the following syntax:
 113  * <blockquote><pre>
 114  * <i>Pattern:</i>
 115  *         <i>PositivePattern</i>
 116  *         <i>PositivePattern</i> <i>[; NegativePattern]<sub>optional</sub></i>
 117  * <i>PositivePattern:</i>
 118  *         <i>Prefix<sub>optional</sub></i> <i>MinimumInteger</i> <i>Suffix<sub>optional</sub></i>
 119  * <i>NegativePattern:</i>
 120  *        <i>Prefix<sub>optional</sub></i> <i>MinimumInteger</i> <i>Suffix<sub>optional</sub></i>
 121  * <i>Prefix:</i>
 122  *      Any Unicode characters except \uFFFE, \uFFFF, and
 123  *      <a href = "DecimalFormat.html#special_pattern_character">special characters</a>
 124  * <i>Suffix:</i>
 125  *      Any Unicode characters except \uFFFE, \uFFFF, and
 126  *      <a href = "DecimalFormat.html#special_pattern_character">special characters</a>
 127  * <i>MinimumInteger:</i>
 128  *      0
 129  *      0 <i>MinimumInteger</i>
 130  * </pre></blockquote>
 131  *
 132  * A compact pattern contains a positive and negative subpattern
 133  * separated by a subpattern boundary character {@code ';' (U+003B)},
 134  * for example, {@code "0K;-0K"}. Each subpattern has a prefix,
 135  * minimum integer digits, and suffix. The negative subpattern
 136  * is optional, if absent, then the positive subpattern prefixed with the
 137  * minus sign ({@code '-' U+002D HYPHEN-MINUS}) is used as the negative
 138  * subpattern. That is, {@code "0K"} alone is equivalent to {@code "0K;-0K"}.
 139  * If there is an explicit negative subpattern, it serves only to specify
 140  * the negative prefix and suffix. The number of minimum integer digits,
 141  * and other characteristics are all the same as the positive pattern.
 142  * That means that {@code "0K;-00K"} produces precisely the same behavior
 143  * as {@code "0K;-0K"}.
 144  *
 145  * <p>
 146  * Many characters in a compact pattern are taken literally, they are matched
 147  * during parsing and output unchanged during formatting.
 148  * <a href = "DecimalFormat.html#special_pattern_character">Special characters</a>,
 149  * on the other hand, stand for other characters, strings, or classes of
 150  * characters. They must be quoted, using single quote {@code ' (U+0027)}
 151  * unless noted otherwise, if they are to appear in the prefix or suffix
 152  * as literals. For example, 0\u0915'.'.
 153  *
 154  * <h3>Formatting</h3>
 155  * The default formatting behavior returns a formatted string with no fractional
 156  * digits, however users can use the {@link #setMinimumFractionDigits(int)}
 157  * method to include the fractional part.
 158  * The number {@code 1000.0} or {@code 1000} is formatted as {@code "1K"}
 159  * not {@code "1.00K"} (in the {@link java.util.Locale#US US locale}). For this
 160  * reason, the patterns provided for formatting contain only the minimum
 161  * integer digits, prefix and/or suffix, but no fractional part.
 162  * For example, patterns used are {@code {"", "", "", 0K, 00K, ...}}. If the pattern
 163  * selected for formatting a number is {@code "0"} (special pattern),
 164  * either explicit or defaulted, then the general number formatting provided by
 165  * {@link java.text.DecimalFormat DecimalFormat}
 166  * for the specified locale is used.
 167  *
 168  * <h3>Parsing</h3>
 169  * The default parsing behavior does not allow a grouping separator until
 170  * grouping used is set to {@code true} by using
 171  * {@link #setGroupingUsed(boolean)}. The parsing of the fractional part
 172  * depends on the {@link #isParseIntegerOnly()}. For example, if the
 173  * parse integer only is set to true, then the fractional part is skipped.
 174  *
 175  * <h3>Rounding</h3>
 176  * {@code CompactNumberFormat} provides rounding modes defined in
 177  * {@link java.math.RoundingMode} for formatting.  By default, it uses
 178  * {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}.
 179  *
 180  * @see CompactNumberFormat.Style
 181  * @see NumberFormat
 182  * @see DecimalFormat
 183  * @since 12
 184  */
 185 public final class CompactNumberFormat extends NumberFormat {
 186 
 187     private static final long serialVersionUID = 7128367218649234678L;
 188 
 189     /**
 190      * The patterns for compact form of numbers for this
 191      * {@code CompactNumberFormat}. A possible example is
 192      * {@code {"", "", "", "0K", "00K", "000K", "0M", "00M", "000M", "0B",
 193      * "00B", "000B", "0T", "00T", "000T"}} ranging from
 194      * {@code 10}<sup>{@code 0}</sup>-{@code 10}<sup>{@code 14}</sup>,
 195      * where each pattern is used to format a range of numbers.
 196      * For example, {@code "0K"} is used for formatting
 197      * {@code number >= 1000 and number < 10000}, {@code "00K"} is used for
 198      * formatting {@code number >= 10000 and number < 100000} and so on.
 199      * This field must not be {@code null}.
 200      *
 201      * @serial
 202      */
 203     private String[] compactPatterns;
 204 
 205     /**
 206      * List of positive prefix patterns of this formatter's
 207      * compact number patterns.
 208      */
 209     private transient List<String> positivePrefixPatterns;
 210 
 211     /**
 212      * List of negative prefix patterns of this formatter's
 213      * compact number patterns.
 214      */
 215     private transient List<String> negativePrefixPatterns;
 216 
 217     /**
 218      * List of positive suffix patterns of this formatter's
 219      * compact number patterns.
 220      */
 221     private transient List<String> positiveSuffixPatterns;
 222 
 223     /**
 224      * List of negative suffix patterns of this formatter's
 225      * compact number patterns.
 226      */
 227     private transient List<String> negativeSuffixPatterns;
 228 
 229     /**
 230      * List of divisors of this formatter's compact number patterns.
 231      * Divisor can be either Long or BigInteger (if the divisor value goes
 232      * beyond long boundary)
 233      */
 234     private transient List<Number> divisors;
 235 
 236     /**
 237      * The {@code DecimalFormatSymbols} object used by this format.
 238      * It contains the symbols used to format numbers. For example,
 239      * the grouping separator, decimal separator, and so on.
 240      * This field must not be {@code null}.
 241      *
 242      * @serial
 243      * @see DecimalFormatSymbols
 244      */
 245     private DecimalFormatSymbols symbols;
 246 
 247     /**
 248      * The decimal pattern which is used for formatting the numbers
 249      * matching special pattern "0". This field must not be {@code null}.
 250      *
 251      * @serial
 252      * @see DecimalFormat
 253      */
 254     private final String decimalPattern;
 255 
 256     /**
 257      * A {@code DecimalFormat} used by this format for getting corresponding
 258      * general number formatting behavior for compact numbers.
 259      *
 260      */
 261     private transient DecimalFormat decimalFormat;
 262 
 263     /**
 264      * A {@code DecimalFormat} used by this format for getting general number
 265      * formatting behavior for the numbers which can't be represented as compact
 266      * numbers. For example, number matching the special pattern "0" are
 267      * formatted through general number format pattern provided by
 268      * {@link java.text.DecimalFormat DecimalFormat}
 269      * for the specified locale.
 270      *
 271      */
 272     private transient DecimalFormat defaultDecimalFormat;
 273 
 274     /**
 275      * The number of digits between grouping separators in the integer portion
 276      * of a compact number. For the grouping to work while formatting, this
 277      * field needs to be greater than 0 with grouping used set as true.
 278      * This field must not be negative.
 279      *
 280      * @serial
 281      */
 282     private byte groupingSize = 0;
 283 
 284     /**
 285      * Returns whether the {@link #parse(String, ParsePosition)}
 286      * method returns {@code BigDecimal}.
 287      *
 288      * @serial
 289      */
 290     private boolean parseBigDecimal = false;
 291 
 292     /**
 293      * The {@code RoundingMode} used in this compact number format.
 294      * This field must not be {@code null}.
 295      *
 296      * @serial
 297      */
 298     private RoundingMode roundingMode = RoundingMode.HALF_EVEN;
 299 
 300     /**
 301      * Special pattern used for compact numbers
 302      */
 303     private static final String SPECIAL_PATTERN = "0";
 304 
 305     /**
 306      * Multiplier for compact pattern range. In
 307      * the list compact patterns each compact pattern
 308      * specify the range with the multiplication factor of 10
 309      * of its previous compact pattern range.
 310      * For example, 10^0, 10^1, 10^2, 10^3, 10^4...
 311      *
 312      */
 313     private static final int RANGE_MULTIPLIER = 10;
 314 
 315     /**
 316      * Creates a {@code CompactNumberFormat} using the given decimal pattern,
 317      * decimal format symbols and compact patterns.
 318      * To obtain the instance of {@code CompactNumberFormat} with the standard
 319      * compact patterns for a {@code Locale} and {@code Style},
 320      * it is recommended to use the factory methods given by
 321      * {@code NumberFormat} for compact number formatting. For example,
 322      * {@link NumberFormat#getCompactNumberInstance(Locale, Style)}.
 323      *
 324      * @param decimalPattern a decimal pattern for general number formatting
 325      * @param symbols the set of symbols to be used
 326      * @param compactPatterns an array of
 327      *        <a href = "CompactNumberFormat.html#compact_number_patterns">
 328      *        compact number patterns</a>
 329      * @throws NullPointerException if any of the given arguments is
 330      *                                 {@code null}
 331      * @throws IllegalArgumentException if the given {@code decimalPattern} or the
 332      *                     {@code compactPatterns} array contains an invalid pattern
 333      *                     or if a {@code null} appears in the array of compact
 334      *                     patterns
 335      * @see DecimalFormat#DecimalFormat(java.lang.String, DecimalFormatSymbols)
 336      * @see DecimalFormatSymbols
 337      */
 338     public CompactNumberFormat(String decimalPattern,
 339             DecimalFormatSymbols symbols, String[] compactPatterns) {
 340 
 341         Objects.requireNonNull(decimalPattern, "decimalPattern");
 342         Objects.requireNonNull(symbols, "symbols");
 343         Objects.requireNonNull(compactPatterns, "compactPatterns");
 344 
 345         this.symbols = symbols;
 346         // Instantiating the DecimalFormat with "0" pattern; this acts just as a
 347         // basic pattern; the properties (For example, prefix/suffix)
 348         // are later computed based on the compact number formatting process.
 349         decimalFormat = new DecimalFormat(SPECIAL_PATTERN, this.symbols);
 350 
 351         // Initializing the super class state with the decimalFormat values
 352         // to represent this CompactNumberFormat.
 353         // For setting the digits counts, use overridden setXXX methods of this
 354         // CompactNumberFormat, as it performs check with the max range allowed
 355         // for compact number formatting
 356         setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits());
 357         setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits());
 358         setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits());
 359         setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits());
 360 
 361         super.setGroupingUsed(decimalFormat.isGroupingUsed());
 362         super.setParseIntegerOnly(decimalFormat.isParseIntegerOnly());
 363 
 364         this.compactPatterns = compactPatterns;
 365 
 366         // DecimalFormat used for formatting numbers with special pattern "0".
 367         // Formatting is delegated to the DecimalFormat's number formatting
 368         // with no fraction digits
 369         this.decimalPattern = decimalPattern;
 370         defaultDecimalFormat = new DecimalFormat(this.decimalPattern,
 371                 this.symbols);
 372         defaultDecimalFormat.setMaximumFractionDigits(0);
 373         // Process compact patterns to extract the prefixes, suffixes and
 374         // divisors
 375         processCompactPatterns();
 376     }
 377 
 378     /**
 379      * Formats a number to produce a string representing its compact form.
 380      * The number can be of any subclass of {@link java.lang.Number}.
 381      * @param number     the number to format
 382      * @param toAppendTo the {@code StringBuffer} to which the formatted
 383      *                   text is to be appended
 384      * @param fieldPosition    keeps track on the position of the field within
 385      *                         the returned string. For example, for formatting
 386      *                         a number {@code 123456789} in the
 387      *                         {@link java.util.Locale#US US locale},
 388      *                         if the given {@code fieldPosition} is
 389      *                         {@link NumberFormat#INTEGER_FIELD}, the begin
 390      *                         index and end index of {@code fieldPosition}
 391      *                         will be set to 0 and 3, respectively for the
 392      *                         output string {@code 123M}. Similarly, positions
 393      *                         of the prefix and the suffix fields can be
 394      *                         obtained using {@link NumberFormat.Field#PREFIX}
 395      *                         and {@link NumberFormat.Field#SUFFIX} respectively.
 396      * @return           the {@code StringBuffer} passed in as {@code toAppendTo}
 397      * @throws           IllegalArgumentException if {@code number} is
 398      *                   {@code null} or not an instance of {@code Number}
 399      * @throws           NullPointerException if {@code toAppendTo} or
 400      *                   {@code fieldPosition} is {@code null}
 401      * @throws           ArithmeticException if rounding is needed with rounding
 402      *                   mode being set to {@code RoundingMode.UNNECESSARY}
 403      * @see              FieldPosition
 404      */
 405     @Override
 406     public final StringBuffer format(Object number,
 407             StringBuffer toAppendTo,
 408             FieldPosition fieldPosition) {
 409 
 410         if (number == null) {
 411             throw new IllegalArgumentException("Cannot format null as a number");
 412         }
 413 
 414         if (number instanceof Long || number instanceof Integer
 415                 || number instanceof Short || number instanceof Byte
 416                 || number instanceof AtomicInteger
 417                 || number instanceof AtomicLong
 418                 || (number instanceof BigInteger
 419                 && ((BigInteger) number).bitLength() < 64)) {
 420             return format(((Number) number).longValue(), toAppendTo,
 421                     fieldPosition);
 422         } else if (number instanceof BigDecimal) {
 423             return format((BigDecimal) number, toAppendTo, fieldPosition);
 424         } else if (number instanceof BigInteger) {
 425             return format((BigInteger) number, toAppendTo, fieldPosition);
 426         } else if (number instanceof Number) {
 427             return format(((Number) number).doubleValue(), toAppendTo, fieldPosition);
 428         } else {
 429             throw new IllegalArgumentException("Cannot format "
 430                     + number.getClass().getName() + " as a number");
 431         }
 432     }
 433 
 434     /**
 435      * Formats a double to produce a string representing its compact form.
 436      * @param number    the double number to format
 437      * @param result    where the text is to be appended
 438      * @param fieldPosition    keeps track on the position of the field within
 439      *                         the returned string. For example, to format
 440      *                         a number {@code 1234567.89} in the
 441      *                         {@link java.util.Locale#US US locale}
 442      *                         if the given {@code fieldPosition} is
 443      *                         {@link NumberFormat#INTEGER_FIELD}, the begin
 444      *                         index and end index of {@code fieldPosition}
 445      *                         will be set to 0 and 1, respectively for the
 446      *                         output string {@code 1M}. Similarly, positions
 447      *                         of the prefix and the suffix fields can be
 448      *                         obtained using {@link NumberFormat.Field#PREFIX}
 449      *                         and {@link NumberFormat.Field#SUFFIX} respectively.
 450      * @return    the {@code StringBuffer} passed in as {@code result}
 451      * @throws NullPointerException if {@code result} or
 452      *            {@code fieldPosition} is {@code null}
 453      * @throws ArithmeticException if rounding is needed with rounding
 454      *            mode being set to {@code RoundingMode.UNNECESSARY}
 455      * @see FieldPosition
 456      */
 457     @Override
 458     public StringBuffer format(double number, StringBuffer result,
 459             FieldPosition fieldPosition) {
 460 
 461         fieldPosition.setBeginIndex(0);
 462         fieldPosition.setEndIndex(0);
 463         return format(number, result, fieldPosition.getFieldDelegate());
 464     }
 465 
 466     private StringBuffer format(double number, StringBuffer result,
 467             FieldDelegate delegate) {
 468 
 469         boolean nanOrInfinity = decimalFormat.handleNaN(number, result, delegate);
 470         if (nanOrInfinity) {
 471             return result;
 472         }
 473 
 474         boolean isNegative = ((number < 0.0)
 475                 || (number == 0.0 && 1 / number < 0.0));
 476 
 477         nanOrInfinity = decimalFormat.handleInfinity(number, result, delegate, isNegative);
 478         if (nanOrInfinity) {
 479             return result;
 480         }
 481 
 482         // Round the double value with min fraction digits, the integer
 483         // part of the rounded value is used for matching the compact
 484         // number pattern
 485         // For example, if roundingMode is HALF_UP with min fraction
 486         // digits = 0, the number 999.6 should round up
 487         // to 1000 and outputs 1K/thousand in "en_US" locale
 488         DigitList dList = new DigitList();
 489         dList.setRoundingMode(getRoundingMode());
 490         number = isNegative ? -number : number;
 491         dList.set(isNegative, number, getMinimumFractionDigits());
 492 
 493         double roundedNumber = dList.getDouble();
 494         int compactDataIndex = selectCompactPattern((long) roundedNumber);
 495         if (compactDataIndex != -1) {
 496             String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex)
 497                     : positivePrefixPatterns.get(compactDataIndex);
 498             String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex)
 499                     : positiveSuffixPatterns.get(compactDataIndex);
 500 
 501             if (!prefix.isEmpty() || !suffix.isEmpty()) {
 502                 appendPrefix(result, prefix, delegate);
 503                 long divisor = (Long) divisors.get(compactDataIndex);
 504                 roundedNumber = roundedNumber / divisor;
 505                 decimalFormat.setDigitList(roundedNumber, isNegative, getMaximumFractionDigits());
 506                 decimalFormat.subformatNumber(result, delegate, isNegative,
 507                         false, getMaximumIntegerDigits(), getMinimumIntegerDigits(),
 508                         getMaximumFractionDigits(), getMinimumFractionDigits());
 509                 appendSuffix(result, suffix, delegate);
 510             } else {
 511                 defaultDecimalFormat.doubleSubformat(number, result, delegate, isNegative);
 512             }
 513         } else {
 514             defaultDecimalFormat.doubleSubformat(number, result, delegate, isNegative);
 515         }
 516         return result;
 517     }
 518 
 519     /**
 520      * Formats a long to produce a string representing its compact form.
 521      * @param number    the long number to format
 522      * @param result    where the text is to be appended
 523      * @param fieldPosition    keeps track on the position of the field within
 524      *                         the returned string. For example, to format
 525      *                         a number {@code 123456789} in the
 526      *                         {@link java.util.Locale#US US locale},
 527      *                         if the given {@code fieldPosition} is
 528      *                         {@link NumberFormat#INTEGER_FIELD}, the begin
 529      *                         index and end index of {@code fieldPosition}
 530      *                         will be set to 0 and 3, respectively for the
 531      *                         output string {@code 123M}. Similarly, positions
 532      *                         of the prefix and the suffix fields can be
 533      *                         obtained using {@link NumberFormat.Field#PREFIX}
 534      *                         and {@link NumberFormat.Field#SUFFIX} respectively.
 535      * @return       the {@code StringBuffer} passed in as {@code result}
 536      * @throws       NullPointerException if {@code result} or
 537      *               {@code fieldPosition} is {@code null}
 538      * @throws       ArithmeticException if rounding is needed with rounding
 539      *               mode being set to {@code RoundingMode.UNNECESSARY}
 540      * @see FieldPosition
 541      */
 542     @Override
 543     public StringBuffer format(long number, StringBuffer result,
 544             FieldPosition fieldPosition) {
 545 
 546         fieldPosition.setBeginIndex(0);
 547         fieldPosition.setEndIndex(0);
 548         return format(number, result, fieldPosition.getFieldDelegate());
 549     }
 550 
 551     private StringBuffer format(long number, StringBuffer result, FieldDelegate delegate) {
 552         boolean isNegative = (number < 0);
 553         if (isNegative) {
 554             number = -number;
 555         }
 556 
 557         if (number < 0) { // LONG_MIN
 558             BigInteger bigIntegerValue = BigInteger.valueOf(number);
 559             return format(bigIntegerValue, result, delegate, true);
 560         }
 561 
 562         int compactDataIndex = selectCompactPattern(number);
 563         if (compactDataIndex != -1) {
 564             String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex)
 565                     : positivePrefixPatterns.get(compactDataIndex);
 566             String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex)
 567                     : positiveSuffixPatterns.get(compactDataIndex);
 568             if (!prefix.isEmpty() || !suffix.isEmpty()) {
 569                 appendPrefix(result, prefix, delegate);
 570                 long divisor = (Long) divisors.get(compactDataIndex);
 571                 if ((number % divisor == 0)) {
 572                     number = number / divisor;
 573                     decimalFormat.setDigitList(number, isNegative, 0);
 574                     decimalFormat.subformatNumber(result, delegate,
 575                             isNegative, true, getMaximumIntegerDigits(),
 576                             getMinimumIntegerDigits(), getMaximumFractionDigits(),
 577                             getMinimumFractionDigits());
 578                 } else {
 579                     // To avoid truncation of fractional part store
 580                     // the value in double and follow double path instead of
 581                     // long path
 582                     double dNumber = (double) number / divisor;
 583                     decimalFormat.setDigitList(dNumber, isNegative, getMaximumFractionDigits());
 584                     decimalFormat.subformatNumber(result, delegate,
 585                             isNegative, false, getMaximumIntegerDigits(),
 586                             getMinimumIntegerDigits(), getMaximumFractionDigits(),
 587                             getMinimumFractionDigits());
 588                 }
 589                 appendSuffix(result, suffix, delegate);
 590             } else {
 591                 number = isNegative ? -number : number;
 592                 defaultDecimalFormat.format(number, result, delegate);
 593             }
 594         } else {
 595             number = isNegative ? -number : number;
 596             defaultDecimalFormat.format(number, result, delegate);
 597         }
 598         return result;
 599     }
 600 
 601     /**
 602      * Formats a BigDecimal to produce a string representing its compact form.
 603      * @param number    the BigDecimal number to format
 604      * @param result    where the text is to be appended
 605      * @param fieldPosition    keeps track on the position of the field within
 606      *                         the returned string. For example, to format
 607      *                         a number {@code 1234567.89} in the
 608      *                         {@link java.util.Locale#US US locale},
 609      *                         if the given {@code fieldPosition} is
 610      *                         {@link NumberFormat#INTEGER_FIELD}, the begin
 611      *                         index and end index of {@code fieldPosition}
 612      *                         will be set to 0 and 1, respectively for the
 613      *                         output string {@code 1M}. Similarly, positions
 614      *                         of the prefix and the suffix fields can be
 615      *                         obtained using {@link NumberFormat.Field#PREFIX}
 616      *                         and {@link NumberFormat.Field#SUFFIX} respectively.
 617      * @return        the {@code StringBuffer} passed in as {@code result}
 618      * @throws        ArithmeticException if rounding is needed with rounding
 619      *                mode being set to {@code RoundingMode.UNNECESSARY}
 620      * @throws        NullPointerException if any of the given parameter
 621      *                is {@code null}
 622      * @see FieldPosition
 623      */
 624     private StringBuffer format(BigDecimal number, StringBuffer result,
 625             FieldPosition fieldPosition) {
 626 
 627         Objects.requireNonNull(number);
 628         fieldPosition.setBeginIndex(0);
 629         fieldPosition.setEndIndex(0);
 630         return format(number, result, fieldPosition.getFieldDelegate());
 631     }
 632 
 633     private StringBuffer format(BigDecimal number, StringBuffer result,
 634             FieldDelegate delegate) {
 635 
 636         boolean isNegative = number.signum() == -1;
 637         if (isNegative) {
 638             number = number.negate();
 639         }
 640 
 641         // Round the value with min fraction digits, the integer
 642         // part of the rounded value is used for matching the compact
 643         // number pattern
 644         // For example, If roundingMode is HALF_UP with min fraction digits = 0,
 645         // the number 999.6 should round up
 646         // to 1000 and outputs 1K/thousand in "en_US" locale
 647         number = number.setScale(getMinimumFractionDigits(), getRoundingMode());
 648 
 649         int compactDataIndex;
 650         if (number.toBigInteger().bitLength() < 64) {
 651             compactDataIndex = selectCompactPattern(number.toBigInteger().longValue());
 652         } else {
 653             compactDataIndex = selectCompactPattern(number.toBigInteger());
 654         }
 655 
 656         if (compactDataIndex != -1) {
 657             String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex)
 658                     : positivePrefixPatterns.get(compactDataIndex);
 659             String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex)
 660                     : positiveSuffixPatterns.get(compactDataIndex);
 661             if (!prefix.isEmpty() || !suffix.isEmpty()) {
 662                 appendPrefix(result, prefix, delegate);
 663                 Number divisor = divisors.get(compactDataIndex);
 664                 number = number.divide(new BigDecimal(divisor.toString()), getRoundingMode());
 665                 decimalFormat.setDigitList(number, isNegative, getMaximumFractionDigits());
 666                 decimalFormat.subformatNumber(result, delegate, isNegative,
 667                         false, getMaximumIntegerDigits(), getMinimumIntegerDigits(),
 668                         getMaximumFractionDigits(), getMinimumFractionDigits());
 669                 appendSuffix(result, suffix, delegate);
 670             } else {
 671                 number = isNegative ? number.negate() : number;
 672                 defaultDecimalFormat.format(number, result, delegate);
 673             }
 674         } else {
 675             number = isNegative ? number.negate() : number;
 676             defaultDecimalFormat.format(number, result, delegate);
 677         }
 678         return result;
 679     }
 680 
 681     /**
 682      * Formats a BigInteger to produce a string representing its compact form.
 683      * @param number    the BigInteger number to format
 684      * @param result    where the text is to be appended
 685      * @param fieldPosition    keeps track on the position of the field within
 686      *                         the returned string. For example, to format
 687      *                         a number {@code 123456789} in the
 688      *                         {@link java.util.Locale#US US locale},
 689      *                         if the given {@code fieldPosition} is
 690      *                         {@link NumberFormat#INTEGER_FIELD}, the begin index
 691      *                         and end index of {@code fieldPosition} will be set
 692      *                         to 0 and 3, respectively for the output string
 693      *                         {@code 123M}. Similarly, positions of the
 694      *                         prefix and the suffix fields can be obtained
 695      *                         using {@link NumberFormat.Field#PREFIX} and
 696      *                         {@link NumberFormat.Field#SUFFIX} respectively.
 697      * @return        the {@code StringBuffer} passed in as {@code result}
 698      * @throws        ArithmeticException if rounding is needed with rounding
 699      *                mode being set to {@code RoundingMode.UNNECESSARY}
 700      * @throws        NullPointerException if any of the given parameter
 701      *                is {@code null}
 702      * @see FieldPosition
 703      */
 704     private StringBuffer format(BigInteger number, StringBuffer result,
 705             FieldPosition fieldPosition) {
 706 
 707         Objects.requireNonNull(number);
 708         fieldPosition.setBeginIndex(0);
 709         fieldPosition.setEndIndex(0);
 710         return format(number, result, fieldPosition.getFieldDelegate(), false);
 711     }
 712 
 713     private StringBuffer format(BigInteger number, StringBuffer result,
 714             FieldDelegate delegate, boolean formatLong) {
 715 
 716         boolean isNegative = number.signum() == -1;
 717         if (isNegative) {
 718             number = number.negate();
 719         }
 720 
 721         int compactDataIndex = selectCompactPattern(number);
 722         if (compactDataIndex != -1) {
 723             String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex)
 724                     : positivePrefixPatterns.get(compactDataIndex);
 725             String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex)
 726                     : positiveSuffixPatterns.get(compactDataIndex);
 727             if (!prefix.isEmpty() || !suffix.isEmpty()) {
 728                 appendPrefix(result, prefix, delegate);
 729                 Number divisor = divisors.get(compactDataIndex);
 730                 if (number.mod(new BigInteger(divisor.toString()))
 731                         .compareTo(BigInteger.ZERO) == 0) {
 732                     number = number.divide(new BigInteger(divisor.toString()));
 733 
 734                     decimalFormat.setDigitList(number, isNegative, 0);
 735                     decimalFormat.subformatNumber(result, delegate,
 736                             isNegative, true, getMaximumIntegerDigits(),
 737                             getMinimumIntegerDigits(), getMaximumFractionDigits(),
 738                             getMinimumFractionDigits());
 739                 } else {
 740                     // To avoid truncation of fractional part store the value in
 741                     // BigDecimal and follow BigDecimal path instead of
 742                     // BigInteger path
 743                     BigDecimal nDecimal = new BigDecimal(number)
 744                             .divide(new BigDecimal(divisor.toString()), getRoundingMode());
 745                     decimalFormat.setDigitList(nDecimal, isNegative, getMaximumFractionDigits());
 746                     decimalFormat.subformatNumber(result, delegate,
 747                             isNegative, false, getMaximumIntegerDigits(),
 748                             getMinimumIntegerDigits(), getMaximumFractionDigits(),
 749                             getMinimumFractionDigits());
 750                 }
 751                 appendSuffix(result, suffix, delegate);
 752             } else {
 753                 number = isNegative ? number.negate() : number;
 754                 defaultDecimalFormat.format(number, result, delegate, formatLong);
 755             }
 756         } else {
 757             number = isNegative ? number.negate() : number;
 758             defaultDecimalFormat.format(number, result, delegate, formatLong);
 759         }
 760         return result;
 761     }
 762 
 763     /**
 764      * Appends the {@code prefix} to the {@code result} and also set the
 765      * {@code NumberFormat.Field.SIGN} and {@code NumberFormat.Field.PREFIX}
 766      * field positions.
 767      * @param result the resulting string, where the pefix is to be appended
 768      * @param prefix prefix to append
 769      * @param delegate notified of the locations of
 770      *                 {@code NumberFormat.Field.SIGN} and
 771      *                 {@code NumberFormat.Field.PREFIX} fields
 772      */
 773     private void appendPrefix(StringBuffer result, String prefix,
 774             FieldDelegate delegate) {
 775         append(result, expandAffix(prefix), delegate,
 776                 getFieldPositions(prefix, NumberFormat.Field.PREFIX));
 777     }
 778 
 779     /**
 780      * Appends {@code suffix} to the {@code result} and also set the
 781      * {@code NumberFormat.Field.SIGN} and {@code NumberFormat.Field.SUFFIX}
 782      * field positions.
 783      * @param result the resulting string, where the suffix is to be appended
 784      * @param suffix suffix to append
 785      * @param delegate notified of the locations of
 786      *                 {@code NumberFormat.Field.SIGN} and
 787      *                 {@code NumberFormat.Field.SUFFIX} fields
 788      */
 789     private void appendSuffix(StringBuffer result, String suffix,
 790             FieldDelegate delegate) {
 791         append(result, expandAffix(suffix), delegate,
 792                 getFieldPositions(suffix, NumberFormat.Field.SUFFIX));
 793     }
 794 
 795     /**
 796      * Appends the {@code string} to the {@code result}.
 797      * {@code delegate} is notified of SIGN, PREFIX and/or SUFFIX
 798      * field positions.
 799      * @param result the resulting string, where the text is to be appended
 800      * @param string the text to append
 801      * @param delegate notified of the locations of sub fields
 802      * @param positions a list of {@code FieldPostion} in the given
 803      *                  string
 804      */
 805     private void append(StringBuffer result, String string,
 806             FieldDelegate delegate, List<FieldPosition> positions) {
 807         if (!string.isEmpty()) {
 808             int start = result.length();
 809             result.append(string);
 810             for (int counter = 0; counter < positions.size(); counter++) {
 811                 FieldPosition fp = positions.get(counter);
 812                 Format.Field attribute = fp.getFieldAttribute();
 813                 delegate.formatted(attribute, attribute,
 814                         start + fp.getBeginIndex(),
 815                         start + fp.getEndIndex(), result);
 816             }
 817         }
 818     }
 819 
 820     /**
 821      * Expands an affix {@code pattern} into a string of literals.
 822      * All characters in the pattern are literals unless prefixed by QUOTE.
 823      * The character prefixed by QUOTE is replaced with its respective
 824      * localized literal.
 825      * @param pattern a compact number pattern affix
 826      * @return an expanded affix
 827      */
 828     private String expandAffix(String pattern) {
 829         // Return if no quoted character exists
 830         if (pattern.indexOf(QUOTE) < 0) {
 831             return pattern;
 832         }
 833         StringBuilder sb = new StringBuilder();
 834         for (int index = 0; index < pattern.length();) {
 835             char ch = pattern.charAt(index++);
 836             if (ch == QUOTE) {
 837                 ch = pattern.charAt(index++);
 838                 if (ch == MINUS_SIGN) {
 839                     ch = symbols.getMinusSign();
 840                 }
 841             }
 842             sb.append(ch);
 843         }
 844         return sb.toString();
 845     }
 846 
 847     /**
 848      * Returns a list of {@code FieldPostion} in the given {@code pattern}.
 849      * @param pattern the pattern to be parsed for {@code FieldPosition}
 850      * @param field whether a PREFIX or SUFFIX field
 851      * @return a list of {@code FieldPostion}
 852      */
 853     private List<FieldPosition> getFieldPositions(String pattern, Field field) {
 854         List<FieldPosition> positions = new ArrayList<>();
 855         StringBuilder affix = new StringBuilder();
 856         int stringIndex = 0;
 857         for (int index = 0; index < pattern.length();) {
 858             char ch = pattern.charAt(index++);
 859             if (ch == QUOTE) {
 860                 ch = pattern.charAt(index++);
 861                 if (ch == MINUS_SIGN) {
 862                     ch = symbols.getMinusSign();
 863                     FieldPosition fp = new FieldPosition(NumberFormat.Field.SIGN);
 864                     fp.setBeginIndex(stringIndex);
 865                     fp.setEndIndex(stringIndex + 1);
 866                     positions.add(fp);
 867                 }
 868             }
 869             stringIndex++;
 870             affix.append(ch);
 871         }
 872         if (affix.length() != 0) {
 873             FieldPosition fp = new FieldPosition(field);
 874             fp.setBeginIndex(0);
 875             fp.setEndIndex(affix.length());
 876             positions.add(fp);
 877         }
 878         return positions;
 879     }
 880 
 881     /**
 882      * Select the index of the matched compact number pattern for
 883      * the given {@code long} {@code number}.
 884      *
 885      * @param number number to be formatted
 886      * @return index of matched compact pattern;
 887      *         -1 if no compact patterns specified
 888      */
 889     private int selectCompactPattern(long number) {
 890 
 891         if (compactPatterns.length == 0) {
 892             return -1;
 893         }
 894 
 895         // Minimum index can be "0", max index can be "size - 1"
 896         int dataIndex = number <= 1 ? 0 : (int) Math.log10(number);
 897         dataIndex = Math.min(dataIndex, compactPatterns.length - 1);
 898         return dataIndex;
 899     }
 900 
 901     /**
 902      * Select the index of the matched compact number
 903      * pattern for the given {@code BigInteger} {@code number}.
 904      *
 905      * @param number number to be formatted
 906      * @return index of matched compact pattern;
 907      *         -1 if no compact patterns specified
 908      */
 909     private int selectCompactPattern(BigInteger number) {
 910 
 911         int matchedIndex = -1;
 912         if (compactPatterns.length == 0) {
 913             return matchedIndex;
 914         }
 915 
 916         BigInteger currentValue = BigInteger.ONE;
 917 
 918         // For formatting a number, the greatest type less than
 919         // or equal to number is used
 920         for (int index = 0; index < compactPatterns.length; index++) {
 921             if (number.compareTo(currentValue) > 0) {
 922                 // Input number is greater than current type; try matching with
 923                 // the next
 924                 matchedIndex = index;
 925                 currentValue = currentValue.multiply(BigInteger.valueOf(RANGE_MULTIPLIER));
 926                 continue;
 927             }
 928             if (number.compareTo(currentValue) < 0) {
 929                 // Current type is greater than the input number;
 930                 // take the previous pattern
 931                 break;
 932             } else {
 933                 // Equal
 934                 matchedIndex = index;
 935                 break;
 936             }
 937         }
 938         return matchedIndex;
 939     }
 940 
 941     /**
 942      * Formats an Object producing an {@code AttributedCharacterIterator}.
 943      * The returned {@code AttributedCharacterIterator} can be used
 944      * to build the resulting string, as well as to determine information
 945      * about the resulting string.
 946      * <p>
 947      * Each attribute key of the {@code AttributedCharacterIterator} will
 948      * be of type {@code NumberFormat.Field}, with the attribute value
 949      * being the same as the attribute key. The prefix and the suffix
 950      * parts of the returned iterator (if present) are represented by
 951      * the attributes {@link NumberFormat.Field#PREFIX} and
 952      * {@link NumberFormat.Field#SUFFIX} respectively.
 953      *
 954      *
 955      * @throws NullPointerException if obj is null
 956      * @throws IllegalArgumentException when the Format cannot format the
 957      *         given object
 958      * @throws ArithmeticException if rounding is needed with rounding
 959      *         mode being set to {@code RoundingMode.UNNECESSARY}
 960      * @param obj The object to format
 961      * @return an {@code AttributedCharacterIterator} describing the
 962      *         formatted value
 963      */
 964     @Override
 965     public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
 966         CharacterIteratorFieldDelegate delegate
 967                 = new CharacterIteratorFieldDelegate();
 968         StringBuffer sb = new StringBuffer();
 969 
 970         if (obj instanceof Double || obj instanceof Float) {
 971             format(((Number) obj).doubleValue(), sb, delegate);
 972         } else if (obj instanceof Long || obj instanceof Integer
 973                 || obj instanceof Short || obj instanceof Byte
 974                 || obj instanceof AtomicInteger || obj instanceof AtomicLong) {
 975             format(((Number) obj).longValue(), sb, delegate);
 976         } else if (obj instanceof BigDecimal) {
 977             format((BigDecimal) obj, sb, delegate);
 978         } else if (obj instanceof BigInteger) {
 979             format((BigInteger) obj, sb, delegate, false);
 980         } else if (obj == null) {
 981             throw new NullPointerException(
 982                     "formatToCharacterIterator must be passed non-null object");
 983         } else {
 984             throw new IllegalArgumentException(
 985                     "Cannot format given Object as a Number");
 986         }
 987         return delegate.getIterator(sb.toString());
 988     }
 989 
 990     /**
 991      * Computes the divisor using minimum integer digits and
 992      * matched pattern index.
 993      * @param minIntDigits string of 0s in compact pattern
 994      * @param patternIndex index of matched compact pattern
 995      * @return divisor value for the number matching the compact
 996      *         pattern at given {@code patternIndex}
 997      */
 998     private Number computeDivisor(String minIntDigits, int patternIndex) {
 999         int count = minIntDigits.length() - 1;
1000         Number matchedValue;
1001         // The divisor value can go above long range, if the compact patterns
1002         // goes above index 18, divisor may need to be stored as BigInteger,
1003         // since long can't store numbers >= 10^19,
1004         if (patternIndex < 19) {
1005             matchedValue = (long) Math.pow(RANGE_MULTIPLIER, patternIndex);
1006         } else {
1007             matchedValue = BigInteger.valueOf(RANGE_MULTIPLIER).pow(patternIndex);
1008         }
1009         Number divisor = matchedValue;
1010         if (count != 0) {
1011             if (matchedValue instanceof BigInteger) {
1012                 BigInteger bigValue = (BigInteger) matchedValue;
1013                 if (bigValue.compareTo(BigInteger.valueOf((long) Math.pow(RANGE_MULTIPLIER, count))) < 0) {
1014                     throw new IllegalArgumentException("Invalid Pattern"
1015                             + " [" + compactPatterns[patternIndex]
1016                             + "]: min integer digits specified exceeds the limit"
1017                             + " for the index " + patternIndex);
1018                 }
1019                 divisor = bigValue.divide(BigInteger.valueOf((long) Math.pow(RANGE_MULTIPLIER, count)));
1020             } else {
1021                 long longValue = (long) matchedValue;
1022                 if (longValue < (long) Math.pow(RANGE_MULTIPLIER, count)) {
1023                     throw new IllegalArgumentException("Invalid Pattern"
1024                             + " [" + compactPatterns[patternIndex]
1025                             + "]: min integer digits specified exceeds the limit"
1026                             + " for the index " + patternIndex);
1027                 }
1028                 divisor = longValue / (long) Math.pow(RANGE_MULTIPLIER, count);
1029             }
1030         }
1031         return divisor;
1032     }
1033 
1034     /**
1035      * Process the series of compact patterns to compute the
1036      * series of prefixes, suffixes and their respective divisor
1037      * value.
1038      *
1039      */
1040     private void processCompactPatterns() {
1041         int size = compactPatterns.length;
1042         positivePrefixPatterns = new ArrayList<>(size);
1043         negativePrefixPatterns = new ArrayList<>(size);
1044         positiveSuffixPatterns = new ArrayList<>(size);
1045         negativeSuffixPatterns = new ArrayList<>(size);
1046         divisors = new ArrayList<>(size);
1047 
1048         for (int index = 0; index < size; index++) {
1049             applyPattern(compactPatterns[index], index);
1050         }
1051     }
1052 
1053     /**
1054      * Process a compact pattern at a specific {@code index}
1055      * @param pattern the compact pattern to be processed
1056      * @param index index in the array of compact patterns
1057      *
1058      */
1059     private void applyPattern(String pattern, int index) {
1060 
1061         if (pattern == null) {
1062             throw new IllegalArgumentException("A null compact pattern" +
1063                     " encountered at index: " + index);
1064         }
1065 
1066         int start = 0;
1067         boolean gotNegative = false;
1068 
1069         String positivePrefix = "";
1070         String positiveSuffix = "";
1071         String negativePrefix = "";
1072         String negativeSuffix = "";
1073         String zeros = "";
1074         for (int j = 1; j >= 0 && start < pattern.length(); --j) {
1075 
1076             StringBuffer prefix = new StringBuffer();
1077             StringBuffer suffix = new StringBuffer();
1078             boolean inQuote = false;
1079             // The phase ranges from 0 to 2.  Phase 0 is the prefix.  Phase 1 is
1080             // the section of the pattern with digits. Phase 2 is the suffix.
1081             // The separation of the characters into phases is
1082             // strictly enforced; if phase 1 characters are to appear in the
1083             // suffix, for example, they must be quoted.
1084             int phase = 0;
1085 
1086             // The affix is either the prefix or the suffix.
1087             StringBuffer affix = prefix;
1088 
1089             for (int pos = start; pos < pattern.length(); ++pos) {
1090                 char ch = pattern.charAt(pos);
1091                 switch (phase) {
1092                     case 0:
1093                     case 2:
1094                         // Process the prefix / suffix characters
1095                         if (inQuote) {
1096                             // A quote within quotes indicates either the closing
1097                             // quote or two quotes, which is a quote literal. That
1098                             // is, we have the second quote in 'do' or 'don''t'.
1099                             if (ch == QUOTE) {
1100                                 if ((pos + 1) < pattern.length()
1101                                         && pattern.charAt(pos + 1) == QUOTE) {
1102                                     ++pos;
1103                                     affix.append("''"); // 'don''t'
1104                                 } else {
1105                                     inQuote = false; // 'do'
1106                                 }
1107                                 continue;
1108                             }
1109                         } else {
1110                             // Process unquoted characters seen in prefix or suffix
1111                             // phase.
1112                             switch (ch) {
1113                                 case ZERO_DIGIT:
1114                                     phase = 1;
1115                                     --pos; // Reprocess this character
1116                                     continue;
1117                                 case QUOTE:
1118                                     // A quote outside quotes indicates either the
1119                                     // opening quote or two quotes, which is a quote
1120                                     // literal. That is, we have the first quote in 'do'
1121                                     // or o''clock.
1122                                     if ((pos + 1) < pattern.length()
1123                                             && pattern.charAt(pos + 1) == QUOTE) {
1124                                         ++pos;
1125                                         affix.append("''"); // o''clock
1126                                     } else {
1127                                         inQuote = true; // 'do'
1128                                     }
1129                                     continue;
1130                                 case SEPARATOR:
1131                                     // Don't allow separators before we see digit
1132                                     // characters of phase 1, and don't allow separators
1133                                     // in the second pattern (j == 0).
1134                                     if (phase == 0 || j == 0) {
1135                                         throw new IllegalArgumentException(
1136                                                 "Unquoted special character '"
1137                                                 + ch + "' in pattern \"" + pattern + "\"");
1138                                     }
1139                                     start = pos + 1;
1140                                     pos = pattern.length();
1141                                     continue;
1142                                 case MINUS_SIGN:
1143                                     affix.append("'-");
1144                                     continue;
1145                                 case DECIMAL_SEPARATOR:
1146                                 case GROUPING_SEPARATOR:
1147                                 case DIGIT:
1148                                 case PERCENT:
1149                                 case PER_MILLE:
1150                                 case CURRENCY_SIGN:
1151                                     throw new IllegalArgumentException(
1152                                             "Unquoted special character '" + ch
1153                                             + "' in pattern \"" + pattern + "\"");
1154                                 default:
1155                                     break;
1156                             }
1157                         }
1158                         // Note that if we are within quotes, or if this is an
1159                         // unquoted, non-special character, then we usually fall
1160                         // through to here.
1161                         affix.append(ch);
1162                         break;
1163 
1164                     case 1:
1165                         // The negative subpattern (j = 0) serves only to specify the
1166                         // negative prefix and suffix, so all the phase 1 characters,
1167                         // for example, digits, zeroDigit, groupingSeparator,
1168                         // decimalSeparator, exponent are ignored
1169                         if (j == 0) {
1170                             while (pos < pattern.length()) {
1171                                 char negPatternChar = pattern.charAt(pos);
1172                                 if (negPatternChar == ZERO_DIGIT) {
1173                                     ++pos;
1174                                 } else {
1175                                     // Not a phase 1 character, consider it as
1176                                     // suffix and parse it in phase 2
1177                                     --pos; //process it again in outer loop
1178                                     phase = 2;
1179                                     affix = suffix;
1180                                     break;
1181                                 }
1182                             }
1183                             continue;
1184                         }
1185                         // Consider only '0' as valid pattern char which can appear
1186                         // in number part, rest can be either suffix or prefix
1187                         if (ch == ZERO_DIGIT) {
1188                             zeros = zeros + "0";
1189                         } else {
1190                             phase = 2;
1191                             affix = suffix;
1192                             --pos;
1193                         }
1194                         break;
1195                 }
1196             }
1197 
1198             if (inQuote) {
1199                 throw new IllegalArgumentException("Invalid single quote"
1200                         + " in pattern \"" + pattern + "\"");
1201             }
1202 
1203             if (j == 1) {
1204                 positivePrefix = prefix.toString();
1205                 positiveSuffix = suffix.toString();
1206                 negativePrefix = positivePrefix;
1207                 negativeSuffix = positiveSuffix;
1208             } else {
1209                 negativePrefix = prefix.toString();
1210                 negativeSuffix = suffix.toString();
1211                 gotNegative = true;
1212             }
1213 
1214             // If there is no negative pattern, or if the negative pattern is
1215             // identical to the positive pattern, then prepend the minus sign to
1216             // the positive pattern to form the negative pattern.
1217             if (!gotNegative
1218                     || (negativePrefix.equals(positivePrefix)
1219                     && negativeSuffix.equals(positiveSuffix))) {
1220                 negativeSuffix = positiveSuffix;
1221                 negativePrefix = "'-" + positivePrefix;
1222             }
1223         }
1224 
1225         // If no 0s are specified in a non empty pattern, it is invalid
1226         if (!pattern.isEmpty() && zeros.isEmpty()) {
1227             throw new IllegalArgumentException("Invalid pattern"
1228                     + " [" + pattern + "]: all patterns must include digit"
1229                     + " placement 0s");
1230         }
1231 
1232         // Only if positive affix exists; else put empty strings
1233         if (!positivePrefix.isEmpty() || !positiveSuffix.isEmpty()) {
1234             positivePrefixPatterns.add(positivePrefix);
1235             negativePrefixPatterns.add(negativePrefix);
1236             positiveSuffixPatterns.add(positiveSuffix);
1237             negativeSuffixPatterns.add(negativeSuffix);
1238             divisors.add(computeDivisor(zeros, index));
1239         } else {
1240             positivePrefixPatterns.add("");
1241             negativePrefixPatterns.add("");
1242             positiveSuffixPatterns.add("");
1243             negativeSuffixPatterns.add("");
1244             divisors.add(1L);
1245         }
1246     }
1247 
1248     private final transient DigitList digitList = new DigitList();
1249     private static final int STATUS_INFINITE = 0;
1250     private static final int STATUS_POSITIVE = 1;
1251     private static final int STATUS_LENGTH   = 2;
1252 
1253     private static final char ZERO_DIGIT = '0';
1254     private static final char DIGIT = '#';
1255     private static final char DECIMAL_SEPARATOR = '.';
1256     private static final char GROUPING_SEPARATOR = ',';
1257     private static final char MINUS_SIGN = '-';
1258     private static final char PERCENT = '%';
1259     private static final char PER_MILLE = '\u2030';
1260     private static final char SEPARATOR = ';';
1261     private static final char CURRENCY_SIGN = '\u00A4';
1262     private static final char QUOTE = '\'';
1263 
1264     // Expanded form of positive/negative prefix/suffix,
1265     // the expanded form contains special characters in
1266     // its localized form, which are used for matching
1267     // while parsing a string to number
1268     private transient List<String> positivePrefixes;
1269     private transient List<String> negativePrefixes;
1270     private transient List<String> positiveSuffixes;
1271     private transient List<String> negativeSuffixes;
1272 
1273     private void expandAffixPatterns() {
1274         positivePrefixes = new ArrayList<>(compactPatterns.length);
1275         negativePrefixes = new ArrayList<>(compactPatterns.length);
1276         positiveSuffixes = new ArrayList<>(compactPatterns.length);
1277         negativeSuffixes = new ArrayList<>(compactPatterns.length);
1278         for (int index = 0; index < compactPatterns.length; index++) {
1279             positivePrefixes.add(expandAffix(positivePrefixPatterns.get(index)));
1280             negativePrefixes.add(expandAffix(negativePrefixPatterns.get(index)));
1281             positiveSuffixes.add(expandAffix(positiveSuffixPatterns.get(index)));
1282             negativeSuffixes.add(expandAffix(negativeSuffixPatterns.get(index)));
1283         }
1284     }
1285 
1286     /**
1287      * Parses a compact number from a string to produce a {@code Number}.
1288      * <p>
1289      * The method attempts to parse text starting at the index given by
1290      * {@code pos}.
1291      * If parsing succeeds, then the index of {@code pos} is updated
1292      * to the index after the last character used (parsing does not necessarily
1293      * use all characters up to the end of the string), and the parsed
1294      * number is returned. The updated {@code pos} can be used to
1295      * indicate the starting point for the next call to this method.
1296      * If an error occurs, then the index of {@code pos} is not
1297      * changed, the error index of {@code pos} is set to the index of
1298      * the character where the error occurred, and {@code null} is returned.
1299      * <p>
1300      * The value is the numeric part in the given text multiplied
1301      * by the numeric equivalent of the affix attached
1302      * (For example, "K" = 1000 in {@link java.util.Locale#US US locale}).
1303      * The subclass returned depends on the value of
1304      * {@link #isParseBigDecimal}.
1305      * <ul>
1306      * <li>If {@link #isParseBigDecimal()} is false (the default),
1307      *     most integer values are returned as {@code Long}
1308      *     objects, no matter how they are written: {@code "17K"} and
1309      *     {@code "17.000K"} both parse to {@code Long.valueOf(17000)}.
1310      *     If the value cannot fit into {@code Long}, then the result is
1311      *     returned as {@code Double}. This includes values with a
1312      *     fractional part, infinite values, {@code NaN},
1313      *     and the value -0.0.
1314      *     <p>
1315      *     Callers may use the {@code Number} methods {@code doubleValue},
1316      *     {@code longValue}, etc., to obtain the type they want.
1317      *
1318      * <li>If {@link #isParseBigDecimal()} is true, values are returned
1319      *     as {@code BigDecimal} objects. The special cases negative
1320      *     and positive infinity and NaN are returned as {@code Double}
1321      *     instances holding the values of the corresponding
1322      *     {@code Double} constants.
1323      * </ul>
1324      * <p>
1325      * {@code CompactNumberFormat} parses all Unicode characters that represent
1326      * decimal digits, as defined by {@code Character.digit()}. In
1327      * addition, {@code CompactNumberFormat} also recognizes as digits the ten
1328      * consecutive characters starting with the localized zero digit defined in
1329      * the {@code DecimalFormatSymbols} object.
1330      * <p>
1331      * {@code CompactNumberFormat} parse does not allow parsing scientific
1332      * notations. For example, parsing a string {@code "1.05E4K"} in
1333      * {@link java.util.Locale#US US locale} breaks at character 'E'
1334      * and returns 1.05.
1335      *
1336      * @param text the string to be parsed
1337      * @param pos  a {@code ParsePosition} object with index and error
1338      *             index information as described above
1339      * @return the parsed value, or {@code null} if the parse fails
1340      * @exception  NullPointerException if {@code text} or
1341      *             {@code pos} is null
1342      *
1343      */
1344     @Override
1345     public Number parse(String text, ParsePosition pos) {
1346 
1347         Objects.requireNonNull(text);
1348         Objects.requireNonNull(pos);
1349 
1350         // Lazily expanding the affix patterns, on the first parse
1351         // call on this instance
1352         // If not initialized, expand and load all affixes
1353         if (positivePrefixes == null) {
1354             expandAffixPatterns();
1355         }
1356 
1357         // The compact number multiplier for parsed string.
1358         // Its value is set on parsing prefix and suffix. For example,
1359         // in the {@link java.util.Locale#US US locale} parsing {@code "1K"}
1360         // sets its value to 1000, as K (thousand) is abbreviated form of 1000.
1361         Number cnfMultiplier = 1L;
1362 
1363         // Special case NaN
1364         if (text.regionMatches(pos.index, symbols.getNaN(),
1365                 0, symbols.getNaN().length())) {
1366             pos.index = pos.index + symbols.getNaN().length();
1367             return Double.NaN;
1368         }
1369 
1370         int position = pos.index;
1371         int oldStart = pos.index;
1372         boolean gotPositive = false;
1373         boolean gotNegative = false;
1374         int matchedPosIndex = -1;
1375         int matchedNegIndex = -1;
1376         String matchedPosPrefix = "";
1377         String matchedNegPrefix = "";
1378         String defaultPosPrefix = defaultDecimalFormat.getPositivePrefix();
1379         String defaultNegPrefix = defaultDecimalFormat.getNegativePrefix();
1380         // Prefix matching
1381         for (int compactIndex = 0; compactIndex < compactPatterns.length; compactIndex++) {
1382             String positivePrefix = positivePrefixes.get(compactIndex);
1383             String negativePrefix = negativePrefixes.get(compactIndex);
1384 
1385             // Do not break if a match occur; there is a possibility that the
1386             // subsequent affixes may match the longer subsequence in the given
1387             // string.
1388             // For example, matching "Mdx 3" with "M", "Md" as prefix should
1389             // match with "Md"
1390             boolean match = matchAffix(text, position, positivePrefix,
1391                     defaultPosPrefix, matchedPosPrefix);
1392             if (match) {
1393                 matchedPosIndex = compactIndex;
1394                 matchedPosPrefix = positivePrefix;
1395                 gotPositive = true;
1396             }
1397 
1398             match = matchAffix(text, position, negativePrefix,
1399                     defaultNegPrefix, matchedNegPrefix);
1400             if (match) {
1401                 matchedNegIndex = compactIndex;
1402                 matchedNegPrefix = negativePrefix;
1403                 gotNegative = true;
1404             }
1405         }
1406 
1407         // Given text does not match the non empty valid compact prefixes
1408         // check with the default prefixes
1409         if (!gotPositive && !gotNegative) {
1410             if (text.regionMatches(pos.index, defaultPosPrefix, 0,
1411                     defaultPosPrefix.length())) {
1412                 // Matches the default positive prefix
1413                 matchedPosPrefix = defaultPosPrefix;
1414                 gotPositive = true;
1415             }
1416             if (text.regionMatches(pos.index, defaultNegPrefix, 0,
1417                     defaultNegPrefix.length())) {
1418                 // Matches the default negative prefix
1419                 matchedNegPrefix = defaultNegPrefix;
1420                 gotNegative = true;
1421             }
1422         }
1423 
1424         // If both match, take the longest one
1425         if (gotPositive && gotNegative) {
1426             if (matchedPosPrefix.length() > matchedNegPrefix.length()) {
1427                 gotNegative = false;
1428             } else if (matchedPosPrefix.length() < matchedNegPrefix.length()) {
1429                 gotPositive = false;
1430             }
1431         }
1432 
1433         // Update the position and take compact multiplier
1434         // only if it matches the compact prefix, not the default
1435         // prefix; else multiplier should be 1
1436         if (gotPositive) {
1437             position += matchedPosPrefix.length();
1438             cnfMultiplier = matchedPosIndex != -1
1439                     ? divisors.get(matchedPosIndex) : 1L;
1440         } else if (gotNegative) {
1441             position += matchedNegPrefix.length();
1442             cnfMultiplier = matchedNegIndex != -1
1443                     ? divisors.get(matchedNegIndex) : 1L;
1444         }
1445 
1446         digitList.setRoundingMode(getRoundingMode());
1447         boolean[] status = new boolean[STATUS_LENGTH];
1448 
1449         // Call DecimalFormat.subparseNumber() method to parse the
1450         // number part of the input text
1451         position = decimalFormat.subparseNumber(text, position,
1452                 digitList, false, false, status);
1453 
1454         if (position == -1) {
1455             // Unable to parse the number successfully
1456             pos.index = oldStart;
1457             pos.errorIndex = oldStart;
1458             return null;
1459         }
1460 
1461         // If parse integer only is true and the parsing is broken at
1462         // decimal point, then pass/ignore all digits and move pointer
1463         // at the start of suffix, to process the suffix part
1464         if (isParseIntegerOnly()
1465                 && text.charAt(position) == symbols.getDecimalSeparator()) {
1466             position++; // Pass decimal character
1467             for (; position < text.length(); ++position) {
1468                 char ch = text.charAt(position);
1469                 int digit = ch - symbols.getZeroDigit();
1470                 if (digit < 0 || digit > 9) {
1471                     digit = Character.digit(ch, 10);
1472                     // Parse all digit characters
1473                     if (!(digit >= 0 && digit <= 9)) {
1474                         break;
1475                     }
1476                 }
1477             }
1478         }
1479 
1480         // Number parsed successfully; match prefix and
1481         // suffix to obtain multiplier
1482         pos.index = position;
1483         Number multiplier = computeParseMultiplier(text, pos,
1484                 gotPositive ? matchedPosPrefix : matchedNegPrefix,
1485                 status, gotPositive, gotNegative);
1486 
1487         if (multiplier.longValue() == -1L) {
1488             return null;
1489         } else if (multiplier.longValue() != 1L) {
1490             cnfMultiplier = multiplier;
1491         }
1492 
1493         // Special case INFINITY
1494         if (status[STATUS_INFINITE]) {
1495             if (status[STATUS_POSITIVE]) {
1496                 return Double.POSITIVE_INFINITY;
1497             } else {
1498                 return Double.NEGATIVE_INFINITY;
1499             }
1500         }
1501 
1502         if (isParseBigDecimal()) {
1503             BigDecimal bigDecimalResult = digitList.getBigDecimal();
1504 
1505             if (cnfMultiplier.longValue() != 1) {
1506                 bigDecimalResult = bigDecimalResult
1507                         .multiply(new BigDecimal(cnfMultiplier.toString()));
1508             }
1509             if (!status[STATUS_POSITIVE]) {
1510                 bigDecimalResult = bigDecimalResult.negate();
1511             }
1512             return bigDecimalResult;
1513         } else {
1514             Number cnfResult;
1515             if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly())) {
1516                 long longResult = digitList.getLong();
1517                 cnfResult = generateParseResult(longResult, false,
1518                         longResult < 0, status, cnfMultiplier);
1519             } else {
1520                 cnfResult = generateParseResult(digitList.getDouble(),
1521                         true, false, status, cnfMultiplier);
1522             }
1523             return cnfResult;
1524         }
1525     }
1526 
1527     /**
1528      * Returns the parsed result by multiplying the parsed number
1529      * with the multiplier representing the prefix and suffix.
1530      *
1531      * @param number parsed number component
1532      * @param gotDouble whether the parsed number contains decimal
1533      * @param gotLongMin whether the parsed number is Long.MIN
1534      * @param status boolean status flags indicating whether the
1535      *               value is infinite and whether it is positive
1536      * @param cnfMultiplier compact number multiplier
1537      * @return parsed result
1538      */
1539     private Number generateParseResult(Number number, boolean gotDouble,
1540             boolean gotLongMin, boolean[] status, Number cnfMultiplier) {
1541 
1542         if (gotDouble) {
1543             if (cnfMultiplier.longValue() != 1L) {
1544                 double doubleResult = number.doubleValue() * cnfMultiplier.doubleValue();
1545                 doubleResult = (double) convertIfNegative(doubleResult, status, gotLongMin);
1546                 // Check if a double can be represeneted as a long
1547                 long longResult = (long) doubleResult;
1548                 gotDouble = ((doubleResult != (double) longResult)
1549                         || (doubleResult == 0.0 && 1 / doubleResult < 0.0));
1550                 return gotDouble ? (Number) doubleResult : (Number) longResult;
1551             }
1552         } else {
1553             if (cnfMultiplier.longValue() != 1L) {
1554                 Number result;
1555                 if ((cnfMultiplier instanceof Long) && !gotLongMin) {
1556                     long longMultiplier = (long) cnfMultiplier;
1557                     try {
1558                         result = Math.multiplyExact(number.longValue(),
1559                                 longMultiplier);
1560                     } catch (ArithmeticException ex) {
1561                         // If number * longMultiplier can not be represented
1562                         // as long return as double
1563                         result = number.doubleValue() * cnfMultiplier.doubleValue();
1564                     }
1565                 } else {
1566                     // cnfMultiplier can not be stored into long or the number
1567                     // part is Long.MIN, return as double
1568                     result = number.doubleValue() * cnfMultiplier.doubleValue();
1569                 }
1570                 return convertIfNegative(result, status, gotLongMin);
1571             }
1572         }
1573 
1574         // Default number
1575         return convertIfNegative(number, status, gotLongMin);
1576     }
1577 
1578     /**
1579      * Negate the parsed value if the positive status flag is false
1580      * and the value is not a Long.MIN
1581      * @param number parsed value
1582      * @param status boolean status flags indicating whether the
1583      *               value is infinite and whether it is positive
1584      * @param gotLongMin whether the parsed number is Long.MIN
1585      * @return the resulting value
1586      */
1587     private Number convertIfNegative(Number number, boolean[] status,
1588             boolean gotLongMin) {
1589 
1590         if (!status[STATUS_POSITIVE] && !gotLongMin) {
1591             if (number instanceof Long) {
1592                 return -(long) number;
1593             } else {
1594                 return -(double) number;
1595             }
1596         } else {
1597             return number;
1598         }
1599     }
1600 
1601     /**
1602      * Attempts to match the given {@code affix} in the
1603      * specified {@code text}.
1604      */
1605     private boolean matchAffix(String text, int position, String affix,
1606             String defaultAffix, String matchedAffix) {
1607 
1608         // Check with the compact affixes which are non empty and
1609         // do not match with default affix
1610         if (!affix.isEmpty() && !affix.equals(defaultAffix)) {
1611             // Look ahead only for the longer match than the previous match
1612             if (matchedAffix.length() < affix.length()) {
1613                 if (text.regionMatches(position, affix, 0, affix.length())) {
1614                     return true;
1615                 }
1616             }
1617         }
1618         return false;
1619     }
1620 
1621     /**
1622      * Attempts to match given {@code prefix} and {@code suffix} in
1623      * the specified {@code text}.
1624      */
1625     private boolean matchPrefixAndSuffix(String text, int position, String prefix,
1626             String matchedPrefix, String defaultPrefix, String suffix,
1627             String matchedSuffix, String defaultSuffix) {
1628 
1629         // Check the compact pattern suffix only if there is a
1630         // compact prefix match or a default prefix match
1631         // because the compact prefix and suffix should match at the same
1632         // index to obtain the multiplier.
1633         // The prefix match is required because of the possibility of
1634         // same prefix at multiple index, in which case matching the suffix
1635         // is used to obtain the single match
1636 
1637         if (prefix.equals(matchedPrefix)
1638                 || matchedPrefix.equals(defaultPrefix)) {
1639             return matchAffix(text, position, suffix, defaultSuffix, matchedSuffix);
1640         }
1641         return false;
1642     }
1643 
1644     /**
1645      * Computes multiplier by matching the given {@code matchedPrefix}
1646      * and suffix in the specified {@code text} from the lists of
1647      * prefixes and suffixes extracted from compact patterns.
1648      *
1649      * @param text the string to parse
1650      * @param parsePosition the {@code ParsePosition} object representing the
1651      *                      index and error index of the parse string
1652      * @param matchedPrefix prefix extracted which needs to be matched to
1653      *                      obtain the multiplier
1654      * @param status upon return contains boolean status flags indicating
1655      *               whether the value is positive
1656      * @param gotPositive based on the prefix parsed; whether the number is positive
1657      * @param gotNegative based on the prefix parsed; whether the number is negative
1658      * @return the multiplier matching the prefix and suffix; -1 otherwise
1659      */
1660     private Number computeParseMultiplier(String text, ParsePosition parsePosition,
1661             String matchedPrefix, boolean[] status, boolean gotPositive,
1662             boolean gotNegative) {
1663 
1664         int position = parsePosition.index;
1665         boolean gotPos = false;
1666         boolean gotNeg = false;
1667         int matchedPosIndex = -1;
1668         int matchedNegIndex = -1;
1669         String matchedPosSuffix = "";
1670         String matchedNegSuffix = "";
1671         for (int compactIndex = 0; compactIndex < compactPatterns.length; compactIndex++) {
1672             String positivePrefix = positivePrefixes.get(compactIndex);
1673             String negativePrefix = negativePrefixes.get(compactIndex);
1674             String positiveSuffix = positiveSuffixes.get(compactIndex);
1675             String negativeSuffix = negativeSuffixes.get(compactIndex);
1676 
1677             // Do not break if a match occur; there is a possibility that the
1678             // subsequent affixes may match the longer subsequence in the given
1679             // string.
1680             // For example, matching "3Mdx" with "M", "Md" should match with "Md"
1681             boolean match = matchPrefixAndSuffix(text, position, positivePrefix, matchedPrefix,
1682                     defaultDecimalFormat.getPositivePrefix(), positiveSuffix,
1683                     matchedPosSuffix, defaultDecimalFormat.getPositiveSuffix());
1684             if (match) {
1685                 matchedPosIndex = compactIndex;
1686                 matchedPosSuffix = positiveSuffix;
1687                 gotPos = true;
1688             }
1689 
1690             match = matchPrefixAndSuffix(text, position, negativePrefix, matchedPrefix,
1691                     defaultDecimalFormat.getNegativePrefix(), negativeSuffix,
1692                     matchedNegSuffix, defaultDecimalFormat.getNegativeSuffix());
1693             if (match) {
1694                 matchedNegIndex = compactIndex;
1695                 matchedNegSuffix = negativeSuffix;
1696                 gotNeg = true;
1697             }
1698         }
1699 
1700         // Suffix in the given text does not match with the compact
1701         // patterns suffixes; match with the default suffix
1702         if (!gotPos && !gotNeg) {
1703             String positiveSuffix = defaultDecimalFormat.getPositiveSuffix();
1704             String negativeSuffix = defaultDecimalFormat.getNegativeSuffix();
1705             if (text.regionMatches(position, positiveSuffix, 0,
1706                     positiveSuffix.length())) {
1707                 // Matches the default positive prefix
1708                 matchedPosSuffix = positiveSuffix;
1709                 gotPos = true;
1710             }
1711             if (text.regionMatches(position, negativeSuffix, 0,
1712                     negativeSuffix.length())) {
1713                 // Matches the default negative suffix
1714                 matchedNegSuffix = negativeSuffix;
1715                 gotNeg = true;
1716             }
1717         }
1718 
1719         // If both matches, take the longest one
1720         if (gotPos && gotNeg) {
1721             if (matchedPosSuffix.length() > matchedNegSuffix.length()) {
1722                 gotNeg = false;
1723             } else if (matchedPosSuffix.length() < matchedNegSuffix.length()) {
1724                 gotPos = false;
1725             } else {
1726                 // If longest comparison fails; take the positive and negative
1727                 // sign of matching prefix
1728                 gotPos = gotPositive;
1729                 gotNeg = gotNegative;
1730             }
1731         }
1732 
1733         // Fail if neither or both
1734         if (gotPos == gotNeg) {
1735             parsePosition.errorIndex = position;
1736             return -1L;
1737         }
1738 
1739         Number cnfMultiplier;
1740         // Update the parse position index and take compact multiplier
1741         // only if it matches the compact suffix, not the default
1742         // suffix; else multiplier should be 1
1743         if (gotPos) {
1744             parsePosition.index = position + matchedPosSuffix.length();
1745             cnfMultiplier = matchedPosIndex != -1
1746                     ? divisors.get(matchedPosIndex) : 1L;
1747         } else {
1748             parsePosition.index = position + matchedNegSuffix.length();
1749             cnfMultiplier = matchedNegIndex != -1
1750                     ? divisors.get(matchedNegIndex) : 1L;
1751         }
1752         status[STATUS_POSITIVE] = gotPos;
1753         return cnfMultiplier;
1754     }
1755 
1756     /**
1757      * Reconstitutes this {@code CompactNumberFormat} from a stream
1758      * (that is, deserializes it) after performing some validations.
1759      * This method throws InvalidObjectException, if the stream data is invalid
1760      * because of the following reasons,
1761      * <ul>
1762      * <li> If any of the {@code decimalPattern}, {@code compactPatterns},
1763      * {@code symbols} or {@code roundingMode} is {@code null}.
1764      * <li> If the {@code decimalPattern} or the {@code compactPatterns} array
1765      * contains an invalid pattern or if a {@code null} appears in the array of
1766      * compact patterns.
1767      * <li> If the {@code minimumIntegerDigits} is greater than the
1768      * {@code maximumIntegerDigits} or the {@code minimumFractionDigits} is
1769      * greater than the {@code maximumFractionDigits}. This check is performed
1770      * by superclass's Object.
1771      * <li> If any of the minimum/maximum integer/fraction digit count is
1772      * negative. This check is performed by superclass's readObject.
1773      * <li> If the minimum or maximum integer digit count is larger than 309 or
1774      * if the minimum or maximum fraction digit count is larger than 340.
1775      * <li> If the grouping size is negative or larger than 127.
1776      * </ul>
1777      *
1778      * @param inStream the stream
1779      * @throws IOException if an I/O error occurs
1780      * @throws ClassNotFoundException if the class of a serialized object
1781      *         could not be found
1782      */
1783     private void readObject(ObjectInputStream inStream) throws IOException,
1784             ClassNotFoundException {
1785 
1786         inStream.defaultReadObject();
1787         if (decimalPattern == null || compactPatterns == null
1788                 || symbols == null || roundingMode == null) {
1789             throw new InvalidObjectException("One of the 'decimalPattern',"
1790                     + " 'compactPatterns', 'symbols' or 'roundingMode'"
1791                     + " is null");
1792         }
1793 
1794         // Check only the maximum counts because NumberFormat.readObject has
1795         // already ensured that the maximum is greater than the minimum count.
1796         if (getMaximumIntegerDigits() > DecimalFormat.DOUBLE_INTEGER_DIGITS
1797                 || getMaximumFractionDigits() > DecimalFormat.DOUBLE_FRACTION_DIGITS) {
1798             throw new InvalidObjectException("Digit count out of range");
1799         }
1800 
1801         // Check if the grouping size is negative, on an attempt to
1802         // put value > 127, it wraps around, so check just negative value
1803         if (groupingSize < 0) {
1804             throw new InvalidObjectException("Grouping size is negative");
1805         }
1806 
1807         try {
1808             processCompactPatterns();
1809         } catch (IllegalArgumentException ex) {
1810             throw new InvalidObjectException(ex.getMessage());
1811         }
1812 
1813         decimalFormat = new DecimalFormat(SPECIAL_PATTERN, symbols);
1814         decimalFormat.setMaximumFractionDigits(getMaximumFractionDigits());
1815         decimalFormat.setMinimumFractionDigits(getMinimumFractionDigits());
1816         decimalFormat.setMaximumIntegerDigits(getMaximumIntegerDigits());
1817         decimalFormat.setMinimumIntegerDigits(getMinimumIntegerDigits());
1818         decimalFormat.setRoundingMode(getRoundingMode());
1819         decimalFormat.setGroupingSize(getGroupingSize());
1820         decimalFormat.setGroupingUsed(isGroupingUsed());
1821         decimalFormat.setParseIntegerOnly(isParseIntegerOnly());
1822 
1823         try {
1824             defaultDecimalFormat = new DecimalFormat(decimalPattern, symbols);
1825             defaultDecimalFormat.setMaximumFractionDigits(0);
1826         } catch (IllegalArgumentException ex) {
1827             throw new InvalidObjectException(ex.getMessage());
1828         }
1829 
1830     }
1831 
1832     /**
1833      * Sets the maximum number of digits allowed in the integer portion of a
1834      * number.
1835      * The maximum allowed integer range is 309, if the {@code newValue} &gt; 309,
1836      * then the maximum integer digits count is set to 309. Negative input
1837      * values are replaced with 0.
1838      *
1839      * @param newValue the maximum number of integer digits to be shown
1840      * @see #getMaximumIntegerDigits()
1841      */
1842     @Override
1843     public void setMaximumIntegerDigits(int newValue) {
1844         // The maximum integer digits is checked with the allowed range before calling
1845         // the DecimalFormat.setMaximumIntegerDigits, which performs the negative check
1846         // on the given newValue while setting it as max integer digits.
1847         // For example, if a negative value is specified, it is replaced with 0
1848         decimalFormat.setMaximumIntegerDigits(Math.min(newValue,
1849                 DecimalFormat.DOUBLE_INTEGER_DIGITS));
1850         super.setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits());
1851         if (decimalFormat.getMinimumIntegerDigits() > decimalFormat.getMaximumIntegerDigits()) {
1852             decimalFormat.setMinimumIntegerDigits(decimalFormat.getMaximumIntegerDigits());
1853             super.setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits());
1854         }
1855     }
1856 
1857     /**
1858      * Sets the minimum number of digits allowed in the integer portion of a
1859      * number.
1860      * The maximum allowed integer range is 309, if the {@code newValue} &gt; 309,
1861      * then the minimum integer digits count is set to 309. Negative input
1862      * values are replaced with 0.
1863      *
1864      * @param newValue the minimum number of integer digits to be shown
1865      * @see #getMinimumIntegerDigits()
1866      */
1867     @Override
1868     public void setMinimumIntegerDigits(int newValue) {
1869         // The minimum integer digits is checked with the allowed range before calling
1870         // the DecimalFormat.setMinimumIntegerDigits, which performs check on the given
1871         // newValue while setting it as min integer digits. For example, if a negative
1872         // value is specified, it is replaced with 0
1873         decimalFormat.setMinimumIntegerDigits(Math.min(newValue,
1874                 DecimalFormat.DOUBLE_INTEGER_DIGITS));
1875         super.setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits());
1876         if (decimalFormat.getMinimumIntegerDigits() > decimalFormat.getMaximumIntegerDigits()) {
1877             decimalFormat.setMaximumIntegerDigits(decimalFormat.getMinimumIntegerDigits());
1878             super.setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits());
1879         }
1880     }
1881 
1882     /**
1883      * Sets the minimum number of digits allowed in the fraction portion of a
1884      * number.
1885      * The maximum allowed fraction range is 340, if the {@code newValue} &gt; 340,
1886      * then the minimum fraction digits count is set to 340. Negative input
1887      * values are replaced with 0.
1888      *
1889      * @param newValue the minimum number of fraction digits to be shown
1890      * @see #getMinimumFractionDigits()
1891      */
1892     @Override
1893     public void setMinimumFractionDigits(int newValue) {
1894         // The minimum fraction digits is checked with the allowed range before
1895         // calling the DecimalFormat.setMinimumFractionDigits, which performs
1896         // check on the given newValue while setting it as min fraction
1897         // digits. For example, if a negative value is specified, it is
1898         // replaced with 0
1899         decimalFormat.setMinimumFractionDigits(Math.min(newValue,
1900                 DecimalFormat.DOUBLE_FRACTION_DIGITS));
1901         super.setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits());
1902         if (decimalFormat.getMinimumFractionDigits() > decimalFormat.getMaximumFractionDigits()) {
1903             decimalFormat.setMaximumFractionDigits(decimalFormat.getMinimumFractionDigits());
1904             super.setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits());
1905         }
1906     }
1907 
1908     /**
1909      * Sets the maximum number of digits allowed in the fraction portion of a
1910      * number.
1911      * The maximum allowed fraction range is 340, if the {@code newValue} &gt; 340,
1912      * then the maximum fraction digits count is set to 340. Negative input
1913      * values are replaced with 0.
1914      *
1915      * @param newValue the maximum number of fraction digits to be shown
1916      * @see #getMaximumFractionDigits()
1917      */
1918     @Override
1919     public void setMaximumFractionDigits(int newValue) {
1920         // The maximum fraction digits is checked with the allowed range before
1921         // calling the DecimalFormat.setMaximumFractionDigits, which performs
1922         // check on the given newValue while setting it as max fraction digits.
1923         // For example, if a negative value is specified, it is replaced with 0
1924         decimalFormat.setMaximumFractionDigits(Math.min(newValue,
1925                 DecimalFormat.DOUBLE_FRACTION_DIGITS));
1926         super.setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits());
1927         if (decimalFormat.getMinimumFractionDigits() > decimalFormat.getMaximumFractionDigits()) {
1928             decimalFormat.setMinimumFractionDigits(decimalFormat.getMaximumFractionDigits());
1929             super.setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits());
1930         }
1931     }
1932 
1933     /**
1934      * Gets the {@link java.math.RoundingMode} used in this
1935      * {@code CompactNumberFormat}.
1936      *
1937      * @return the {@code RoundingMode} used for this
1938      *         {@code CompactNumberFormat}
1939      * @see #setRoundingMode(RoundingMode)
1940      */
1941     @Override
1942     public RoundingMode getRoundingMode() {
1943         return roundingMode;
1944     }
1945 
1946     /**
1947      * Sets the {@link java.math.RoundingMode} used in this
1948      * {@code CompactNumberFormat}.
1949      *
1950      * @param roundingMode the {@code RoundingMode} to be used
1951      * @see #getRoundingMode()
1952      * @throws NullPointerException if {@code roundingMode} is {@code null}
1953      */
1954     @Override
1955     public void setRoundingMode(RoundingMode roundingMode) {
1956         decimalFormat.setRoundingMode(roundingMode);
1957         this.roundingMode = roundingMode;
1958     }
1959 
1960     /**
1961      * Returns the grouping size. Grouping size is the number of digits between
1962      * grouping separators in the integer portion of a number. For example,
1963      * in the compact number {@code "12,347 trillion"} for the
1964      * {@link java.util.Locale#US US locale}, the grouping size is 3.
1965      *
1966      * @return the grouping size
1967      * @see #setGroupingSize
1968      * @see java.text.NumberFormat#isGroupingUsed
1969      * @see java.text.DecimalFormatSymbols#getGroupingSeparator
1970      */
1971     public int getGroupingSize() {
1972         return groupingSize;
1973     }
1974 
1975     /**
1976      * Sets the grouping size. Grouping size is the number of digits between
1977      * grouping separators in the integer portion of a number. For example,
1978      * in the compact number {@code "12,347 trillion"} for the
1979      * {@link java.util.Locale#US US locale}, the grouping size is 3. The grouping
1980      * size must be greater than or equal to zero and less than or equal to 127.
1981      *
1982      * @param newValue the new grouping size
1983      * @see #getGroupingSize
1984      * @see java.text.NumberFormat#setGroupingUsed
1985      * @see java.text.DecimalFormatSymbols#setGroupingSeparator
1986      * @throws IllegalArgumentException if {@code newValue} is negative or
1987      * larger than 127
1988      */
1989     public void setGroupingSize(int newValue) {
1990         if (newValue < 0 || newValue > 127) {
1991             throw new IllegalArgumentException(
1992                     "The value passed is negative or larger than 127");
1993         }
1994         groupingSize = (byte) newValue;
1995         decimalFormat.setGroupingSize(groupingSize);
1996     }
1997 
1998     /**
1999      * Returns true if grouping is used in this format. For example, with
2000      * grouping on and grouping size set to 3, the number {@code 12346567890987654}
2001      * can be formatted as {@code "12,347 trillion"} in the
2002      * {@link java.util.Locale#US US locale}.
2003      * The grouping separator is locale dependent.
2004      *
2005      * @return {@code true} if grouping is used;
2006      *         {@code false} otherwise
2007      * @see #setGroupingUsed
2008      */
2009     @Override
2010     public boolean isGroupingUsed() {
2011         return super.isGroupingUsed();
2012     }
2013 
2014     /**
2015      * Sets whether or not grouping will be used in this format.
2016      *
2017      * @param newValue {@code true} if grouping is used;
2018      *                 {@code false} otherwise
2019      * @see #isGroupingUsed
2020      */
2021     @Override
2022     public void setGroupingUsed(boolean newValue) {
2023         decimalFormat.setGroupingUsed(newValue);
2024         super.setGroupingUsed(newValue);
2025     }
2026 
2027     /**
2028      * Returns true if this format parses only an integer from the number
2029      * component of a compact number.
2030      * Parsing an integer means that only an integer is considered from the
2031      * number component, prefix/suffix is still considered to compute the
2032      * resulting output.
2033      * For example, in the {@link java.util.Locale#US US locale}, if this method
2034      * returns {@code true}, the string {@code "1234.78 thousand"} would be
2035      * parsed as the value {@code 1234000} (1234 (integer part) * 1000
2036      * (thousand)) and the fractional part would be skipped.
2037      * The exact format accepted by the parse operation is locale dependent.
2038      *
2039      * @return {@code true} if compact numbers should be parsed as integers
2040      *         only; {@code false} otherwise
2041      */
2042     @Override
2043     public boolean isParseIntegerOnly() {
2044         return super.isParseIntegerOnly();
2045     }
2046 
2047     /**
2048      * Sets whether or not this format parses only an integer from the number
2049      * component of a compact number.
2050      *
2051      * @param value {@code true} if compact numbers should be parsed as
2052      *              integers only; {@code false} otherwise
2053      * @see #isParseIntegerOnly
2054      */
2055     @Override
2056     public void setParseIntegerOnly(boolean value) {
2057         decimalFormat.setParseIntegerOnly(value);
2058         super.setParseIntegerOnly(value);
2059     }
2060 
2061     /**
2062      * Returns whether the {@link #parse(String, ParsePosition)}
2063      * method returns {@code BigDecimal}. The default value is false.
2064      *
2065      * @return {@code true} if the parse method returns BigDecimal;
2066      *         {@code false} otherwise
2067      * @see #setParseBigDecimal
2068      *
2069      */
2070     public boolean isParseBigDecimal() {
2071         return parseBigDecimal;
2072     }
2073 
2074     /**
2075      * Sets whether the {@link #parse(String, ParsePosition)}
2076      * method returns {@code BigDecimal}.
2077      *
2078      * @param newValue {@code true} if the parse method returns BigDecimal;
2079      *                 {@code false} otherwise
2080      * @see #isParseBigDecimal
2081      *
2082      */
2083     public void setParseBigDecimal(boolean newValue) {
2084         parseBigDecimal = newValue;
2085     }
2086 
2087     /**
2088      * Checks if this {@code CompactNumberFormat} is equal to the
2089      * specified {@code obj}. The objects of type {@code CompactNumberFormat}
2090      * are compared, other types return false; obeys the general contract of
2091      * {@link java.lang.Object#equals(java.lang.Object) Object.equals}.
2092      *
2093      * @param obj the object to compare with
2094      * @return true if this is equal to the other {@code CompactNumberFormat}
2095      */
2096     @Override
2097     public boolean equals(Object obj) {
2098 
2099         if (!super.equals(obj)) {
2100             return false;
2101         }
2102 
2103         CompactNumberFormat other = (CompactNumberFormat) obj;
2104         return decimalPattern.equals(other.decimalPattern)
2105                 && symbols.equals(other.symbols)
2106                 && Arrays.equals(compactPatterns, other.compactPatterns)
2107                 && roundingMode.equals(other.roundingMode)
2108                 && groupingSize == other.groupingSize
2109                 && parseBigDecimal == other.parseBigDecimal;
2110     }
2111 
2112     /**
2113      * Returns the hash code for this {@code CompactNumberFormat} instance.
2114      *
2115      * @return hash code for this {@code CompactNumberFormat}
2116      */
2117     @Override
2118     public int hashCode() {
2119         return 31 * super.hashCode() +
2120                 Objects.hash(decimalPattern, symbols, roundingMode)
2121                 + Arrays.hashCode(compactPatterns) + groupingSize
2122                 + Boolean.hashCode(parseBigDecimal);
2123     }
2124 
2125     /**
2126      * Creates and returns a copy of this {@code CompactNumberFormat}
2127      * instance.
2128      *
2129      * @return a clone of this instance
2130      */
2131     @Override
2132     public CompactNumberFormat clone() {
2133         CompactNumberFormat other = (CompactNumberFormat) super.clone();
2134         other.compactPatterns = compactPatterns.clone();
2135         other.symbols = (DecimalFormatSymbols) symbols.clone();
2136         return other;
2137     }
2138 
2139 }
2140