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 017 package com.google.common.primitives; 018 019 import static com.google.common.base.Preconditions.checkArgument; 020 import static com.google.common.base.Preconditions.checkElementIndex; 021 import static com.google.common.base.Preconditions.checkNotNull; 022 import static com.google.common.base.Preconditions.checkPositionIndexes; 023 024 import com.google.common.annotations.GwtCompatible; 025 import com.google.common.annotations.GwtIncompatible; 026 027 import java.io.Serializable; 028 import java.util.AbstractList; 029 import java.util.Arrays; 030 import java.util.Collection; 031 import java.util.Collections; 032 import java.util.Comparator; 033 import java.util.List; 034 import java.util.RandomAccess; 035 036 /** 037 * Static utility methods pertaining to {@code int} primitives, that are not 038 * already found in either {@link Integer} or {@link Arrays}. 039 * 040 * @author Kevin Bourrillion 041 * @since 1 042 */ 043 @GwtCompatible(emulated = true) 044 public final class Ints { 045 private Ints() {} 046 047 /** 048 * The number of bytes required to represent a primitive {@code int} 049 * value. 050 */ 051 public static final int BYTES = Integer.SIZE / Byte.SIZE; 052 053 /** 054 * Returns a hash code for {@code value}; equal to the result of invoking 055 * {@code ((Integer) value).hashCode()}. 056 * 057 * @param value a primitive {@code int} value 058 * @return a hash code for the value 059 */ 060 public static int hashCode(int value) { 061 return value; 062 } 063 064 /** 065 * Returns the {@code int} value that is equal to {@code value}, if possible. 066 * 067 * @param value any value in the range of the {@code int} type 068 * @return the {@code int} value that equals {@code value} 069 * @throws IllegalArgumentException if {@code value} is greater than {@link 070 * Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE} 071 */ 072 public static int checkedCast(long value) { 073 int result = (int) value; 074 checkArgument(result == value, "Out of range: %s", value); 075 return result; 076 } 077 078 /** 079 * Returns the {@code int} nearest in value to {@code value}. 080 * 081 * @param value any {@code long} value 082 * @return the same value cast to {@code int} if it is in the range of the 083 * {@code int} type, {@link Integer#MAX_VALUE} if it is too large, 084 * or {@link Integer#MIN_VALUE} if it is too small 085 */ 086 public static int saturatedCast(long value) { 087 if (value > Integer.MAX_VALUE) { 088 return Integer.MAX_VALUE; 089 } 090 if (value < Integer.MIN_VALUE) { 091 return Integer.MIN_VALUE; 092 } 093 return (int) value; 094 } 095 096 /** 097 * Compares the two specified {@code int} values. The sign of the value 098 * returned is the same as that of {@code ((Integer) a).compareTo(b)}. 099 * 100 * @param a the first {@code int} to compare 101 * @param b the second {@code int} to compare 102 * @return a negative value if {@code a} is less than {@code b}; a positive 103 * value if {@code a} is greater than {@code b}; or zero if they are equal 104 */ 105 public static int compare(int a, int b) { 106 return (a < b) ? -1 : ((a > b) ? 1 : 0); 107 } 108 109 /** 110 * Returns {@code true} if {@code target} is present as an element anywhere in 111 * {@code array}. 112 * 113 * @param array an array of {@code int} values, possibly empty 114 * @param target a primitive {@code int} value 115 * @return {@code true} if {@code array[i] == target} for some value of {@code 116 * i} 117 */ 118 public static boolean contains(int[] array, int target) { 119 for (int value : array) { 120 if (value == target) { 121 return true; 122 } 123 } 124 return false; 125 } 126 127 /** 128 * Returns the index of the first appearance of the value {@code target} in 129 * {@code array}. 130 * 131 * @param array an array of {@code int} values, possibly empty 132 * @param target a primitive {@code int} 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(int[] array, int target) { 137 return indexOf(array, target, 0, array.length); 138 } 139 140 // TODO(kevinb): consider making this public 141 private static int indexOf( 142 int[] array, int 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 * @param array the array to search for the sequence {@code target} 160 * @param target the array to search for as a sub-sequence of {@code array} 161 */ 162 public static int indexOf(int[] array, int[] target) { 163 checkNotNull(array, "array"); 164 checkNotNull(target, "target"); 165 if (target.length == 0) { 166 return 0; 167 } 168 169 outer: 170 for (int i = 0; i < array.length - target.length + 1; i++) { 171 for (int j = 0; j < target.length; j++) { 172 if (array[i + j] != target[j]) { 173 continue outer; 174 } 175 } 176 return i; 177 } 178 return -1; 179 } 180 181 /** 182 * Returns the index of the last appearance of the value {@code target} in 183 * {@code array}. 184 * 185 * @param array an array of {@code int} values, possibly empty 186 * @param target a primitive {@code int} value 187 * @return the greatest index {@code i} for which {@code array[i] == target}, 188 * or {@code -1} if no such index exists. 189 */ 190 public static int lastIndexOf(int[] array, int target) { 191 return lastIndexOf(array, target, 0, array.length); 192 } 193 194 // TODO(kevinb): consider making this public 195 private static int lastIndexOf( 196 int[] array, int target, int start, int end) { 197 for (int i = end - 1; i >= start; i--) { 198 if (array[i] == target) { 199 return i; 200 } 201 } 202 return -1; 203 } 204 205 /** 206 * Returns the least value present in {@code array}. 207 * 208 * @param array a <i>nonempty</i> array of {@code int} values 209 * @return the value present in {@code array} that is less than or equal to 210 * every other value in the array 211 * @throws IllegalArgumentException if {@code array} is empty 212 */ 213 public static int min(int... array) { 214 checkArgument(array.length > 0); 215 int min = array[0]; 216 for (int i = 1; i < array.length; i++) { 217 if (array[i] < min) { 218 min = array[i]; 219 } 220 } 221 return min; 222 } 223 224 /** 225 * Returns the greatest value present in {@code array}. 226 * 227 * @param array a <i>nonempty</i> array of {@code int} values 228 * @return the value present in {@code array} that is greater than or equal to 229 * every other value in the array 230 * @throws IllegalArgumentException if {@code array} is empty 231 */ 232 public static int max(int... array) { 233 checkArgument(array.length > 0); 234 int max = array[0]; 235 for (int i = 1; i < array.length; i++) { 236 if (array[i] > max) { 237 max = array[i]; 238 } 239 } 240 return max; 241 } 242 243 /** 244 * Returns the values from each provided array combined into a single array. 245 * For example, {@code concat(new int[] {a, b}, new int[] {}, new 246 * int[] {c}} returns the array {@code {a, b, c}}. 247 * 248 * @param arrays zero or more {@code int} arrays 249 * @return a single array containing all the values from the source arrays, in 250 * order 251 */ 252 public static int[] concat(int[]... arrays) { 253 int length = 0; 254 for (int[] array : arrays) { 255 length += array.length; 256 } 257 int[] result = new int[length]; 258 int pos = 0; 259 for (int[] array : arrays) { 260 System.arraycopy(array, 0, result, pos, array.length); 261 pos += array.length; 262 } 263 return result; 264 } 265 266 /** 267 * Returns a big-endian representation of {@code value} in a 4-element byte 268 * array; equivalent to {@code ByteBuffer.allocate(4).putInt(value).array()}. 269 * For example, the input value {@code 0x12131415} would yield the byte array 270 * {@code {0x12, 0x13, 0x14, 0x15}}. 271 * 272 * <p>If you need to convert and concatenate several values (possibly even of 273 * different types), use a shared {@link java.nio.ByteBuffer} instance, or use 274 * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable 275 * buffer. 276 */ 277 @GwtIncompatible("doesn't work") 278 public static byte[] toByteArray(int value) { 279 return new byte[] { 280 (byte) (value >> 24), 281 (byte) (value >> 16), 282 (byte) (value >> 8), 283 (byte) value}; 284 } 285 286 /** 287 * Returns the {@code int} value whose big-endian representation is stored in 288 * the first 4 bytes of {@code bytes}; equivalent to {@code 289 * ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array {@code 290 * {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code 291 * 0x12131415}. 292 * 293 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that 294 * library exposes much more flexibility at little cost in readability. 295 * 296 * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements 297 */ 298 @GwtIncompatible("doesn't work") 299 public static int fromByteArray(byte[] bytes) { 300 checkArgument(bytes.length >= BYTES, 301 "array too small: %s < %s", bytes.length, BYTES); 302 return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); 303 } 304 305 /** 306 * Returns the {@code int} value whose byte representation is the given 4 307 * bytes, in big-endian order; equivalent to {@code Ints.fromByteArray(new 308 * byte[] {b1, b2, b3, b4})}. 309 * 310 * @since 7 311 */ 312 @GwtIncompatible("doesn't work") 313 public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { 314 return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); 315 } 316 317 /** 318 * Returns an array containing the same values as {@code array}, but 319 * guaranteed to be of a specified minimum length. If {@code array} already 320 * has a length of at least {@code minLength}, it is returned directly. 321 * Otherwise, a new array of size {@code minLength + padding} is returned, 322 * containing the values of {@code array}, and zeroes in the remaining places. 323 * 324 * @param array the source array 325 * @param minLength the minimum length the returned array must guarantee 326 * @param padding an extra amount to "grow" the array by if growth is 327 * necessary 328 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is 329 * negative 330 * @return an array containing the values of {@code array}, with guaranteed 331 * minimum length {@code minLength} 332 */ 333 public static int[] ensureCapacity( 334 int[] array, int minLength, int padding) { 335 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 336 checkArgument(padding >= 0, "Invalid padding: %s", padding); 337 return (array.length < minLength) 338 ? copyOf(array, minLength + padding) 339 : array; 340 } 341 342 // Arrays.copyOf() requires Java 6 343 private static int[] copyOf(int[] original, int length) { 344 int[] copy = new int[length]; 345 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); 346 return copy; 347 } 348 349 /** 350 * Returns a string containing the supplied {@code int} values separated 351 * by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns 352 * the string {@code "1-2-3"}. 353 * 354 * @param separator the text that should appear between consecutive values in 355 * the resulting string (but not at the start or end) 356 * @param array an array of {@code int} values, possibly empty 357 */ 358 public static String join(String separator, int... array) { 359 checkNotNull(separator); 360 if (array.length == 0) { 361 return ""; 362 } 363 364 // For pre-sizing a builder, just get the right order of magnitude 365 StringBuilder builder = new StringBuilder(array.length * 5); 366 builder.append(array[0]); 367 for (int i = 1; i < array.length; i++) { 368 builder.append(separator).append(array[i]); 369 } 370 return builder.toString(); 371 } 372 373 /** 374 * Returns a comparator that compares two {@code int} arrays 375 * lexicographically. That is, it compares, using {@link 376 * #compare(int, int)}), the first pair of values that follow any 377 * common prefix, or when one array is a prefix of the other, treats the 378 * shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}. 379 * 380 * <p>The returned comparator is inconsistent with {@link 381 * Object#equals(Object)} (since arrays support only identity equality), but 382 * it is consistent with {@link Arrays#equals(int[], int[])}. 383 * 384 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> 385 * Lexicographical order article at Wikipedia</a> 386 * @since 2 387 */ 388 public static Comparator<int[]> lexicographicalComparator() { 389 return LexicographicalComparator.INSTANCE; 390 } 391 392 private enum LexicographicalComparator implements Comparator<int[]> { 393 INSTANCE; 394 395 @Override 396 public int compare(int[] left, int[] right) { 397 int minLength = Math.min(left.length, right.length); 398 for (int i = 0; i < minLength; i++) { 399 int result = Ints.compare(left[i], right[i]); 400 if (result != 0) { 401 return result; 402 } 403 } 404 return left.length - right.length; 405 } 406 } 407 408 /** 409 * Copies a collection of {@code Integer} instances into a new array of 410 * primitive {@code int} values. 411 * 412 * <p>Elements are copied from the argument collection as if by {@code 413 * collection.toArray()}. Calling this method is as thread-safe as calling 414 * that method. 415 * 416 * @param collection a collection of {@code Integer} objects 417 * @return an array containing the same values as {@code collection}, in the 418 * same order, converted to primitives 419 * @throws NullPointerException if {@code collection} or any of its elements 420 * is null 421 */ 422 public static int[] toArray(Collection<Integer> collection) { 423 if (collection instanceof IntArrayAsList) { 424 return ((IntArrayAsList) collection).toIntArray(); 425 } 426 427 Object[] boxedArray = collection.toArray(); 428 int len = boxedArray.length; 429 int[] array = new int[len]; 430 for (int i = 0; i < len; i++) { 431 array[i] = (Integer) boxedArray[i]; 432 } 433 return array; 434 } 435 436 /** 437 * Returns a fixed-size list backed by the specified array, similar to {@link 438 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, 439 * but any attempt to set a value to {@code null} will result in a {@link 440 * NullPointerException}. 441 * 442 * <p>The returned list maintains the values, but not the identities, of 443 * {@code Integer} objects written to or read from it. For example, whether 444 * {@code list.get(0) == list.get(0)} is true for the returned list is 445 * unspecified. 446 * 447 * @param backingArray the array to back the list 448 * @return a list view of the array 449 */ 450 public static List<Integer> asList(int... backingArray) { 451 if (backingArray.length == 0) { 452 return Collections.emptyList(); 453 } 454 return new IntArrayAsList(backingArray); 455 } 456 457 @GwtCompatible 458 private static class IntArrayAsList extends AbstractList<Integer> 459 implements RandomAccess, Serializable { 460 final int[] array; 461 final int start; 462 final int end; 463 464 IntArrayAsList(int[] array) { 465 this(array, 0, array.length); 466 } 467 468 IntArrayAsList(int[] array, int start, int end) { 469 this.array = array; 470 this.start = start; 471 this.end = end; 472 } 473 474 @Override public int size() { 475 return end - start; 476 } 477 478 @Override public boolean isEmpty() { 479 return false; 480 } 481 482 @Override public Integer get(int index) { 483 checkElementIndex(index, size()); 484 return array[start + index]; 485 } 486 487 @Override public boolean contains(Object target) { 488 // Overridden to prevent a ton of boxing 489 return (target instanceof Integer) 490 && Ints.indexOf(array, (Integer) target, start, end) != -1; 491 } 492 493 @Override public int indexOf(Object target) { 494 // Overridden to prevent a ton of boxing 495 if (target instanceof Integer) { 496 int i = Ints.indexOf(array, (Integer) target, start, end); 497 if (i >= 0) { 498 return i - start; 499 } 500 } 501 return -1; 502 } 503 504 @Override public int lastIndexOf(Object target) { 505 // Overridden to prevent a ton of boxing 506 if (target instanceof Integer) { 507 int i = Ints.lastIndexOf(array, (Integer) target, start, end); 508 if (i >= 0) { 509 return i - start; 510 } 511 } 512 return -1; 513 } 514 515 @Override public Integer set(int index, Integer element) { 516 checkElementIndex(index, size()); 517 int oldValue = array[start + index]; 518 array[start + index] = element; 519 return oldValue; 520 } 521 522 @Override public List<Integer> subList(int fromIndex, int toIndex) { 523 int size = size(); 524 checkPositionIndexes(fromIndex, toIndex, size); 525 if (fromIndex == toIndex) { 526 return Collections.emptyList(); 527 } 528 return new IntArrayAsList(array, start + fromIndex, start + toIndex); 529 } 530 531 @Override public boolean equals(Object object) { 532 if (object == this) { 533 return true; 534 } 535 if (object instanceof IntArrayAsList) { 536 IntArrayAsList that = (IntArrayAsList) object; 537 int size = size(); 538 if (that.size() != size) { 539 return false; 540 } 541 for (int i = 0; i < size; i++) { 542 if (array[start + i] != that.array[that.start + i]) { 543 return false; 544 } 545 } 546 return true; 547 } 548 return super.equals(object); 549 } 550 551 @Override public int hashCode() { 552 int result = 1; 553 for (int i = start; i < end; i++) { 554 result = 31 * result + Ints.hashCode(array[i]); 555 } 556 return result; 557 } 558 559 @Override public String toString() { 560 StringBuilder builder = new StringBuilder(size() * 5); 561 builder.append('[').append(array[start]); 562 for (int i = start + 1; i < end; i++) { 563 builder.append(", ").append(array[i]); 564 } 565 return builder.append(']').toString(); 566 } 567 568 int[] toIntArray() { 569 // Arrays.copyOfRange() requires Java 6 570 int size = size(); 571 int[] result = new int[size]; 572 System.arraycopy(array, start, result, 0, size); 573 return result; 574 } 575 576 private static final long serialVersionUID = 0; 577 } 578 }