rt/emul/compact/src/main/java/java/text/ChoiceFormat.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 03 Oct 2013 15:40:35 +0200
branchjdk7-b147
changeset 1334 588d5bf7a560
permissions -rw-r--r--
Set of JDK classes needed to run javac
jtulach@1334
     1
/*
jtulach@1334
     2
 * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
jtulach@1334
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jtulach@1334
     4
 *
jtulach@1334
     5
 * This code is free software; you can redistribute it and/or modify it
jtulach@1334
     6
 * under the terms of the GNU General Public License version 2 only, as
jtulach@1334
     7
 * published by the Free Software Foundation.  Oracle designates this
jtulach@1334
     8
 * particular file as subject to the "Classpath" exception as provided
jtulach@1334
     9
 * by Oracle in the LICENSE file that accompanied this code.
jtulach@1334
    10
 *
jtulach@1334
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jtulach@1334
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jtulach@1334
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jtulach@1334
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jtulach@1334
    15
 * accompanied this code).
jtulach@1334
    16
 *
jtulach@1334
    17
 * You should have received a copy of the GNU General Public License version
jtulach@1334
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jtulach@1334
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jtulach@1334
    20
 *
jtulach@1334
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jtulach@1334
    22
 * or visit www.oracle.com if you need additional information or have any
jtulach@1334
    23
 * questions.
jtulach@1334
    24
 */
jtulach@1334
    25
jtulach@1334
    26
/*
jtulach@1334
    27
 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
jtulach@1334
    28
 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
jtulach@1334
    29
 *
jtulach@1334
    30
 *   The original version of this source code and documentation is copyrighted
jtulach@1334
    31
 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
jtulach@1334
    32
 * materials are provided under terms of a License Agreement between Taligent
jtulach@1334
    33
 * and Sun. This technology is protected by multiple US and International
jtulach@1334
    34
 * patents. This notice and attribution to Taligent may not be removed.
jtulach@1334
    35
 *   Taligent is a registered trademark of Taligent, Inc.
jtulach@1334
    36
 *
jtulach@1334
    37
 */
jtulach@1334
    38
jtulach@1334
    39
package java.text;
jtulach@1334
    40
jtulach@1334
    41
import java.io.InvalidObjectException;
jtulach@1334
    42
import java.io.IOException;
jtulach@1334
    43
import java.io.ObjectInputStream;
jtulach@1334
    44
import java.util.Arrays;
jtulach@1334
    45
jtulach@1334
    46
/**
jtulach@1334
    47
 * A <code>ChoiceFormat</code> allows you to attach a format to a range of numbers.
jtulach@1334
    48
 * It is generally used in a <code>MessageFormat</code> for handling plurals.
jtulach@1334
    49
 * The choice is specified with an ascending list of doubles, where each item
jtulach@1334
    50
 * specifies a half-open interval up to the next item:
jtulach@1334
    51
 * <blockquote>
jtulach@1334
    52
 * <pre>
jtulach@1334
    53
 * X matches j if and only if limit[j] &lt;= X &lt; limit[j+1]
jtulach@1334
    54
 * </pre>
jtulach@1334
    55
 * </blockquote>
jtulach@1334
    56
 * If there is no match, then either the first or last index is used, depending
jtulach@1334
    57
 * on whether the number (X) is too low or too high.  If the limit array is not
jtulach@1334
    58
 * in ascending order, the results of formatting will be incorrect.  ChoiceFormat
jtulach@1334
    59
 * also accepts <code>&#92;u221E</code> as equivalent to infinity(INF).
jtulach@1334
    60
 *
jtulach@1334
    61
 * <p>
jtulach@1334
    62
 * <strong>Note:</strong>
jtulach@1334
    63
 * <code>ChoiceFormat</code> differs from the other <code>Format</code>
jtulach@1334
    64
 * classes in that you create a <code>ChoiceFormat</code> object with a
jtulach@1334
    65
 * constructor (not with a <code>getInstance</code> style factory
jtulach@1334
    66
 * method). The factory methods aren't necessary because <code>ChoiceFormat</code>
jtulach@1334
    67
 * doesn't require any complex setup for a given locale. In fact,
jtulach@1334
    68
 * <code>ChoiceFormat</code> doesn't implement any locale specific behavior.
jtulach@1334
    69
 *
jtulach@1334
    70
 * <p>
jtulach@1334
    71
 * When creating a <code>ChoiceFormat</code>, you must specify an array of formats
jtulach@1334
    72
 * and an array of limits. The length of these arrays must be the same.
jtulach@1334
    73
 * For example,
jtulach@1334
    74
 * <ul>
jtulach@1334
    75
 * <li>
jtulach@1334
    76
 *     <em>limits</em> = {1,2,3,4,5,6,7}<br>
jtulach@1334
    77
 *     <em>formats</em> = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}
jtulach@1334
    78
 * <li>
jtulach@1334
    79
 *     <em>limits</em> = {0, 1, ChoiceFormat.nextDouble(1)}<br>
jtulach@1334
    80
 *     <em>formats</em> = {"no files", "one file", "many files"}<br>
jtulach@1334
    81
 *     (<code>nextDouble</code> can be used to get the next higher double, to
jtulach@1334
    82
 *     make the half-open interval.)
jtulach@1334
    83
 * </ul>
jtulach@1334
    84
 *
jtulach@1334
    85
 * <p>
jtulach@1334
    86
 * Here is a simple example that shows formatting and parsing:
jtulach@1334
    87
 * <blockquote>
jtulach@1334
    88
 * <pre>
jtulach@1334
    89
 * double[] limits = {1,2,3,4,5,6,7};
jtulach@1334
    90
 * String[] dayOfWeekNames = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
jtulach@1334
    91
 * ChoiceFormat form = new ChoiceFormat(limits, dayOfWeekNames);
jtulach@1334
    92
 * ParsePosition status = new ParsePosition(0);
jtulach@1334
    93
 * for (double i = 0.0; i &lt;= 8.0; ++i) {
jtulach@1334
    94
 *     status.setIndex(0);
jtulach@1334
    95
 *     System.out.println(i + " -&gt; " + form.format(i) + " -&gt; "
jtulach@1334
    96
 *                              + form.parse(form.format(i),status));
jtulach@1334
    97
 * }
jtulach@1334
    98
 * </pre>
jtulach@1334
    99
 * </blockquote>
jtulach@1334
   100
 * Here is a more complex example, with a pattern format:
jtulach@1334
   101
 * <blockquote>
jtulach@1334
   102
 * <pre>
jtulach@1334
   103
 * double[] filelimits = {0,1,2};
jtulach@1334
   104
 * String[] filepart = {"are no files","is one file","are {2} files"};
jtulach@1334
   105
 * ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
jtulach@1334
   106
 * Format[] testFormats = {fileform, null, NumberFormat.getInstance()};
jtulach@1334
   107
 * MessageFormat pattform = new MessageFormat("There {0} on {1}");
jtulach@1334
   108
 * pattform.setFormats(testFormats);
jtulach@1334
   109
 * Object[] testArgs = {null, "ADisk", null};
jtulach@1334
   110
 * for (int i = 0; i &lt; 4; ++i) {
jtulach@1334
   111
 *     testArgs[0] = new Integer(i);
jtulach@1334
   112
 *     testArgs[2] = testArgs[0];
jtulach@1334
   113
 *     System.out.println(pattform.format(testArgs));
jtulach@1334
   114
 * }
jtulach@1334
   115
 * </pre>
jtulach@1334
   116
 * </blockquote>
jtulach@1334
   117
 * <p>
jtulach@1334
   118
 * Specifying a pattern for ChoiceFormat objects is fairly straightforward.
jtulach@1334
   119
 * For example:
jtulach@1334
   120
 * <blockquote>
jtulach@1334
   121
 * <pre>
jtulach@1334
   122
 * ChoiceFormat fmt = new ChoiceFormat(
jtulach@1334
   123
 *      "-1#is negative| 0#is zero or fraction | 1#is one |1.0&lt;is 1+ |2#is two |2&lt;is more than 2.");
jtulach@1334
   124
 * System.out.println("Formatter Pattern : " + fmt.toPattern());
jtulach@1334
   125
 *
jtulach@1334
   126
 * System.out.println("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY));
jtulach@1334
   127
 * System.out.println("Format with -1.0 : " + fmt.format(-1.0));
jtulach@1334
   128
 * System.out.println("Format with 0 : " + fmt.format(0));
jtulach@1334
   129
 * System.out.println("Format with 0.9 : " + fmt.format(0.9));
jtulach@1334
   130
 * System.out.println("Format with 1.0 : " + fmt.format(1));
jtulach@1334
   131
 * System.out.println("Format with 1.5 : " + fmt.format(1.5));
jtulach@1334
   132
 * System.out.println("Format with 2 : " + fmt.format(2));
jtulach@1334
   133
 * System.out.println("Format with 2.1 : " + fmt.format(2.1));
jtulach@1334
   134
 * System.out.println("Format with NaN : " + fmt.format(Double.NaN));
jtulach@1334
   135
 * System.out.println("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY));
jtulach@1334
   136
 * </pre>
jtulach@1334
   137
 * </blockquote>
jtulach@1334
   138
 * And the output result would be like the following:
jtulach@1334
   139
 * <blockquote>
jtulach@1334
   140
 * <pre>
jtulach@1334
   141
 *   Format with -INF : is negative
jtulach@1334
   142
 *   Format with -1.0 : is negative
jtulach@1334
   143
 *   Format with 0 : is zero or fraction
jtulach@1334
   144
 *   Format with 0.9 : is zero or fraction
jtulach@1334
   145
 *   Format with 1.0 : is one
jtulach@1334
   146
 *   Format with 1.5 : is 1+
jtulach@1334
   147
 *   Format with 2 : is two
jtulach@1334
   148
 *   Format with 2.1 : is more than 2.
jtulach@1334
   149
 *   Format with NaN : is negative
jtulach@1334
   150
 *   Format with +INF : is more than 2.
jtulach@1334
   151
 * </pre>
jtulach@1334
   152
 * </blockquote>
jtulach@1334
   153
 *
jtulach@1334
   154
 * <h4><a name="synchronization">Synchronization</a></h4>
jtulach@1334
   155
 *
jtulach@1334
   156
 * <p>
jtulach@1334
   157
 * Choice formats are not synchronized.
jtulach@1334
   158
 * It is recommended to create separate format instances for each thread.
jtulach@1334
   159
 * If multiple threads access a format concurrently, it must be synchronized
jtulach@1334
   160
 * externally.
jtulach@1334
   161
 *
jtulach@1334
   162
 *
jtulach@1334
   163
 * @see          DecimalFormat
jtulach@1334
   164
 * @see          MessageFormat
jtulach@1334
   165
 * @author       Mark Davis
jtulach@1334
   166
 */
jtulach@1334
   167
public class ChoiceFormat extends NumberFormat {
jtulach@1334
   168
jtulach@1334
   169
    // Proclaim serial compatibility with 1.1 FCS
jtulach@1334
   170
    private static final long serialVersionUID = 1795184449645032964L;
jtulach@1334
   171
jtulach@1334
   172
    /**
jtulach@1334
   173
     * Sets the pattern.
jtulach@1334
   174
     * @param newPattern See the class description.
jtulach@1334
   175
     */
jtulach@1334
   176
    public void applyPattern(String newPattern) {
jtulach@1334
   177
        StringBuffer[] segments = new StringBuffer[2];
jtulach@1334
   178
        for (int i = 0; i < segments.length; ++i) {
jtulach@1334
   179
            segments[i] = new StringBuffer();
jtulach@1334
   180
        }
jtulach@1334
   181
        double[] newChoiceLimits = new double[30];
jtulach@1334
   182
        String[] newChoiceFormats = new String[30];
jtulach@1334
   183
        int count = 0;
jtulach@1334
   184
        int part = 0;
jtulach@1334
   185
        double startValue = 0;
jtulach@1334
   186
        double oldStartValue = Double.NaN;
jtulach@1334
   187
        boolean inQuote = false;
jtulach@1334
   188
        for (int i = 0; i < newPattern.length(); ++i) {
jtulach@1334
   189
            char ch = newPattern.charAt(i);
jtulach@1334
   190
            if (ch=='\'') {
jtulach@1334
   191
                // Check for "''" indicating a literal quote
jtulach@1334
   192
                if ((i+1)<newPattern.length() && newPattern.charAt(i+1)==ch) {
jtulach@1334
   193
                    segments[part].append(ch);
jtulach@1334
   194
                    ++i;
jtulach@1334
   195
                } else {
jtulach@1334
   196
                    inQuote = !inQuote;
jtulach@1334
   197
                }
jtulach@1334
   198
            } else if (inQuote) {
jtulach@1334
   199
                segments[part].append(ch);
jtulach@1334
   200
            } else if (ch == '<' || ch == '#' || ch == '\u2264') {
jtulach@1334
   201
                if (segments[0].length() == 0) {
jtulach@1334
   202
                    throw new IllegalArgumentException();
jtulach@1334
   203
                }
jtulach@1334
   204
                try {
jtulach@1334
   205
                    String tempBuffer = segments[0].toString();
jtulach@1334
   206
                    if (tempBuffer.equals("\u221E")) {
jtulach@1334
   207
                        startValue = Double.POSITIVE_INFINITY;
jtulach@1334
   208
                    } else if (tempBuffer.equals("-\u221E")) {
jtulach@1334
   209
                        startValue = Double.NEGATIVE_INFINITY;
jtulach@1334
   210
                    } else {
jtulach@1334
   211
                        startValue = Double.valueOf(segments[0].toString()).doubleValue();
jtulach@1334
   212
                    }
jtulach@1334
   213
                } catch (Exception e) {
jtulach@1334
   214
                    throw new IllegalArgumentException();
jtulach@1334
   215
                }
jtulach@1334
   216
                if (ch == '<' && startValue != Double.POSITIVE_INFINITY &&
jtulach@1334
   217
                        startValue != Double.NEGATIVE_INFINITY) {
jtulach@1334
   218
                    startValue = nextDouble(startValue);
jtulach@1334
   219
                }
jtulach@1334
   220
                if (startValue <= oldStartValue) {
jtulach@1334
   221
                    throw new IllegalArgumentException();
jtulach@1334
   222
                }
jtulach@1334
   223
                segments[0].setLength(0);
jtulach@1334
   224
                part = 1;
jtulach@1334
   225
            } else if (ch == '|') {
jtulach@1334
   226
                if (count == newChoiceLimits.length) {
jtulach@1334
   227
                    newChoiceLimits = doubleArraySize(newChoiceLimits);
jtulach@1334
   228
                    newChoiceFormats = doubleArraySize(newChoiceFormats);
jtulach@1334
   229
                }
jtulach@1334
   230
                newChoiceLimits[count] = startValue;
jtulach@1334
   231
                newChoiceFormats[count] = segments[1].toString();
jtulach@1334
   232
                ++count;
jtulach@1334
   233
                oldStartValue = startValue;
jtulach@1334
   234
                segments[1].setLength(0);
jtulach@1334
   235
                part = 0;
jtulach@1334
   236
            } else {
jtulach@1334
   237
                segments[part].append(ch);
jtulach@1334
   238
            }
jtulach@1334
   239
        }
jtulach@1334
   240
        // clean up last one
jtulach@1334
   241
        if (part == 1) {
jtulach@1334
   242
            if (count == newChoiceLimits.length) {
jtulach@1334
   243
                newChoiceLimits = doubleArraySize(newChoiceLimits);
jtulach@1334
   244
                newChoiceFormats = doubleArraySize(newChoiceFormats);
jtulach@1334
   245
            }
jtulach@1334
   246
            newChoiceLimits[count] = startValue;
jtulach@1334
   247
            newChoiceFormats[count] = segments[1].toString();
jtulach@1334
   248
            ++count;
jtulach@1334
   249
        }
jtulach@1334
   250
        choiceLimits = new double[count];
jtulach@1334
   251
        System.arraycopy(newChoiceLimits, 0, choiceLimits, 0, count);
jtulach@1334
   252
        choiceFormats = new String[count];
jtulach@1334
   253
        System.arraycopy(newChoiceFormats, 0, choiceFormats, 0, count);
jtulach@1334
   254
    }
jtulach@1334
   255
jtulach@1334
   256
    /**
jtulach@1334
   257
     * Gets the pattern.
jtulach@1334
   258
     */
jtulach@1334
   259
    public String toPattern() {
jtulach@1334
   260
        StringBuffer result = new StringBuffer();
jtulach@1334
   261
        for (int i = 0; i < choiceLimits.length; ++i) {
jtulach@1334
   262
            if (i != 0) {
jtulach@1334
   263
                result.append('|');
jtulach@1334
   264
            }
jtulach@1334
   265
            // choose based upon which has less precision
jtulach@1334
   266
            // approximate that by choosing the closest one to an integer.
jtulach@1334
   267
            // could do better, but it's not worth it.
jtulach@1334
   268
            double less = previousDouble(choiceLimits[i]);
jtulach@1334
   269
            double tryLessOrEqual = Math.abs(Math.IEEEremainder(choiceLimits[i], 1.0d));
jtulach@1334
   270
            double tryLess = Math.abs(Math.IEEEremainder(less, 1.0d));
jtulach@1334
   271
jtulach@1334
   272
            if (tryLessOrEqual < tryLess) {
jtulach@1334
   273
                result.append(""+choiceLimits[i]);
jtulach@1334
   274
                result.append('#');
jtulach@1334
   275
            } else {
jtulach@1334
   276
                if (choiceLimits[i] == Double.POSITIVE_INFINITY) {
jtulach@1334
   277
                    result.append("\u221E");
jtulach@1334
   278
                } else if (choiceLimits[i] == Double.NEGATIVE_INFINITY) {
jtulach@1334
   279
                    result.append("-\u221E");
jtulach@1334
   280
                } else {
jtulach@1334
   281
                    result.append(""+less);
jtulach@1334
   282
                }
jtulach@1334
   283
                result.append('<');
jtulach@1334
   284
            }
jtulach@1334
   285
            // Append choiceFormats[i], using quotes if there are special characters.
jtulach@1334
   286
            // Single quotes themselves must be escaped in either case.
jtulach@1334
   287
            String text = choiceFormats[i];
jtulach@1334
   288
            boolean needQuote = text.indexOf('<') >= 0
jtulach@1334
   289
                || text.indexOf('#') >= 0
jtulach@1334
   290
                || text.indexOf('\u2264') >= 0
jtulach@1334
   291
                || text.indexOf('|') >= 0;
jtulach@1334
   292
            if (needQuote) result.append('\'');
jtulach@1334
   293
            if (text.indexOf('\'') < 0) result.append(text);
jtulach@1334
   294
            else {
jtulach@1334
   295
                for (int j=0; j<text.length(); ++j) {
jtulach@1334
   296
                    char c = text.charAt(j);
jtulach@1334
   297
                    result.append(c);
jtulach@1334
   298
                    if (c == '\'') result.append(c);
jtulach@1334
   299
                }
jtulach@1334
   300
            }
jtulach@1334
   301
            if (needQuote) result.append('\'');
jtulach@1334
   302
        }
jtulach@1334
   303
        return result.toString();
jtulach@1334
   304
    }
jtulach@1334
   305
jtulach@1334
   306
    /**
jtulach@1334
   307
     * Constructs with limits and corresponding formats based on the pattern.
jtulach@1334
   308
     * @see #applyPattern
jtulach@1334
   309
     */
jtulach@1334
   310
    public ChoiceFormat(String newPattern)  {
jtulach@1334
   311
        applyPattern(newPattern);
jtulach@1334
   312
    }
jtulach@1334
   313
jtulach@1334
   314
    /**
jtulach@1334
   315
     * Constructs with the limits and the corresponding formats.
jtulach@1334
   316
     * @see #setChoices
jtulach@1334
   317
     */
jtulach@1334
   318
    public ChoiceFormat(double[] limits, String[] formats) {
jtulach@1334
   319
        setChoices(limits, formats);
jtulach@1334
   320
    }
jtulach@1334
   321
jtulach@1334
   322
    /**
jtulach@1334
   323
     * Set the choices to be used in formatting.
jtulach@1334
   324
     * @param limits contains the top value that you want
jtulach@1334
   325
     * parsed with that format,and should be in ascending sorted order. When
jtulach@1334
   326
     * formatting X, the choice will be the i, where
jtulach@1334
   327
     * limit[i] &lt;= X &lt; limit[i+1].
jtulach@1334
   328
     * If the limit array is not in ascending order, the results of formatting
jtulach@1334
   329
     * will be incorrect.
jtulach@1334
   330
     * @param formats are the formats you want to use for each limit.
jtulach@1334
   331
     * They can be either Format objects or Strings.
jtulach@1334
   332
     * When formatting with object Y,
jtulach@1334
   333
     * if the object is a NumberFormat, then ((NumberFormat) Y).format(X)
jtulach@1334
   334
     * is called. Otherwise Y.toString() is called.
jtulach@1334
   335
     */
jtulach@1334
   336
    public void setChoices(double[] limits, String formats[]) {
jtulach@1334
   337
        if (limits.length != formats.length) {
jtulach@1334
   338
            throw new IllegalArgumentException(
jtulach@1334
   339
                "Array and limit arrays must be of the same length.");
jtulach@1334
   340
        }
jtulach@1334
   341
        choiceLimits = limits;
jtulach@1334
   342
        choiceFormats = formats;
jtulach@1334
   343
    }
jtulach@1334
   344
jtulach@1334
   345
    /**
jtulach@1334
   346
     * Get the limits passed in the constructor.
jtulach@1334
   347
     * @return the limits.
jtulach@1334
   348
     */
jtulach@1334
   349
    public double[] getLimits() {
jtulach@1334
   350
        return choiceLimits;
jtulach@1334
   351
    }
jtulach@1334
   352
jtulach@1334
   353
    /**
jtulach@1334
   354
     * Get the formats passed in the constructor.
jtulach@1334
   355
     * @return the formats.
jtulach@1334
   356
     */
jtulach@1334
   357
    public Object[] getFormats() {
jtulach@1334
   358
        return choiceFormats;
jtulach@1334
   359
    }
jtulach@1334
   360
jtulach@1334
   361
    // Overrides
jtulach@1334
   362
jtulach@1334
   363
    /**
jtulach@1334
   364
     * Specialization of format. This method really calls
jtulach@1334
   365
     * <code>format(double, StringBuffer, FieldPosition)</code>
jtulach@1334
   366
     * thus the range of longs that are supported is only equal to
jtulach@1334
   367
     * the range that can be stored by double. This will never be
jtulach@1334
   368
     * a practical limitation.
jtulach@1334
   369
     */
jtulach@1334
   370
    public StringBuffer format(long number, StringBuffer toAppendTo,
jtulach@1334
   371
                               FieldPosition status) {
jtulach@1334
   372
        return format((double)number, toAppendTo, status);
jtulach@1334
   373
    }
jtulach@1334
   374
jtulach@1334
   375
    /**
jtulach@1334
   376
     * Returns pattern with formatted double.
jtulach@1334
   377
     * @param number number to be formatted & substituted.
jtulach@1334
   378
     * @param toAppendTo where text is appended.
jtulach@1334
   379
     * @param status ignore no useful status is returned.
jtulach@1334
   380
     */
jtulach@1334
   381
   public StringBuffer format(double number, StringBuffer toAppendTo,
jtulach@1334
   382
                               FieldPosition status) {
jtulach@1334
   383
        // find the number
jtulach@1334
   384
        int i;
jtulach@1334
   385
        for (i = 0; i < choiceLimits.length; ++i) {
jtulach@1334
   386
            if (!(number >= choiceLimits[i])) {
jtulach@1334
   387
                // same as number < choiceLimits, except catchs NaN
jtulach@1334
   388
                break;
jtulach@1334
   389
            }
jtulach@1334
   390
        }
jtulach@1334
   391
        --i;
jtulach@1334
   392
        if (i < 0) i = 0;
jtulach@1334
   393
        // return either a formatted number, or a string
jtulach@1334
   394
        return toAppendTo.append(choiceFormats[i]);
jtulach@1334
   395
    }
jtulach@1334
   396
jtulach@1334
   397
    /**
jtulach@1334
   398
     * Parses a Number from the input text.
jtulach@1334
   399
     * @param text the source text.
jtulach@1334
   400
     * @param status an input-output parameter.  On input, the
jtulach@1334
   401
     * status.index field indicates the first character of the
jtulach@1334
   402
     * source text that should be parsed.  On exit, if no error
jtulach@1334
   403
     * occured, status.index is set to the first unparsed character
jtulach@1334
   404
     * in the source text.  On exit, if an error did occur,
jtulach@1334
   405
     * status.index is unchanged and status.errorIndex is set to the
jtulach@1334
   406
     * first index of the character that caused the parse to fail.
jtulach@1334
   407
     * @return A Number representing the value of the number parsed.
jtulach@1334
   408
     */
jtulach@1334
   409
    public Number parse(String text, ParsePosition status) {
jtulach@1334
   410
        // find the best number (defined as the one with the longest parse)
jtulach@1334
   411
        int start = status.index;
jtulach@1334
   412
        int furthest = start;
jtulach@1334
   413
        double bestNumber = Double.NaN;
jtulach@1334
   414
        double tempNumber = 0.0;
jtulach@1334
   415
        for (int i = 0; i < choiceFormats.length; ++i) {
jtulach@1334
   416
            String tempString = choiceFormats[i];
jtulach@1334
   417
            if (text.regionMatches(start, tempString, 0, tempString.length())) {
jtulach@1334
   418
                status.index = start + tempString.length();
jtulach@1334
   419
                tempNumber = choiceLimits[i];
jtulach@1334
   420
                if (status.index > furthest) {
jtulach@1334
   421
                    furthest = status.index;
jtulach@1334
   422
                    bestNumber = tempNumber;
jtulach@1334
   423
                    if (furthest == text.length()) break;
jtulach@1334
   424
                }
jtulach@1334
   425
            }
jtulach@1334
   426
        }
jtulach@1334
   427
        status.index = furthest;
jtulach@1334
   428
        if (status.index == start) {
jtulach@1334
   429
            status.errorIndex = furthest;
jtulach@1334
   430
        }
jtulach@1334
   431
        return new Double(bestNumber);
jtulach@1334
   432
    }
jtulach@1334
   433
jtulach@1334
   434
    /**
jtulach@1334
   435
     * Finds the least double greater than d.
jtulach@1334
   436
     * If NaN, returns same value.
jtulach@1334
   437
     * <p>Used to make half-open intervals.
jtulach@1334
   438
     * @see #previousDouble
jtulach@1334
   439
     */
jtulach@1334
   440
    public static final double nextDouble (double d) {
jtulach@1334
   441
        return nextDouble(d,true);
jtulach@1334
   442
    }
jtulach@1334
   443
jtulach@1334
   444
    /**
jtulach@1334
   445
     * Finds the greatest double less than d.
jtulach@1334
   446
     * If NaN, returns same value.
jtulach@1334
   447
     * @see #nextDouble
jtulach@1334
   448
     */
jtulach@1334
   449
    public static final double previousDouble (double d) {
jtulach@1334
   450
        return nextDouble(d,false);
jtulach@1334
   451
    }
jtulach@1334
   452
jtulach@1334
   453
    /**
jtulach@1334
   454
     * Overrides Cloneable
jtulach@1334
   455
     */
jtulach@1334
   456
    public Object clone()
jtulach@1334
   457
    {
jtulach@1334
   458
        ChoiceFormat other = (ChoiceFormat) super.clone();
jtulach@1334
   459
        // for primitives or immutables, shallow clone is enough
jtulach@1334
   460
        other.choiceLimits = (double[]) choiceLimits.clone();
jtulach@1334
   461
        other.choiceFormats = (String[]) choiceFormats.clone();
jtulach@1334
   462
        return other;
jtulach@1334
   463
    }
jtulach@1334
   464
jtulach@1334
   465
    /**
jtulach@1334
   466
     * Generates a hash code for the message format object.
jtulach@1334
   467
     */
jtulach@1334
   468
    public int hashCode() {
jtulach@1334
   469
        int result = choiceLimits.length;
jtulach@1334
   470
        if (choiceFormats.length > 0) {
jtulach@1334
   471
            // enough for reasonable distribution
jtulach@1334
   472
            result ^= choiceFormats[choiceFormats.length-1].hashCode();
jtulach@1334
   473
        }
jtulach@1334
   474
        return result;
jtulach@1334
   475
    }
jtulach@1334
   476
jtulach@1334
   477
    /**
jtulach@1334
   478
     * Equality comparision between two
jtulach@1334
   479
     */
jtulach@1334
   480
    public boolean equals(Object obj) {
jtulach@1334
   481
        if (obj == null) return false;
jtulach@1334
   482
        if (this == obj)                      // quick check
jtulach@1334
   483
            return true;
jtulach@1334
   484
        if (getClass() != obj.getClass())
jtulach@1334
   485
            return false;
jtulach@1334
   486
        ChoiceFormat other = (ChoiceFormat) obj;
jtulach@1334
   487
        return (Arrays.equals(choiceLimits, other.choiceLimits)
jtulach@1334
   488
             && Arrays.equals(choiceFormats, other.choiceFormats));
jtulach@1334
   489
    }
jtulach@1334
   490
jtulach@1334
   491
    /**
jtulach@1334
   492
     * After reading an object from the input stream, do a simple verification
jtulach@1334
   493
     * to maintain class invariants.
jtulach@1334
   494
     * @throws InvalidObjectException if the objects read from the stream is invalid.
jtulach@1334
   495
     */
jtulach@1334
   496
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
jtulach@1334
   497
        in.defaultReadObject();
jtulach@1334
   498
        if (choiceLimits.length != choiceFormats.length) {
jtulach@1334
   499
            throw new InvalidObjectException(
jtulach@1334
   500
                    "limits and format arrays of different length.");
jtulach@1334
   501
        }
jtulach@1334
   502
    }
jtulach@1334
   503
jtulach@1334
   504
    // ===============privates===========================
jtulach@1334
   505
jtulach@1334
   506
    /**
jtulach@1334
   507
     * A list of lower bounds for the choices.  The formatter will return
jtulach@1334
   508
     * <code>choiceFormats[i]</code> if the number being formatted is greater than or equal to
jtulach@1334
   509
     * <code>choiceLimits[i]</code> and less than <code>choiceLimits[i+1]</code>.
jtulach@1334
   510
     * @serial
jtulach@1334
   511
     */
jtulach@1334
   512
    private double[] choiceLimits;
jtulach@1334
   513
jtulach@1334
   514
    /**
jtulach@1334
   515
     * A list of choice strings.  The formatter will return
jtulach@1334
   516
     * <code>choiceFormats[i]</code> if the number being formatted is greater than or equal to
jtulach@1334
   517
     * <code>choiceLimits[i]</code> and less than <code>choiceLimits[i+1]</code>.
jtulach@1334
   518
     * @serial
jtulach@1334
   519
     */
jtulach@1334
   520
    private String[] choiceFormats;
jtulach@1334
   521
jtulach@1334
   522
    /*
jtulach@1334
   523
    static final long SIGN          = 0x8000000000000000L;
jtulach@1334
   524
    static final long EXPONENT      = 0x7FF0000000000000L;
jtulach@1334
   525
    static final long SIGNIFICAND   = 0x000FFFFFFFFFFFFFL;
jtulach@1334
   526
jtulach@1334
   527
    private static double nextDouble (double d, boolean positive) {
jtulach@1334
   528
        if (Double.isNaN(d) || Double.isInfinite(d)) {
jtulach@1334
   529
                return d;
jtulach@1334
   530
            }
jtulach@1334
   531
        long bits = Double.doubleToLongBits(d);
jtulach@1334
   532
        long significand = bits & SIGNIFICAND;
jtulach@1334
   533
        if (bits < 0) {
jtulach@1334
   534
            significand |= (SIGN | EXPONENT);
jtulach@1334
   535
        }
jtulach@1334
   536
        long exponent = bits & EXPONENT;
jtulach@1334
   537
        if (positive) {
jtulach@1334
   538
            significand += 1;
jtulach@1334
   539
            // FIXME fix overflow & underflow
jtulach@1334
   540
        } else {
jtulach@1334
   541
            significand -= 1;
jtulach@1334
   542
            // FIXME fix overflow & underflow
jtulach@1334
   543
        }
jtulach@1334
   544
        bits = exponent | (significand & ~EXPONENT);
jtulach@1334
   545
        return Double.longBitsToDouble(bits);
jtulach@1334
   546
    }
jtulach@1334
   547
    */
jtulach@1334
   548
jtulach@1334
   549
    static final long SIGN                = 0x8000000000000000L;
jtulach@1334
   550
    static final long EXPONENT            = 0x7FF0000000000000L;
jtulach@1334
   551
    static final long POSITIVEINFINITY    = 0x7FF0000000000000L;
jtulach@1334
   552
jtulach@1334
   553
    /**
jtulach@1334
   554
     * Finds the least double greater than d (if positive == true),
jtulach@1334
   555
     * or the greatest double less than d (if positive == false).
jtulach@1334
   556
     * If NaN, returns same value.
jtulach@1334
   557
     *
jtulach@1334
   558
     * Does not affect floating-point flags,
jtulach@1334
   559
     * provided these member functions do not:
jtulach@1334
   560
     *          Double.longBitsToDouble(long)
jtulach@1334
   561
     *          Double.doubleToLongBits(double)
jtulach@1334
   562
     *          Double.isNaN(double)
jtulach@1334
   563
     */
jtulach@1334
   564
    public static double nextDouble (double d, boolean positive) {
jtulach@1334
   565
jtulach@1334
   566
        /* filter out NaN's */
jtulach@1334
   567
        if (Double.isNaN(d)) {
jtulach@1334
   568
            return d;
jtulach@1334
   569
        }
jtulach@1334
   570
jtulach@1334
   571
        /* zero's are also a special case */
jtulach@1334
   572
        if (d == 0.0) {
jtulach@1334
   573
            double smallestPositiveDouble = Double.longBitsToDouble(1L);
jtulach@1334
   574
            if (positive) {
jtulach@1334
   575
                return smallestPositiveDouble;
jtulach@1334
   576
            } else {
jtulach@1334
   577
                return -smallestPositiveDouble;
jtulach@1334
   578
            }
jtulach@1334
   579
        }
jtulach@1334
   580
jtulach@1334
   581
        /* if entering here, d is a nonzero value */
jtulach@1334
   582
jtulach@1334
   583
        /* hold all bits in a long for later use */
jtulach@1334
   584
        long bits = Double.doubleToLongBits(d);
jtulach@1334
   585
jtulach@1334
   586
        /* strip off the sign bit */
jtulach@1334
   587
        long magnitude = bits & ~SIGN;
jtulach@1334
   588
jtulach@1334
   589
        /* if next double away from zero, increase magnitude */
jtulach@1334
   590
        if ((bits > 0) == positive) {
jtulach@1334
   591
            if (magnitude != POSITIVEINFINITY) {
jtulach@1334
   592
                magnitude += 1;
jtulach@1334
   593
            }
jtulach@1334
   594
        }
jtulach@1334
   595
        /* else decrease magnitude */
jtulach@1334
   596
        else {
jtulach@1334
   597
            magnitude -= 1;
jtulach@1334
   598
        }
jtulach@1334
   599
jtulach@1334
   600
        /* restore sign bit and return */
jtulach@1334
   601
        long signbit = bits & SIGN;
jtulach@1334
   602
        return Double.longBitsToDouble (magnitude | signbit);
jtulach@1334
   603
    }
jtulach@1334
   604
jtulach@1334
   605
    private static double[] doubleArraySize(double[] array) {
jtulach@1334
   606
        int oldSize = array.length;
jtulach@1334
   607
        double[] newArray = new double[oldSize * 2];
jtulach@1334
   608
        System.arraycopy(array, 0, newArray, 0, oldSize);
jtulach@1334
   609
        return newArray;
jtulach@1334
   610
    }
jtulach@1334
   611
jtulach@1334
   612
    private String[] doubleArraySize(String[] array) {
jtulach@1334
   613
        int oldSize = array.length;
jtulach@1334
   614
        String[] newArray = new String[oldSize * 2];
jtulach@1334
   615
        System.arraycopy(array, 0, newArray, 0, oldSize);
jtulach@1334
   616
        return newArray;
jtulach@1334
   617
    }
jtulach@1334
   618
jtulach@1334
   619
}