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