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