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 javax.annotation.CheckForNull; 037import javax.annotation.Nullable; 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 044 * <a 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 { 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 064 * {@code ((Float) 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 108 * 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 113 * i} 114 */ 115 public static boolean contains(float[] array, float target) { 116 for (float value : array) { 117 if (value == target) { 118 return true; 119 } 120 } 121 return false; 122 } 123 124 /** 125 * Returns the index of the first appearance of the value {@code target} in {@code array}. Note 126 * that this always returns {@code -1} when {@code target} is {@code NaN}. 127 * 128 * @param array an array of {@code float} values, possibly empty 129 * @param target a primitive {@code float} value 130 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 131 * such index exists. 132 */ 133 public static int indexOf(float[] array, float target) { 134 return indexOf(array, target, 0, array.length); 135 } 136 137 // TODO(kevinb): consider making this public 138 private static int indexOf(float[] array, float target, int start, int end) { 139 for (int i = start; i < end; i++) { 140 if (array[i] == target) { 141 return i; 142 } 143 } 144 return -1; 145 } 146 147 /** 148 * Returns the start position of the first occurrence of the specified {@code 149 * target} within {@code array}, or {@code -1} if there is no such occurrence. 150 * 151 * <p>More formally, returns the lowest index {@code i} such that 152 * {@code Arrays.copyOfRange(array, i, i + target.length)} contains exactly the same elements as 153 * {@code target}. 154 * 155 * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}. 156 * 157 * @param array the array to search for the sequence {@code target} 158 * @param target the array to search for as a sub-sequence of {@code array} 159 */ 160 public static int indexOf(float[] array, float[] target) { 161 checkNotNull(array, "array"); 162 checkNotNull(target, "target"); 163 if (target.length == 0) { 164 return 0; 165 } 166 167 outer: 168 for (int i = 0; i < array.length - target.length + 1; i++) { 169 for (int j = 0; j < target.length; j++) { 170 if (array[i + j] != target[j]) { 171 continue outer; 172 } 173 } 174 return i; 175 } 176 return -1; 177 } 178 179 /** 180 * Returns the index of the last appearance of the value {@code target} in {@code array}. Note 181 * that this always returns {@code -1} when {@code target} is {@code NaN}. 182 * 183 * @param array an array of {@code float} values, possibly empty 184 * @param target a primitive {@code float} value 185 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 186 * such index exists. 187 */ 188 public static int lastIndexOf(float[] array, float target) { 189 return lastIndexOf(array, target, 0, array.length); 190 } 191 192 // TODO(kevinb): consider making this public 193 private static int lastIndexOf(float[] array, float target, int start, int end) { 194 for (int i = end - 1; i >= start; i--) { 195 if (array[i] == target) { 196 return i; 197 } 198 } 199 return -1; 200 } 201 202 /** 203 * Returns the least value present in {@code array}, using the same rules of comparison as 204 * {@link Math#min(float, float)}. 205 * 206 * @param array a <i>nonempty</i> array of {@code float} values 207 * @return the value present in {@code array} that is less than or equal to every other value in 208 * the array 209 * @throws IllegalArgumentException if {@code array} is empty 210 */ 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 public static float max(float... array) { 230 checkArgument(array.length > 0); 231 float max = array[0]; 232 for (int i = 1; i < array.length; i++) { 233 max = Math.max(max, array[i]); 234 } 235 return max; 236 } 237 238 /** 239 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 240 * 241 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 242 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if 243 * {@code value} is greater than {@code max}, {@code max} is returned. 244 * 245 * @param value the {@code float} value to constrain 246 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 247 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 248 * @throws IllegalArgumentException if {@code min > max} 249 * @since 21.0 250 */ 251 @Beta 252 public static float constrainToRange(float value, float min, float max) { 253 checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); 254 return Math.min(Math.max(value, min), max); 255 } 256 257 /** 258 * Returns the values from each provided array combined into a single array. For example, 259 * {@code concat(new float[] {a, b}, new float[] {}, new float[] {c}} returns the array {@code {a, 260 * b, c}}. 261 * 262 * @param arrays zero or more {@code float} arrays 263 * @return a single array containing all the values from the source arrays, in order 264 */ 265 public static float[] concat(float[]... arrays) { 266 int length = 0; 267 for (float[] array : arrays) { 268 length += array.length; 269 } 270 float[] result = new float[length]; 271 int pos = 0; 272 for (float[] array : arrays) { 273 System.arraycopy(array, 0, result, pos, array.length); 274 pos += array.length; 275 } 276 return result; 277 } 278 279 private static final class FloatConverter extends Converter<String, Float> 280 implements Serializable { 281 static final FloatConverter INSTANCE = new FloatConverter(); 282 283 @Override 284 protected Float doForward(String value) { 285 return Float.valueOf(value); 286 } 287 288 @Override 289 protected String doBackward(Float value) { 290 return value.toString(); 291 } 292 293 @Override 294 public String toString() { 295 return "Floats.stringConverter()"; 296 } 297 298 private Object readResolve() { 299 return INSTANCE; 300 } 301 302 private static final long serialVersionUID = 1; 303 } 304 305 /** 306 * Returns a serializable converter object that converts between strings and floats using 307 * {@link Float#valueOf} and {@link Float#toString()}. 308 * 309 * @since 16.0 310 */ 311 @Beta 312 public static Converter<String, Float> stringConverter() { 313 return FloatConverter.INSTANCE; 314 } 315 316 /** 317 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 318 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 319 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 320 * returned, containing the values of {@code array}, and zeroes in the remaining places. 321 * 322 * @param array the source array 323 * @param minLength the minimum length the returned array must guarantee 324 * @param padding an extra amount to "grow" the array by if growth is necessary 325 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 326 * @return an array containing the values of {@code array}, with guaranteed minimum length 327 * {@code minLength} 328 */ 329 public static float[] ensureCapacity(float[] array, int minLength, int padding) { 330 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 331 checkArgument(padding >= 0, "Invalid padding: %s", padding); 332 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 333 } 334 335 /** 336 * Returns a string containing the supplied {@code float} values, converted to strings as 337 * specified by {@link Float#toString(float)}, and separated by {@code separator}. For example, 338 * {@code join("-", 1.0f, 2.0f, 3.0f)} returns the string {@code "1.0-2.0-3.0"}. 339 * 340 * <p>Note that {@link Float#toString(float)} formats {@code float} differently in GWT. In the 341 * previous example, it returns the string {@code 342 * "1-2-3"}. 343 * 344 * @param separator the text that should appear between consecutive values in the resulting string 345 * (but not at the start or end) 346 * @param array an array of {@code float} values, possibly empty 347 */ 348 public static String join(String separator, float... array) { 349 checkNotNull(separator); 350 if (array.length == 0) { 351 return ""; 352 } 353 354 // For pre-sizing a builder, just get the right order of magnitude 355 StringBuilder builder = new StringBuilder(array.length * 12); 356 builder.append(array[0]); 357 for (int i = 1; i < array.length; i++) { 358 builder.append(separator).append(array[i]); 359 } 360 return builder.toString(); 361 } 362 363 /** 364 * Returns a comparator that compares two {@code float} arrays <a 365 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 366 * compares, using {@link #compare(float, float)}), the first pair of values that follow any 367 * common prefix, or when one array is a prefix of the other, treats the shorter array as the 368 * lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] < [2.0f]}. 369 * 370 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 371 * support only identity equality), but it is consistent with 372 * {@link Arrays#equals(float[], float[])}. 373 * 374 * @since 2.0 375 */ 376 public static Comparator<float[]> lexicographicalComparator() { 377 return LexicographicalComparator.INSTANCE; 378 } 379 380 private enum LexicographicalComparator implements Comparator<float[]> { 381 INSTANCE; 382 383 @Override 384 public int compare(float[] left, float[] right) { 385 int minLength = Math.min(left.length, right.length); 386 for (int i = 0; i < minLength; i++) { 387 int result = Float.compare(left[i], right[i]); 388 if (result != 0) { 389 return result; 390 } 391 } 392 return left.length - right.length; 393 } 394 395 @Override 396 public String toString() { 397 return "Floats.lexicographicalComparator()"; 398 } 399 } 400 401 /** 402 * Returns an array containing each value of {@code collection}, converted to a {@code float} 403 * value in the manner of {@link Number#floatValue}. 404 * 405 * <p>Elements are copied from the argument collection as if by {@code 406 * collection.toArray()}. Calling this method is as thread-safe as calling that method. 407 * 408 * @param collection a collection of {@code Number} instances 409 * @return an array containing the same values as {@code collection}, in the same order, converted 410 * to primitives 411 * @throws NullPointerException if {@code collection} or any of its elements is null 412 * @since 1.0 (parameter was {@code Collection<Float>} before 12.0) 413 */ 414 public static float[] toArray(Collection<? extends Number> collection) { 415 if (collection instanceof FloatArrayAsList) { 416 return ((FloatArrayAsList) collection).toFloatArray(); 417 } 418 419 Object[] boxedArray = collection.toArray(); 420 int len = boxedArray.length; 421 float[] array = new float[len]; 422 for (int i = 0; i < len; i++) { 423 // checkNotNull for GWT (do not optimize) 424 array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue(); 425 } 426 return array; 427 } 428 429 /** 430 * Returns a fixed-size list backed by the specified array, similar to 431 * {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any 432 * attempt to set a value to {@code null} will result in a {@link NullPointerException}. 433 * 434 * <p>The returned list maintains the values, but not the identities, of {@code Float} objects 435 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 436 * the returned list is unspecified. 437 * 438 * <p>The returned list may have unexpected behavior if it contains {@code 439 * NaN}, or if {@code NaN} is used as a parameter to any of its methods. 440 * 441 * @param backingArray the array to back the list 442 * @return a list view of the array 443 */ 444 public static List<Float> asList(float... backingArray) { 445 if (backingArray.length == 0) { 446 return Collections.emptyList(); 447 } 448 return new FloatArrayAsList(backingArray); 449 } 450 451 @GwtCompatible 452 private static class FloatArrayAsList extends AbstractList<Float> 453 implements RandomAccess, Serializable { 454 final float[] array; 455 final int start; 456 final int end; 457 458 FloatArrayAsList(float[] array) { 459 this(array, 0, array.length); 460 } 461 462 FloatArrayAsList(float[] array, int start, int end) { 463 this.array = array; 464 this.start = start; 465 this.end = end; 466 } 467 468 @Override 469 public int size() { 470 return end - start; 471 } 472 473 @Override 474 public boolean isEmpty() { 475 return false; 476 } 477 478 @Override 479 public Float get(int index) { 480 checkElementIndex(index, size()); 481 return array[start + index]; 482 } 483 484 @Override 485 public boolean contains(Object target) { 486 // Overridden to prevent a ton of boxing 487 return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; 488 } 489 490 @Override 491 public int indexOf(Object target) { 492 // Overridden to prevent a ton of boxing 493 if (target instanceof Float) { 494 int i = Floats.indexOf(array, (Float) target, start, end); 495 if (i >= 0) { 496 return i - start; 497 } 498 } 499 return -1; 500 } 501 502 @Override 503 public int lastIndexOf(Object target) { 504 // Overridden to prevent a ton of boxing 505 if (target instanceof Float) { 506 int i = Floats.lastIndexOf(array, (Float) target, start, end); 507 if (i >= 0) { 508 return i - start; 509 } 510 } 511 return -1; 512 } 513 514 @Override 515 public Float set(int index, Float element) { 516 checkElementIndex(index, size()); 517 float oldValue = array[start + index]; 518 // checkNotNull for GWT (do not optimize) 519 array[start + index] = checkNotNull(element); 520 return oldValue; 521 } 522 523 @Override 524 public List<Float> subList(int fromIndex, int toIndex) { 525 int size = size(); 526 checkPositionIndexes(fromIndex, toIndex, size); 527 if (fromIndex == toIndex) { 528 return Collections.emptyList(); 529 } 530 return new FloatArrayAsList(array, start + fromIndex, start + toIndex); 531 } 532 533 @Override 534 public boolean equals(@Nullable Object object) { 535 if (object == this) { 536 return true; 537 } 538 if (object instanceof FloatArrayAsList) { 539 FloatArrayAsList that = (FloatArrayAsList) object; 540 int size = size(); 541 if (that.size() != size) { 542 return false; 543 } 544 for (int i = 0; i < size; i++) { 545 if (array[start + i] != that.array[that.start + i]) { 546 return false; 547 } 548 } 549 return true; 550 } 551 return super.equals(object); 552 } 553 554 @Override 555 public int hashCode() { 556 int result = 1; 557 for (int i = start; i < end; i++) { 558 result = 31 * result + Floats.hashCode(array[i]); 559 } 560 return result; 561 } 562 563 @Override 564 public String toString() { 565 StringBuilder builder = new StringBuilder(size() * 12); 566 builder.append('[').append(array[start]); 567 for (int i = start + 1; i < end; i++) { 568 builder.append(", ").append(array[i]); 569 } 570 return builder.append(']').toString(); 571 } 572 573 float[] toFloatArray() { 574 return Arrays.copyOfRange(array, start, end); 575 } 576 577 private static final long serialVersionUID = 0; 578 } 579 580 /** 581 * Parses the specified string as a single-precision floating point value. The ASCII character 582 * {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. 583 * 584 * <p>Unlike {@link Float#parseFloat(String)}, this method returns {@code null} instead of 585 * throwing an exception if parsing fails. Valid inputs are exactly those accepted by 586 * {@link Float#valueOf(String)}, except that leading and trailing whitespace is not permitted. 587 * 588 * <p>This implementation is likely to be faster than {@code 589 * Float.parseFloat} if many failures are expected. 590 * 591 * @param string the string representation of a {@code float} value 592 * @return the floating point value represented by {@code string}, or {@code null} if 593 * {@code string} has a length of zero or cannot be parsed as a {@code float} value 594 * @since 14.0 595 */ 596 @Beta 597 @Nullable 598 @CheckForNull 599 @GwtIncompatible // regular expressions 600 public static Float tryParse(String string) { 601 if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { 602 // TODO(lowasser): could be potentially optimized, but only with 603 // extensive testing 604 try { 605 return Float.parseFloat(string); 606 } catch (NumberFormatException e) { 607 // Float.parseFloat has changed specs several times, so fall through 608 // gracefully 609 } 610 } 611 return null; 612 } 613}