001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.primitives; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkElementIndex; 021import static com.google.common.base.Preconditions.checkNotNull; 022import static com.google.common.base.Preconditions.checkPositionIndexes; 023import static java.lang.Float.NEGATIVE_INFINITY; 024import static java.lang.Float.POSITIVE_INFINITY; 025 026import com.google.common.annotations.Beta; 027import com.google.common.annotations.GwtCompatible; 028import com.google.common.annotations.GwtIncompatible; 029import com.google.common.base.Converter; 030 031import java.io.Serializable; 032import java.util.AbstractList; 033import java.util.Arrays; 034import java.util.Collection; 035import java.util.Collections; 036import java.util.Comparator; 037import java.util.List; 038import java.util.RandomAccess; 039 040import javax.annotation.Nullable; 041 042/** 043 * Static utility methods pertaining to {@code float} primitives, that are not 044 * already found in either {@link Float} or {@link Arrays}. 045 * 046 * <p>See the Guava User Guide article on <a href= 047 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> 048 * primitive utilities</a>. 049 * 050 * @author Kevin Bourrillion 051 * @since 1.0 052 */ 053@GwtCompatible(emulated = true) 054public final class Floats { 055 private Floats() {} 056 057 /** 058 * The number of bytes required to represent a primitive {@code float} 059 * value. 060 * 061 * @since 10.0 062 */ 063 public static final int BYTES = Float.SIZE / Byte.SIZE; 064 065 /** 066 * Returns a hash code for {@code value}; equal to the result of invoking 067 * {@code ((Float) value).hashCode()}. 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 079 * Float#compare(float, float)}. You may prefer to invoke that method 080 * directly; this method exists only for consistency with the other utilities 081 * in this package. 082 * 083 * <p><b>Note:</b> this method simply delegates to the JDK method {@link 084 * Float#compare}. It is provided for consistency with the other primitive 085 * types, whose compare methods were not added to the JDK until JDK 7. 086 * 087 * @param a the first {@code float} to compare 088 * @param b the second {@code float} to compare 089 * @return the result of invoking {@link Float#compare(float, float)} 090 */ 091 // TODO(kevinb): if Ints.compare etc. are ever removed, remove this one too 092 public static int compare(float a, float b) { 093 return Float.compare(a, b); 094 } 095 096 /** 097 * Returns {@code true} if {@code value} represents a real number. This is 098 * equivalent to, but not necessarily implemented as, 099 * {@code !(Float.isInfinite(value) || Float.isNaN(value))}. 100 * 101 * @since 10.0 102 */ 103 public static boolean isFinite(float value) { 104 return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; 105 } 106 107 /** 108 * Returns {@code true} if {@code target} is present as an element anywhere in 109 * {@code array}. Note that this always returns {@code false} when {@code 110 * target} is {@code NaN}. 111 * 112 * @param array an array of {@code float} values, possibly empty 113 * @param target a primitive {@code float} value 114 * @return {@code true} if {@code array[i] == target} for some value of {@code 115 * i} 116 */ 117 public static boolean contains(float[] array, float target) { 118 for (float value : array) { 119 if (value == target) { 120 return true; 121 } 122 } 123 return false; 124 } 125 126 /** 127 * Returns the index of the first appearance of the value {@code target} in 128 * {@code array}. Note that this always returns {@code -1} when {@code target} 129 * is {@code NaN}. 130 * 131 * @param array an array of {@code float} values, possibly empty 132 * @param target a primitive {@code float} value 133 * @return the least index {@code i} for which {@code array[i] == target}, or 134 * {@code -1} if no such index exists. 135 */ 136 public static int indexOf(float[] array, float target) { 137 return indexOf(array, target, 0, array.length); 138 } 139 140 // TODO(kevinb): consider making this public 141 private static int indexOf( 142 float[] array, float target, int start, int end) { 143 for (int i = start; i < end; i++) { 144 if (array[i] == target) { 145 return i; 146 } 147 } 148 return -1; 149 } 150 151 /** 152 * Returns the start position of the first occurrence of the specified {@code 153 * target} within {@code array}, or {@code -1} if there is no such occurrence. 154 * 155 * <p>More formally, returns the lowest index {@code i} such that {@code 156 * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly 157 * the same elements as {@code target}. 158 * 159 * <p>Note that this always returns {@code -1} when {@code target} contains 160 * {@code NaN}. 161 * 162 * @param array the array to search for the sequence {@code target} 163 * @param target the array to search for as a sub-sequence of {@code array} 164 */ 165 public static int indexOf(float[] array, float[] target) { 166 checkNotNull(array, "array"); 167 checkNotNull(target, "target"); 168 if (target.length == 0) { 169 return 0; 170 } 171 172 outer: 173 for (int i = 0; i < array.length - target.length + 1; i++) { 174 for (int j = 0; j < target.length; j++) { 175 if (array[i + j] != target[j]) { 176 continue outer; 177 } 178 } 179 return i; 180 } 181 return -1; 182 } 183 184 /** 185 * Returns the index of the last appearance of the value {@code target} in 186 * {@code array}. Note that this always returns {@code -1} when {@code target} 187 * is {@code NaN}. 188 * 189 * @param array an array of {@code float} values, possibly empty 190 * @param target a primitive {@code float} value 191 * @return the greatest index {@code i} for which {@code array[i] == target}, 192 * or {@code -1} if no such index exists. 193 */ 194 public static int lastIndexOf(float[] array, float target) { 195 return lastIndexOf(array, target, 0, array.length); 196 } 197 198 // TODO(kevinb): consider making this public 199 private static int lastIndexOf( 200 float[] array, float target, int start, int end) { 201 for (int i = end - 1; i >= start; i--) { 202 if (array[i] == target) { 203 return i; 204 } 205 } 206 return -1; 207 } 208 209 /** 210 * Returns the least value present in {@code array}, using the same rules of 211 * comparison as {@link Math#min(float, float)}. 212 * 213 * @param array a <i>nonempty</i> array of {@code float} values 214 * @return the value present in {@code array} that is less than or equal to 215 * every other value in the array 216 * @throws IllegalArgumentException if {@code array} is empty 217 */ 218 public static float min(float... array) { 219 checkArgument(array.length > 0); 220 float min = array[0]; 221 for (int i = 1; i < array.length; i++) { 222 min = Math.min(min, array[i]); 223 } 224 return min; 225 } 226 227 /** 228 * Returns the greatest value present in {@code array}, using the same rules 229 * of comparison as {@link Math#min(float, float)}. 230 * 231 * @param array a <i>nonempty</i> array of {@code float} values 232 * @return the value present in {@code array} that is greater than or equal to 233 * every other value in the array 234 * @throws IllegalArgumentException if {@code array} is empty 235 */ 236 public static float max(float... array) { 237 checkArgument(array.length > 0); 238 float max = array[0]; 239 for (int i = 1; i < array.length; i++) { 240 max = Math.max(max, array[i]); 241 } 242 return max; 243 } 244 245 /** 246 * Returns the values from each provided array combined into a single array. 247 * For example, {@code concat(new float[] {a, b}, new float[] {}, new 248 * float[] {c}} returns the array {@code {a, b, c}}. 249 * 250 * @param arrays zero or more {@code float} arrays 251 * @return a single array containing all the values from the source arrays, in 252 * order 253 */ 254 public static float[] concat(float[]... arrays) { 255 int length = 0; 256 for (float[] array : arrays) { 257 length += array.length; 258 } 259 float[] result = new float[length]; 260 int pos = 0; 261 for (float[] array : arrays) { 262 System.arraycopy(array, 0, result, pos, array.length); 263 pos += array.length; 264 } 265 return result; 266 } 267 268 private static final class FloatConverter 269 extends Converter<String, Float> implements Serializable { 270 static final FloatConverter INSTANCE = new FloatConverter(); 271 272 @Override 273 protected Float doForward(String value) { 274 return Float.valueOf(value); 275 } 276 277 @Override 278 protected String doBackward(Float value) { 279 return value.toString(); 280 } 281 282 @Override 283 public String toString() { 284 return "Floats.stringConverter()"; 285 } 286 287 private Object readResolve() { 288 return INSTANCE; 289 } 290 private static final long serialVersionUID = 1; 291 } 292 293 /** 294 * Returns a serializable converter object that converts between strings and 295 * floats using {@link Float#valueOf} and {@link Float#toString()}. 296 * 297 * @since 16.0 298 */ 299 @Beta 300 public static Converter<String, Float> stringConverter() { 301 return FloatConverter.INSTANCE; 302 } 303 304 /** 305 * Returns an array containing the same values as {@code array}, but 306 * guaranteed to be of a specified minimum length. If {@code array} already 307 * has a length of at least {@code minLength}, it is returned directly. 308 * Otherwise, a new array of size {@code minLength + padding} is returned, 309 * containing the values of {@code array}, and zeroes in the remaining places. 310 * 311 * @param array the source array 312 * @param minLength the minimum length the returned array must guarantee 313 * @param padding an extra amount to "grow" the array by if growth is 314 * necessary 315 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is 316 * negative 317 * @return an array containing the values of {@code array}, with guaranteed 318 * minimum length {@code minLength} 319 */ 320 public static float[] ensureCapacity( 321 float[] array, int minLength, int padding) { 322 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 323 checkArgument(padding >= 0, "Invalid padding: %s", padding); 324 return (array.length < minLength) 325 ? copyOf(array, minLength + padding) 326 : array; 327 } 328 329 // Arrays.copyOf() requires Java 6 330 private static float[] copyOf(float[] original, int length) { 331 float[] copy = new float[length]; 332 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); 333 return copy; 334 } 335 336 /** 337 * Returns a string containing the supplied {@code float} values, converted 338 * to strings as specified by {@link Float#toString(float)}, and separated by 339 * {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)} 340 * returns the string {@code "1.0-2.0-3.0"}. 341 * 342 * <p>Note that {@link Float#toString(float)} formats {@code float} 343 * differently in GWT. In the previous example, it returns the string {@code 344 * "1-2-3"}. 345 * 346 * @param separator the text that should appear between consecutive values in 347 * the resulting string (but not at the start or end) 348 * @param array an array of {@code float} values, possibly empty 349 */ 350 public static String join(String separator, float... array) { 351 checkNotNull(separator); 352 if (array.length == 0) { 353 return ""; 354 } 355 356 // For pre-sizing a builder, just get the right order of magnitude 357 StringBuilder builder = new StringBuilder(array.length * 12); 358 builder.append(array[0]); 359 for (int i = 1; i < array.length; i++) { 360 builder.append(separator).append(array[i]); 361 } 362 return builder.toString(); 363 } 364 365 /** 366 * Returns a comparator that compares two {@code float} arrays 367 * lexicographically. That is, it compares, using {@link 368 * #compare(float, float)}), the first pair of values that follow any 369 * common prefix, or when one array is a prefix of the other, treats the 370 * shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] 371 * < [2.0f]}. 372 * 373 * <p>The returned comparator is inconsistent with {@link 374 * Object#equals(Object)} (since arrays support only identity equality), but 375 * it is consistent with {@link Arrays#equals(float[], float[])}. 376 * 377 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> 378 * Lexicographical order article at Wikipedia</a> 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 = Floats.compare(left[i], right[i]); 393 if (result != 0) { 394 return result; 395 } 396 } 397 return left.length - right.length; 398 } 399 } 400 401 /** 402 * Returns an array containing each value of {@code collection}, converted to 403 * a {@code float} 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 407 * that method. 408 * 409 * @param collection a collection of {@code Number} instances 410 * @return an array containing the same values as {@code collection}, in the 411 * same order, converted to primitives 412 * @throws NullPointerException if {@code collection} or any of its elements 413 * is null 414 * @since 1.0 (parameter was {@code Collection<Float>} before 12.0) 415 */ 416 public static float[] toArray(Collection<? extends Number> collection) { 417 if (collection instanceof FloatArrayAsList) { 418 return ((FloatArrayAsList) collection).toFloatArray(); 419 } 420 421 Object[] boxedArray = collection.toArray(); 422 int len = boxedArray.length; 423 float[] array = new float[len]; 424 for (int i = 0; i < len; i++) { 425 // checkNotNull for GWT (do not optimize) 426 array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue(); 427 } 428 return array; 429 } 430 431 /** 432 * Returns a fixed-size list backed by the specified array, similar to {@link 433 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, 434 * but any attempt to set a value to {@code null} will result in a {@link 435 * NullPointerException}. 436 * 437 * <p>The returned list maintains the values, but not the identities, of 438 * {@code Float} objects written to or read from it. For example, whether 439 * {@code list.get(0) == list.get(0)} is true for the returned list is 440 * unspecified. 441 * 442 * <p>The returned list may have unexpected behavior if it contains {@code 443 * NaN}, or if {@code NaN} is used as a parameter to any of its methods. 444 * 445 * @param backingArray the array to back the list 446 * @return a list view of the array 447 */ 448 public static List<Float> asList(float... backingArray) { 449 if (backingArray.length == 0) { 450 return Collections.emptyList(); 451 } 452 return new FloatArrayAsList(backingArray); 453 } 454 455 @GwtCompatible 456 private static class FloatArrayAsList extends AbstractList<Float> 457 implements RandomAccess, Serializable { 458 final float[] array; 459 final int start; 460 final int end; 461 462 FloatArrayAsList(float[] array) { 463 this(array, 0, array.length); 464 } 465 466 FloatArrayAsList(float[] array, int start, int end) { 467 this.array = array; 468 this.start = start; 469 this.end = end; 470 } 471 472 @Override public int size() { 473 return end - start; 474 } 475 476 @Override public boolean isEmpty() { 477 return false; 478 } 479 480 @Override public Float get(int index) { 481 checkElementIndex(index, size()); 482 return array[start + index]; 483 } 484 485 @Override public boolean contains(Object target) { 486 // Overridden to prevent a ton of boxing 487 return (target instanceof Float) 488 && Floats.indexOf(array, (Float) target, start, end) != -1; 489 } 490 491 @Override 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 public int lastIndexOf(Object target) { 503 // Overridden to prevent a ton of boxing 504 if (target instanceof Float) { 505 int i = Floats.lastIndexOf(array, (Float) target, start, end); 506 if (i >= 0) { 507 return i - start; 508 } 509 } 510 return -1; 511 } 512 513 @Override public Float set(int index, Float element) { 514 checkElementIndex(index, size()); 515 float oldValue = array[start + index]; 516 // checkNotNull for GWT (do not optimize) 517 array[start + index] = checkNotNull(element); 518 return oldValue; 519 } 520 521 @Override public List<Float> subList(int fromIndex, int toIndex) { 522 int size = size(); 523 checkPositionIndexes(fromIndex, toIndex, size); 524 if (fromIndex == toIndex) { 525 return Collections.emptyList(); 526 } 527 return new FloatArrayAsList(array, start + fromIndex, start + toIndex); 528 } 529 530 @Override public boolean equals(Object object) { 531 if (object == this) { 532 return true; 533 } 534 if (object instanceof FloatArrayAsList) { 535 FloatArrayAsList that = (FloatArrayAsList) object; 536 int size = size(); 537 if (that.size() != size) { 538 return false; 539 } 540 for (int i = 0; i < size; i++) { 541 if (array[start + i] != that.array[that.start + i]) { 542 return false; 543 } 544 } 545 return true; 546 } 547 return super.equals(object); 548 } 549 550 @Override public int hashCode() { 551 int result = 1; 552 for (int i = start; i < end; i++) { 553 result = 31 * result + Floats.hashCode(array[i]); 554 } 555 return result; 556 } 557 558 @Override public String toString() { 559 StringBuilder builder = new StringBuilder(size() * 12); 560 builder.append('[').append(array[start]); 561 for (int i = start + 1; i < end; i++) { 562 builder.append(", ").append(array[i]); 563 } 564 return builder.append(']').toString(); 565 } 566 567 float[] toFloatArray() { 568 // Arrays.copyOfRange() is not available under GWT 569 int size = size(); 570 float[] result = new float[size]; 571 System.arraycopy(array, start, result, 0, size); 572 return result; 573 } 574 575 private static final long serialVersionUID = 0; 576 } 577 578 /** 579 * Parses the specified string as a single-precision floating point value. 580 * The ASCII character {@code '-'} (<code>'\u002D'</code>) is recognized 581 * as the minus sign. 582 * 583 * <p>Unlike {@link Float#parseFloat(String)}, this method returns 584 * {@code null} instead of throwing an exception if parsing fails. 585 * Valid inputs are exactly those accepted by {@link Float#valueOf(String)}, 586 * 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 593 * {@code null} if {@code string} has a length of zero or cannot be 594 * parsed as a {@code float} value 595 * @since 14.0 596 */ 597 @GwtIncompatible("regular expressions") 598 @Nullable 599 @Beta 600 public static Float tryParse(String string) { 601 if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { 602 // TODO(user): 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}