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