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