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