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