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