1 /* 2 * Copyright (c) 1996, 2017, 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] ≤ X < 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>\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 id="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 * @exception NullPointerException if {@code newPattern} 176 * is {@code null} 177 */ 178 public void applyPattern(String newPattern) { 179 StringBuffer[] segments = new StringBuffer[2]; 180 for (int i = 0; i < segments.length; ++i) { 181 segments[i] = new StringBuffer(); 182 } 183 double[] newChoiceLimits = new double[30]; 184 String[] newChoiceFormats = new String[30]; 185 int count = 0; 186 int part = 0; 187 double startValue = 0; 188 double oldStartValue = Double.NaN; 189 boolean inQuote = false; 190 for (int i = 0; i < newPattern.length(); ++i) { 191 char ch = newPattern.charAt(i); 192 if (ch=='\'') { 193 // Check for "''" indicating a literal quote 194 if ((i+1)<newPattern.length() && newPattern.charAt(i+1)==ch) { 195 segments[part].append(ch); 196 ++i; 197 } else { 198 inQuote = !inQuote; 199 } 200 } else if (inQuote) { 201 segments[part].append(ch); 202 } else if (ch == '<' || ch == '#' || ch == '\u2264') { 203 if (segments[0].length() == 0) { 204 throw new IllegalArgumentException(); 205 } 206 try { 207 String tempBuffer = segments[0].toString(); 208 if (tempBuffer.equals("\u221E")) { 209 startValue = Double.POSITIVE_INFINITY; 210 } else if (tempBuffer.equals("-\u221E")) { 211 startValue = Double.NEGATIVE_INFINITY; 212 } else { 213 startValue = Double.valueOf(segments[0].toString()).doubleValue(); 214 } 215 } catch (Exception e) { 216 throw new IllegalArgumentException(); 217 } 218 if (ch == '<' && startValue != Double.POSITIVE_INFINITY && 219 startValue != Double.NEGATIVE_INFINITY) { 220 startValue = nextDouble(startValue); 221 } 222 if (startValue <= oldStartValue) { 223 throw new IllegalArgumentException(); 224 } 225 segments[0].setLength(0); 226 part = 1; 227 } else if (ch == '|') { 228 if (count == newChoiceLimits.length) { 229 newChoiceLimits = doubleArraySize(newChoiceLimits); 230 newChoiceFormats = doubleArraySize(newChoiceFormats); 231 } 232 newChoiceLimits[count] = startValue; 233 newChoiceFormats[count] = segments[1].toString(); 234 ++count; 235 oldStartValue = startValue; 236 segments[1].setLength(0); 237 part = 0; 238 } else { 239 segments[part].append(ch); 240 } 241 } 242 // clean up last one 243 if (part == 1) { 244 if (count == newChoiceLimits.length) { 245 newChoiceLimits = doubleArraySize(newChoiceLimits); 246 newChoiceFormats = doubleArraySize(newChoiceFormats); 247 } 248 newChoiceLimits[count] = startValue; 249 newChoiceFormats[count] = segments[1].toString(); 250 ++count; 251 } 252 choiceLimits = new double[count]; 253 System.arraycopy(newChoiceLimits, 0, choiceLimits, 0, count); 254 choiceFormats = new String[count]; 255 System.arraycopy(newChoiceFormats, 0, choiceFormats, 0, count); 256 } 257 258 /** 259 * Gets the pattern. 260 * 261 * @return the pattern string 262 */ 263 public String toPattern() { 264 StringBuilder result = new StringBuilder(); 265 for (int i = 0; i < choiceLimits.length; ++i) { 266 if (i != 0) { 267 result.append('|'); 268 } 269 // choose based upon which has less precision 270 // approximate that by choosing the closest one to an integer. 271 // could do better, but it's not worth it. 272 double less = previousDouble(choiceLimits[i]); 273 double tryLessOrEqual = Math.abs(Math.IEEEremainder(choiceLimits[i], 1.0d)); 274 double tryLess = Math.abs(Math.IEEEremainder(less, 1.0d)); 275 276 if (tryLessOrEqual < tryLess) { 277 result.append(choiceLimits[i]); 278 result.append('#'); 279 } else { 280 if (choiceLimits[i] == Double.POSITIVE_INFINITY) { 281 result.append("\u221E"); 282 } else if (choiceLimits[i] == Double.NEGATIVE_INFINITY) { 283 result.append("-\u221E"); 284 } else { 285 result.append(less); 286 } 287 result.append('<'); 288 } 289 // Append choiceFormats[i], using quotes if there are special characters. 290 // Single quotes themselves must be escaped in either case. 291 String text = choiceFormats[i]; 292 boolean needQuote = text.indexOf('<') >= 0 293 || text.indexOf('#') >= 0 294 || text.indexOf('\u2264') >= 0 295 || text.indexOf('|') >= 0; 296 if (needQuote) result.append('\''); 297 if (text.indexOf('\'') < 0) result.append(text); 298 else { 299 for (int j=0; j<text.length(); ++j) { 300 char c = text.charAt(j); 301 result.append(c); 302 if (c == '\'') result.append(c); 303 } 304 } 305 if (needQuote) result.append('\''); 306 } 307 return result.toString(); 308 } 309 310 /** 311 * Constructs with limits and corresponding formats based on the pattern. 312 * 313 * @param newPattern the new pattern string 314 * @exception NullPointerExcpetion if {@code newPattern} is 315 * {@code null} 316 * @see #applyPattern 317 */ 318 public ChoiceFormat(String newPattern) { 319 applyPattern(newPattern); 320 } 321 322 /** 323 * Constructs with the limits and the corresponding formats. 324 * 325 * @param limits limits in ascending order 326 * @param formats corresponding format strings 327 * @exception NullPointerException if {@code limits} or {@code formats} 328 * is {@code null} 329 * @see #setChoices 330 */ 331 public ChoiceFormat(double[] limits, String[] formats) { 332 setChoices(limits, formats); 333 } 334 335 /** 336 * Set the choices to be used in formatting. 337 * @param limits contains the top value that you want 338 * parsed with that format, and should be in ascending sorted order. When 339 * formatting X, the choice will be the i, where 340 * limit[i] ≤ X {@literal <} limit[i+1]. 341 * If the limit array is not in ascending order, the results of formatting 342 * will be incorrect. 343 * @param formats are the formats you want to use for each limit. 344 * They can be either Format objects or Strings. 345 * When formatting with object Y, 346 * if the object is a NumberFormat, then ((NumberFormat) Y).format(X) 347 * is called. Otherwise Y.toString() is called. 348 * @exception NullPointerException if {@code limits} or 349 * {@code formats} is {@code null} 350 */ 351 public void setChoices(double[] limits, String formats[]) { 352 if (limits.length != formats.length) { 353 throw new IllegalArgumentException( 354 "Array and limit arrays must be of the same length."); 355 } 356 choiceLimits = Arrays.copyOf(limits, limits.length); 357 choiceFormats = Arrays.copyOf(formats, formats.length); 358 } 359 360 /** 361 * Get the limits passed in the constructor. 362 * @return the limits. 363 */ 364 public double[] getLimits() { 365 double[] newLimits = Arrays.copyOf(choiceLimits, choiceLimits.length); 366 return newLimits; 367 } 368 369 /** 370 * Get the formats passed in the constructor. 371 * @return the formats. 372 */ 373 public Object[] getFormats() { 374 Object[] newFormats = Arrays.copyOf(choiceFormats, choiceFormats.length); 375 return newFormats; 376 } 377 378 // Overrides 379 380 /** 381 * Specialization of format. This method really calls 382 * <code>format(double, StringBuffer, FieldPosition)</code> 383 * thus the range of longs that are supported is only equal to 384 * the range that can be stored by double. This will never be 385 * a practical limitation. 386 */ 387 public StringBuffer format(long number, StringBuffer toAppendTo, 388 FieldPosition status) { 389 return format((double)number, toAppendTo, status); 390 } 391 392 /** 393 * Returns pattern with formatted double. 394 * @param number number to be formatted and substituted. 395 * @param toAppendTo where text is appended. 396 * @param status ignore no useful status is returned. 397 * @exception NullPointerException if {@code toAppendTo} 398 * is {@code null} 399 */ 400 public StringBuffer format(double number, StringBuffer toAppendTo, 401 FieldPosition status) { 402 // find the number 403 int i; 404 for (i = 0; i < choiceLimits.length; ++i) { 405 if (!(number >= choiceLimits[i])) { 406 // same as number < choiceLimits, except catchs NaN 407 break; 408 } 409 } 410 --i; 411 if (i < 0) i = 0; 412 // return either a formatted number, or a string 413 return toAppendTo.append(choiceFormats[i]); 414 } 415 416 /** 417 * Parses a Number from the input text. 418 * @param text the source text. 419 * @param status an input-output parameter. On input, the 420 * status.index field indicates the first character of the 421 * source text that should be parsed. On exit, if no error 422 * occurred, status.index is set to the first unparsed character 423 * in the source text. On exit, if an error did occur, 424 * status.index is unchanged and status.errorIndex is set to the 425 * first index of the character that caused the parse to fail. 426 * @return A Number representing the value of the number parsed. 427 * @exception NullPointerException if {@code status} is {@code null} 428 * or if {@code text} is {@code null} and the list of 429 * choice strings is not empty. 430 */ 431 public Number parse(String text, ParsePosition status) { 432 // find the best number (defined as the one with the longest parse) 433 int start = status.index; 434 int furthest = start; 435 double bestNumber = Double.NaN; 436 double tempNumber = 0.0; 437 for (int i = 0; i < choiceFormats.length; ++i) { 438 String tempString = choiceFormats[i]; 439 if (text.regionMatches(start, tempString, 0, tempString.length())) { 440 status.index = start + tempString.length(); 441 tempNumber = choiceLimits[i]; 442 if (status.index > furthest) { 443 furthest = status.index; 444 bestNumber = tempNumber; 445 if (furthest == text.length()) break; 446 } 447 } 448 } 449 status.index = furthest; 450 if (status.index == start) { 451 status.errorIndex = furthest; 452 } 453 return Double.valueOf(bestNumber); 454 } 455 456 /** 457 * Finds the least double greater than {@code d}. 458 * If {@code NaN}, returns same value. 459 * <p>Used to make half-open intervals. 460 * 461 * @param d the reference value 462 * @return the least double value greather than {@code d} 463 * @see #previousDouble 464 */ 465 public static final double nextDouble (double d) { 466 return nextDouble(d,true); 467 } 468 469 /** 470 * Finds the greatest double less than {@code d}. 471 * If {@code NaN}, returns same value. 472 * 473 * @param d the reference value 474 * @return the greatest double value less than {@code d} 475 * @see #nextDouble 476 */ 477 public static final double previousDouble (double d) { 478 return nextDouble(d,false); 479 } 480 481 /** 482 * Overrides Cloneable 483 */ 484 public Object clone() 485 { 486 ChoiceFormat other = (ChoiceFormat) super.clone(); 487 // for primitives or immutables, shallow clone is enough 488 other.choiceLimits = choiceLimits.clone(); 489 other.choiceFormats = choiceFormats.clone(); 490 return other; 491 } 492 493 /** 494 * Generates a hash code for the message format object. 495 */ 496 public int hashCode() { 497 int result = choiceLimits.length; 498 if (choiceFormats.length > 0) { 499 // enough for reasonable distribution 500 result ^= choiceFormats[choiceFormats.length-1].hashCode(); 501 } 502 return result; 503 } 504 505 /** 506 * Equality comparison between two 507 */ 508 public boolean equals(Object obj) { 509 if (obj == null) return false; 510 if (this == obj) // quick check 511 return true; 512 if (getClass() != obj.getClass()) 513 return false; 514 ChoiceFormat other = (ChoiceFormat) obj; 515 return (Arrays.equals(choiceLimits, other.choiceLimits) 516 && Arrays.equals(choiceFormats, other.choiceFormats)); 517 } 518 519 /** 520 * After reading an object from the input stream, do a simple verification 521 * to maintain class invariants. 522 * @throws InvalidObjectException if the objects read from the stream is invalid. 523 */ 524 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 525 in.defaultReadObject(); 526 if (choiceLimits.length != choiceFormats.length) { 527 throw new InvalidObjectException( 528 "limits and format arrays of different length."); 529 } 530 } 531 532 // ===============privates=========================== 533 534 /** 535 * A list of lower bounds for the choices. The formatter will return 536 * <code>choiceFormats[i]</code> if the number being formatted is greater than or equal to 537 * <code>choiceLimits[i]</code> and less than <code>choiceLimits[i+1]</code>. 538 * @serial 539 */ 540 private double[] choiceLimits; 541 542 /** 543 * A list of choice strings. The formatter will return 544 * <code>choiceFormats[i]</code> if the number being formatted is greater than or equal to 545 * <code>choiceLimits[i]</code> and less than <code>choiceLimits[i+1]</code>. 546 * @serial 547 */ 548 private String[] choiceFormats; 549 550 /* 551 static final long SIGN = 0x8000000000000000L; 552 static final long EXPONENT = 0x7FF0000000000000L; 553 static final long SIGNIFICAND = 0x000FFFFFFFFFFFFFL; 554 555 private static double nextDouble (double d, boolean positive) { 556 if (Double.isNaN(d) || Double.isInfinite(d)) { 557 return d; 558 } 559 long bits = Double.doubleToLongBits(d); 560 long significand = bits & SIGNIFICAND; 561 if (bits < 0) { 562 significand |= (SIGN | EXPONENT); 563 } 564 long exponent = bits & EXPONENT; 565 if (positive) { 566 significand += 1; 567 // FIXME fix overflow & underflow 568 } else { 569 significand -= 1; 570 // FIXME fix overflow & underflow 571 } 572 bits = exponent | (significand & ~EXPONENT); 573 return Double.longBitsToDouble(bits); 574 } 575 */ 576 577 static final long SIGN = 0x8000000000000000L; 578 static final long EXPONENT = 0x7FF0000000000000L; 579 static final long POSITIVEINFINITY = 0x7FF0000000000000L; 580 581 /** 582 * Finds the least double greater than {@code d} (if {@code positive} is 583 * {@code true}), or the greatest double less than {@code d} (if 584 * {@code positive} is {@code false}). 585 * If {@code NaN}, returns same value. 586 * 587 * Does not affect floating-point flags, 588 * provided these member functions do not: 589 * Double.longBitsToDouble(long) 590 * Double.doubleToLongBits(double) 591 * Double.isNaN(double) 592 * 593 * @param d the reference value 594 * @param positive {@code true} if the least double is desired; 595 * {@code false} otherwise 596 * @return the least or greater double value 597 */ 598 public static double nextDouble (double d, boolean positive) { 599 600 /* filter out NaN's */ 601 if (Double.isNaN(d)) { 602 return d; 603 } 604 605 /* zero's are also a special case */ 606 if (d == 0.0) { 607 double smallestPositiveDouble = Double.longBitsToDouble(1L); 608 if (positive) { 609 return smallestPositiveDouble; 610 } else { 611 return -smallestPositiveDouble; 612 } 613 } 614 615 /* if entering here, d is a nonzero value */ 616 617 /* hold all bits in a long for later use */ 618 long bits = Double.doubleToLongBits(d); 619 620 /* strip off the sign bit */ 621 long magnitude = bits & ~SIGN; 622 623 /* if next double away from zero, increase magnitude */ 624 if ((bits > 0) == positive) { 625 if (magnitude != POSITIVEINFINITY) { 626 magnitude += 1; 627 } 628 } 629 /* else decrease magnitude */ 630 else { 631 magnitude -= 1; 632 } 633 634 /* restore sign bit and return */ 635 long signbit = bits & SIGN; 636 return Double.longBitsToDouble (magnitude | signbit); 637 } 638 639 private static double[] doubleArraySize(double[] array) { 640 int oldSize = array.length; 641 double[] newArray = new double[oldSize * 2]; 642 System.arraycopy(array, 0, newArray, 0, oldSize); 643 return newArray; 644 } 645 646 private String[] doubleArraySize(String[] array) { 647 int oldSize = array.length; 648 String[] newArray = new String[oldSize * 2]; 649 System.arraycopy(array, 0, newArray, 0, oldSize); 650 return newArray; 651 } 652 653 }