001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.primitives; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkElementIndex; 019import static com.google.common.base.Preconditions.checkNotNull; 020import static com.google.common.base.Preconditions.checkPositionIndexes; 021import static com.google.common.base.Strings.lenientFormat; 022import static java.lang.Double.NEGATIVE_INFINITY; 023import static java.lang.Double.POSITIVE_INFINITY; 024 025import com.google.common.annotations.GwtCompatible; 026import com.google.common.annotations.GwtIncompatible; 027import com.google.common.annotations.J2ktIncompatible; 028import com.google.common.base.Converter; 029import java.io.Serializable; 030import java.util.AbstractList; 031import java.util.Arrays; 032import java.util.Collection; 033import java.util.Collections; 034import java.util.Comparator; 035import java.util.List; 036import java.util.RandomAccess; 037import javax.annotation.CheckForNull; 038 039/** 040 * Static utility methods pertaining to {@code double} primitives, that are not already found in 041 * either {@link Double} or {@link Arrays}. 042 * 043 * <p>See the Guava User Guide article on <a 044 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 045 * 046 * @author Kevin Bourrillion 047 * @since 1.0 048 */ 049@GwtCompatible(emulated = true) 050@ElementTypesAreNonnullByDefault 051public final class Doubles extends DoublesMethodsForWeb { 052 private Doubles() {} 053 054 /** 055 * The number of bytes required to represent a primitive {@code double} value. 056 * 057 * <p><b>Java 8 users:</b> use {@link Double#BYTES} instead. 058 * 059 * @since 10.0 060 */ 061 public static final int BYTES = Double.SIZE / Byte.SIZE; 062 063 /** 064 * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Double) 065 * value).hashCode()}. 066 * 067 * <p><b>Java 8 users:</b> use {@link Double#hashCode(double)} instead. 068 * 069 * @param value a primitive {@code double} value 070 * @return a hash code for the value 071 */ 072 public static int hashCode(double value) { 073 return ((Double) value).hashCode(); 074 // TODO(kevinb): do it this way when we can (GWT problem): 075 // long bits = Double.doubleToLongBits(value); 076 // return (int) (bits ^ (bits >>> 32)); 077 } 078 079 /** 080 * Compares the two specified {@code double} values. The sign of the value returned is the same as 081 * that of <code>((Double) a).{@linkplain Double#compareTo compareTo}(b)</code>. As with that 082 * method, {@code NaN} is treated as greater than all other values, and {@code 0.0 > -0.0}. 083 * 084 * <p><b>Note:</b> this method simply delegates to the JDK method {@link Double#compare}. It is 085 * provided for consistency with the other primitive types, whose compare methods were not added 086 * to the JDK until JDK 7. 087 * 088 * @param a the first {@code double} to compare 089 * @param b the second {@code double} to compare 090 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 091 * greater than {@code b}; or zero if they are equal 092 */ 093 public static int compare(double a, double b) { 094 return Double.compare(a, b); 095 } 096 097 /** 098 * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not 099 * necessarily implemented as, {@code !(Double.isInfinite(value) || Double.isNaN(value))}. 100 * 101 * <p><b>Java 8 users:</b> use {@link Double#isFinite(double)} instead. 102 * 103 * @since 10.0 104 */ 105 public static boolean isFinite(double value) { 106 return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY; 107 } 108 109 /** 110 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note 111 * that this always returns {@code false} when {@code target} is {@code NaN}. 112 * 113 * @param array an array of {@code double} values, possibly empty 114 * @param target a primitive {@code double} value 115 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 116 */ 117 public static boolean contains(double[] array, double target) { 118 for (double value : array) { 119 if (value == target) { 120 return true; 121 } 122 } 123 return false; 124 } 125 126 /** 127 * Returns the index of the first appearance of the value {@code target} in {@code array}. Note 128 * that this always returns {@code -1} when {@code target} is {@code NaN}. 129 * 130 * @param array an array of {@code double} values, possibly empty 131 * @param target a primitive {@code double} value 132 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 133 * such index exists. 134 */ 135 public static int indexOf(double[] array, double target) { 136 return indexOf(array, target, 0, array.length); 137 } 138 139 // TODO(kevinb): consider making this public 140 private static int indexOf(double[] array, double target, int start, int end) { 141 for (int i = start; i < end; i++) { 142 if (array[i] == target) { 143 return i; 144 } 145 } 146 return -1; 147 } 148 149 /** 150 * Returns the start position of the first occurrence of the specified {@code target} within 151 * {@code array}, or {@code -1} if there is no such occurrence. 152 * 153 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 154 * i, i + target.length)} contains exactly the same elements as {@code target}. 155 * 156 * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}. 157 * 158 * @param array the array to search for the sequence {@code target} 159 * @param target the array to search for as a sub-sequence of {@code array} 160 */ 161 public static int indexOf(double[] array, double[] target) { 162 checkNotNull(array, "array"); 163 checkNotNull(target, "target"); 164 if (target.length == 0) { 165 return 0; 166 } 167 168 outer: 169 for (int i = 0; i < array.length - target.length + 1; i++) { 170 for (int j = 0; j < target.length; j++) { 171 if (array[i + j] != target[j]) { 172 continue outer; 173 } 174 } 175 return i; 176 } 177 return -1; 178 } 179 180 /** 181 * Returns the index of the last appearance of the value {@code target} in {@code array}. Note 182 * that this always returns {@code -1} when {@code target} is {@code NaN}. 183 * 184 * @param array an array of {@code double} values, possibly empty 185 * @param target a primitive {@code double} value 186 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 187 * such index exists. 188 */ 189 public static int lastIndexOf(double[] array, double target) { 190 return lastIndexOf(array, target, 0, array.length); 191 } 192 193 // TODO(kevinb): consider making this public 194 private static int lastIndexOf(double[] array, double target, int start, int end) { 195 for (int i = end - 1; i >= start; i--) { 196 if (array[i] == target) { 197 return i; 198 } 199 } 200 return -1; 201 } 202 203 /** 204 * Returns the least value present in {@code array}, using the same rules of comparison as {@link 205 * Math#min(double, double)}. 206 * 207 * @param array a <i>nonempty</i> array of {@code double} values 208 * @return the value present in {@code array} that is less than or equal to every other value in 209 * the array 210 * @throws IllegalArgumentException if {@code array} is empty 211 */ 212 @GwtIncompatible( 213 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 214 public static double min(double... array) { 215 checkArgument(array.length > 0); 216 double min = array[0]; 217 for (int i = 1; i < array.length; i++) { 218 min = Math.min(min, array[i]); 219 } 220 return min; 221 } 222 223 /** 224 * Returns the greatest value present in {@code array}, using the same rules of comparison as 225 * {@link Math#max(double, double)}. 226 * 227 * @param array a <i>nonempty</i> array of {@code double} values 228 * @return the value present in {@code array} that is greater than or equal to every other value 229 * in the array 230 * @throws IllegalArgumentException if {@code array} is empty 231 */ 232 @GwtIncompatible( 233 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 234 public static double max(double... array) { 235 checkArgument(array.length > 0); 236 double max = array[0]; 237 for (int i = 1; i < array.length; i++) { 238 max = Math.max(max, array[i]); 239 } 240 return max; 241 } 242 243 /** 244 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 245 * 246 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 247 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code 248 * value} is greater than {@code max}, {@code max} is returned. 249 * 250 * @param value the {@code double} value to constrain 251 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 252 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 253 * @throws IllegalArgumentException if {@code min > max} 254 * @since 21.0 255 */ 256 public static double constrainToRange(double value, double min, double max) { 257 // avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984 258 // Reject NaN by testing for the good case (min <= max) instead of the bad (min > max). 259 if (min <= max) { 260 return Math.min(Math.max(value, min), max); 261 } 262 throw new IllegalArgumentException( 263 lenientFormat("min (%s) must be less than or equal to max (%s)", min, max)); 264 } 265 266 /** 267 * Returns the values from each provided array combined into a single array. For example, {@code 268 * concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array {@code {a, b, 269 * c}}. 270 * 271 * @param arrays zero or more {@code double} arrays 272 * @return a single array containing all the values from the source arrays, in order 273 */ 274 public static double[] concat(double[]... arrays) { 275 int length = 0; 276 for (double[] array : arrays) { 277 length += array.length; 278 } 279 double[] result = new double[length]; 280 int pos = 0; 281 for (double[] array : arrays) { 282 System.arraycopy(array, 0, result, pos, array.length); 283 pos += array.length; 284 } 285 return result; 286 } 287 288 private static final class DoubleConverter extends Converter<String, Double> 289 implements Serializable { 290 static final DoubleConverter INSTANCE = new DoubleConverter(); 291 292 @Override 293 protected Double doForward(String value) { 294 return Double.valueOf(value); 295 } 296 297 @Override 298 protected String doBackward(Double value) { 299 return value.toString(); 300 } 301 302 @Override 303 public String toString() { 304 return "Doubles.stringConverter()"; 305 } 306 307 private Object readResolve() { 308 return INSTANCE; 309 } 310 311 private static final long serialVersionUID = 1; 312 } 313 314 /** 315 * Returns a serializable converter object that converts between strings and doubles using {@link 316 * Double#valueOf} and {@link Double#toString()}. 317 * 318 * @since 16.0 319 */ 320 public static Converter<String, Double> stringConverter() { 321 return DoubleConverter.INSTANCE; 322 } 323 324 /** 325 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 326 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 327 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 328 * returned, containing the values of {@code array}, and zeroes in the remaining places. 329 * 330 * @param array the source array 331 * @param minLength the minimum length the returned array must guarantee 332 * @param padding an extra amount to "grow" the array by if growth is necessary 333 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 334 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 335 * minLength} 336 */ 337 public static double[] ensureCapacity(double[] array, int minLength, int padding) { 338 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 339 checkArgument(padding >= 0, "Invalid padding: %s", padding); 340 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 341 } 342 343 /** 344 * Returns a string containing the supplied {@code double} values, converted to strings as 345 * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example, 346 * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}. 347 * 348 * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT 349 * sometimes. In the previous example, it returns the string {@code "1-2-3"}. 350 * 351 * @param separator the text that should appear between consecutive values in the resulting string 352 * (but not at the start or end) 353 * @param array an array of {@code double} values, possibly empty 354 */ 355 public static String join(String separator, double... array) { 356 checkNotNull(separator); 357 if (array.length == 0) { 358 return ""; 359 } 360 361 // For pre-sizing a builder, just get the right order of magnitude 362 StringBuilder builder = new StringBuilder(array.length * 12); 363 builder.append(array[0]); 364 for (int i = 1; i < array.length; i++) { 365 builder.append(separator).append(array[i]); 366 } 367 return builder.toString(); 368 } 369 370 /** 371 * Returns a comparator that compares two {@code double} arrays <a 372 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 373 * compares, using {@link #compare(double, double)}), the first pair of values that follow any 374 * common prefix, or when one array is a prefix of the other, treats the shorter array as the 375 * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. 376 * 377 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 378 * support only identity equality), but it is consistent with {@link Arrays#equals(double[], 379 * double[])}. 380 * 381 * @since 2.0 382 */ 383 public static Comparator<double[]> lexicographicalComparator() { 384 return LexicographicalComparator.INSTANCE; 385 } 386 387 private enum LexicographicalComparator implements Comparator<double[]> { 388 INSTANCE; 389 390 @Override 391 public int compare(double[] left, double[] right) { 392 int minLength = Math.min(left.length, right.length); 393 for (int i = 0; i < minLength; i++) { 394 int result = Double.compare(left[i], right[i]); 395 if (result != 0) { 396 return result; 397 } 398 } 399 return left.length - right.length; 400 } 401 402 @Override 403 public String toString() { 404 return "Doubles.lexicographicalComparator()"; 405 } 406 } 407 408 /** 409 * Sorts the elements of {@code array} in descending order. 410 * 411 * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats 412 * all NaN values as equal and 0.0 as greater than -0.0. 413 * 414 * @since 23.1 415 */ 416 public static void sortDescending(double[] array) { 417 checkNotNull(array); 418 sortDescending(array, 0, array.length); 419 } 420 421 /** 422 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 423 * exclusive in descending order. 424 * 425 * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats 426 * all NaN values as equal and 0.0 as greater than -0.0. 427 * 428 * @since 23.1 429 */ 430 public static void sortDescending(double[] array, int fromIndex, int toIndex) { 431 checkNotNull(array); 432 checkPositionIndexes(fromIndex, toIndex, array.length); 433 Arrays.sort(array, fromIndex, toIndex); 434 reverse(array, fromIndex, toIndex); 435 } 436 437 /** 438 * Reverses the elements of {@code array}. This is equivalent to {@code 439 * Collections.reverse(Doubles.asList(array))}, but is likely to be more efficient. 440 * 441 * @since 23.1 442 */ 443 public static void reverse(double[] array) { 444 checkNotNull(array); 445 reverse(array, 0, array.length); 446 } 447 448 /** 449 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 450 * exclusive. This is equivalent to {@code 451 * Collections.reverse(Doubles.asList(array).subList(fromIndex, toIndex))}, but is likely to be 452 * more efficient. 453 * 454 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 455 * {@code toIndex > fromIndex} 456 * @since 23.1 457 */ 458 public static void reverse(double[] array, int fromIndex, int toIndex) { 459 checkNotNull(array); 460 checkPositionIndexes(fromIndex, toIndex, array.length); 461 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 462 double tmp = array[i]; 463 array[i] = array[j]; 464 array[j] = tmp; 465 } 466 } 467 468 /** 469 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 470 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 471 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array), 472 * distance)}, but is considerably faster and avoids allocation and garbage collection. 473 * 474 * <p>The provided "distance" may be negative, which will rotate left. 475 * 476 * @since 32.0.0 477 */ 478 public static void rotate(double[] array, int distance) { 479 rotate(array, distance, 0, array.length); 480 } 481 482 /** 483 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 484 * toIndex} exclusive. This is equivalent to {@code 485 * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is 486 * considerably faster and avoids allocations and garbage collection. 487 * 488 * <p>The provided "distance" may be negative, which will rotate left. 489 * 490 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 491 * {@code toIndex > fromIndex} 492 * @since 32.0.0 493 */ 494 public static void rotate(double[] array, int distance, int fromIndex, int toIndex) { 495 // See Ints.rotate for more details about possible algorithms here. 496 checkNotNull(array); 497 checkPositionIndexes(fromIndex, toIndex, array.length); 498 if (array.length <= 1) { 499 return; 500 } 501 502 int length = toIndex - fromIndex; 503 // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many 504 // places left to rotate. 505 int m = -distance % length; 506 m = (m < 0) ? m + length : m; 507 // The current index of what will become the first element of the rotated section. 508 int newFirstIndex = m + fromIndex; 509 if (newFirstIndex == fromIndex) { 510 return; 511 } 512 513 reverse(array, fromIndex, newFirstIndex); 514 reverse(array, newFirstIndex, toIndex); 515 reverse(array, fromIndex, toIndex); 516 } 517 518 /** 519 * Returns an array containing each value of {@code collection}, converted to a {@code double} 520 * value in the manner of {@link Number#doubleValue}. 521 * 522 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 523 * Calling this method is as thread-safe as calling that method. 524 * 525 * @param collection a collection of {@code Number} instances 526 * @return an array containing the same values as {@code collection}, in the same order, converted 527 * to primitives 528 * @throws NullPointerException if {@code collection} or any of its elements is null 529 * @since 1.0 (parameter was {@code Collection<Double>} before 12.0) 530 */ 531 public static double[] toArray(Collection<? extends Number> collection) { 532 if (collection instanceof DoubleArrayAsList) { 533 return ((DoubleArrayAsList) collection).toDoubleArray(); 534 } 535 536 Object[] boxedArray = collection.toArray(); 537 int len = boxedArray.length; 538 double[] array = new double[len]; 539 for (int i = 0; i < len; i++) { 540 // checkNotNull for GWT (do not optimize) 541 array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue(); 542 } 543 return array; 544 } 545 546 /** 547 * Returns a fixed-size list backed by the specified array, similar to {@link 548 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 549 * set a value to {@code null} will result in a {@link NullPointerException}. 550 * 551 * <p>The returned list maintains the values, but not the identities, of {@code Double} objects 552 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 553 * the returned list is unspecified. 554 * 555 * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN} 556 * is used as a parameter to any of its methods. 557 * 558 * <p>The returned list is serializable. 559 * 560 * <p><b>Note:</b> when possible, you should represent your data as an {@link 561 * ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view. 562 * 563 * @param backingArray the array to back the list 564 * @return a list view of the array 565 */ 566 public static List<Double> asList(double... backingArray) { 567 if (backingArray.length == 0) { 568 return Collections.emptyList(); 569 } 570 return new DoubleArrayAsList(backingArray); 571 } 572 573 @GwtCompatible 574 private static class DoubleArrayAsList extends AbstractList<Double> 575 implements RandomAccess, Serializable { 576 final double[] array; 577 final int start; 578 final int end; 579 580 DoubleArrayAsList(double[] array) { 581 this(array, 0, array.length); 582 } 583 584 DoubleArrayAsList(double[] array, int start, int end) { 585 this.array = array; 586 this.start = start; 587 this.end = end; 588 } 589 590 @Override 591 public int size() { 592 return end - start; 593 } 594 595 @Override 596 public boolean isEmpty() { 597 return false; 598 } 599 600 @Override 601 public Double get(int index) { 602 checkElementIndex(index, size()); 603 return array[start + index]; 604 } 605 606 @Override 607 public boolean contains(@CheckForNull Object target) { 608 // Overridden to prevent a ton of boxing 609 return (target instanceof Double) 610 && Doubles.indexOf(array, (Double) target, start, end) != -1; 611 } 612 613 @Override 614 public int indexOf(@CheckForNull Object target) { 615 // Overridden to prevent a ton of boxing 616 if (target instanceof Double) { 617 int i = Doubles.indexOf(array, (Double) target, start, end); 618 if (i >= 0) { 619 return i - start; 620 } 621 } 622 return -1; 623 } 624 625 @Override 626 public int lastIndexOf(@CheckForNull Object target) { 627 // Overridden to prevent a ton of boxing 628 if (target instanceof Double) { 629 int i = Doubles.lastIndexOf(array, (Double) target, start, end); 630 if (i >= 0) { 631 return i - start; 632 } 633 } 634 return -1; 635 } 636 637 @Override 638 public Double set(int index, Double element) { 639 checkElementIndex(index, size()); 640 double oldValue = array[start + index]; 641 // checkNotNull for GWT (do not optimize) 642 array[start + index] = checkNotNull(element); 643 return oldValue; 644 } 645 646 @Override 647 public List<Double> subList(int fromIndex, int toIndex) { 648 int size = size(); 649 checkPositionIndexes(fromIndex, toIndex, size); 650 if (fromIndex == toIndex) { 651 return Collections.emptyList(); 652 } 653 return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); 654 } 655 656 @Override 657 public boolean equals(@CheckForNull Object object) { 658 if (object == this) { 659 return true; 660 } 661 if (object instanceof DoubleArrayAsList) { 662 DoubleArrayAsList that = (DoubleArrayAsList) object; 663 int size = size(); 664 if (that.size() != size) { 665 return false; 666 } 667 for (int i = 0; i < size; i++) { 668 if (array[start + i] != that.array[that.start + i]) { 669 return false; 670 } 671 } 672 return true; 673 } 674 return super.equals(object); 675 } 676 677 @Override 678 public int hashCode() { 679 int result = 1; 680 for (int i = start; i < end; i++) { 681 result = 31 * result + Doubles.hashCode(array[i]); 682 } 683 return result; 684 } 685 686 @Override 687 public String toString() { 688 StringBuilder builder = new StringBuilder(size() * 12); 689 builder.append('[').append(array[start]); 690 for (int i = start + 1; i < end; i++) { 691 builder.append(", ").append(array[i]); 692 } 693 return builder.append(']').toString(); 694 } 695 696 double[] toDoubleArray() { 697 return Arrays.copyOfRange(array, start, end); 698 } 699 700 private static final long serialVersionUID = 0; 701 } 702 703 /** 704 * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating 705 * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs 706 * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug. 707 */ 708 @J2ktIncompatible @GwtIncompatible // regular expressions 709 static final 710 java.util.regex.Pattern 711 FLOATING_POINT_PATTERN = fpPattern(); 712 713 @GwtIncompatible // regular expressions 714 private static 715 java.util.regex.Pattern 716 fpPattern() { 717 /* 718 * We use # instead of * for possessive quantifiers. This lets us strip them out when building 719 * the regex for RE2 (which doesn't support them) but leave them in when building it for 720 * java.util.regex (where we want them in order to avoid catastrophic backtracking). 721 */ 722 String decimal = "(?:\\d+#(?:\\.\\d*#)?|\\.\\d+#)"; 723 String completeDec = decimal + "(?:[eE][+-]?\\d+#)?[fFdD]?"; 724 String hex = "(?:[0-9a-fA-F]+#(?:\\.[0-9a-fA-F]*#)?|\\.[0-9a-fA-F]+#)"; 725 String completeHex = "0[xX]" + hex + "[pP][+-]?\\d+#[fFdD]?"; 726 String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; 727 fpPattern = 728 fpPattern.replace( 729 "#", 730 "+" 731 ); 732 return 733 java.util.regex.Pattern 734 .compile(fpPattern); 735 } 736 737 /** 738 * Parses the specified string as a double-precision floating point value. The ASCII character 739 * {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. 740 * 741 * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of 742 * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link 743 * Double#valueOf(String)}, except that leading and trailing whitespace is not permitted. 744 * 745 * <p>This implementation is likely to be faster than {@code Double.parseDouble} if many failures 746 * are expected. 747 * 748 * @param string the string representation of a {@code double} value 749 * @return the floating point value represented by {@code string}, or {@code null} if {@code 750 * string} has a length of zero or cannot be parsed as a {@code double} value 751 * @throws NullPointerException if {@code string} is {@code null} 752 * @since 14.0 753 */ 754 @J2ktIncompatible 755 @GwtIncompatible // regular expressions 756 @CheckForNull 757 public static Double tryParse(String string) { 758 if (FLOATING_POINT_PATTERN.matcher(string).matches()) { 759 // TODO(lowasser): could be potentially optimized, but only with 760 // extensive testing 761 try { 762 return Double.parseDouble(string); 763 } catch (NumberFormatException e) { 764 // Double.parseDouble has changed specs several times, so fall through 765 // gracefully 766 } 767 } 768 return null; 769 } 770}