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