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    // TODO(kevinb): remove null boilerplate (convert() will do it
345    // automatically)
346    protected Integer doForward(String value) {
347      return value == null ? null : Integer.decode(value);
348    }
349
350    @Override
351    protected String doBackward(Integer value) {
352      // TODO(kevinb): remove null boilerplate (convert() will do it
353      // automatically)
354      return value == null ? null : value.toString();
355    }
356
357    @Override
358    public String toString() {
359      return "Ints.stringConverter()";
360    }
361
362    private Object readResolve() {
363      return INSTANCE;
364    }
365    private static final long serialVersionUID = 1;
366  }
367
368  /**
369   * Returns a serializable converter object that converts between strings and
370   * integers using {@link Integer#decode} and {@link Integer#toString()}.
371   *
372   * @since 16.0
373   */
374  @Beta
375  public static Converter<String, Integer> stringConverter() {
376    return IntConverter.INSTANCE;
377  }
378
379  /**
380   * Returns an array containing the same values as {@code array}, but
381   * guaranteed to be of a specified minimum length. If {@code array} already
382   * has a length of at least {@code minLength}, it is returned directly.
383   * Otherwise, a new array of size {@code minLength + padding} is returned,
384   * containing the values of {@code array}, and zeroes in the remaining places.
385   *
386   * @param array the source array
387   * @param minLength the minimum length the returned array must guarantee
388   * @param padding an extra amount to "grow" the array by if growth is
389   *     necessary
390   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
391   *     negative
392   * @return an array containing the values of {@code array}, with guaranteed
393   *     minimum length {@code minLength}
394   */
395  public static int[] ensureCapacity(
396      int[] array, int minLength, int padding) {
397    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
398    checkArgument(padding >= 0, "Invalid padding: %s", padding);
399    return (array.length < minLength)
400        ? copyOf(array, minLength + padding)
401        : array;
402  }
403
404  // Arrays.copyOf() requires Java 6
405  private static int[] copyOf(int[] original, int length) {
406    int[] copy = new int[length];
407    System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
408    return copy;
409  }
410
411  /**
412   * Returns a string containing the supplied {@code int} values separated
413   * by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns
414   * the string {@code "1-2-3"}.
415   *
416   * @param separator the text that should appear between consecutive values in
417   *     the resulting string (but not at the start or end)
418   * @param array an array of {@code int} values, possibly empty
419   */
420  public static String join(String separator, int... array) {
421    checkNotNull(separator);
422    if (array.length == 0) {
423      return "";
424    }
425
426    // For pre-sizing a builder, just get the right order of magnitude
427    StringBuilder builder = new StringBuilder(array.length * 5);
428    builder.append(array[0]);
429    for (int i = 1; i < array.length; i++) {
430      builder.append(separator).append(array[i]);
431    }
432    return builder.toString();
433  }
434
435  /**
436   * Returns a comparator that compares two {@code int} arrays
437   * lexicographically. That is, it compares, using {@link
438   * #compare(int, int)}), the first pair of values that follow any
439   * common prefix, or when one array is a prefix of the other, treats the
440   * shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}.
441   *
442   * <p>The returned comparator is inconsistent with {@link
443   * Object#equals(Object)} (since arrays support only identity equality), but
444   * it is consistent with {@link Arrays#equals(int[], int[])}.
445   *
446   * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
447   *     Lexicographical order article at Wikipedia</a>
448   * @since 2.0
449   */
450  public static Comparator<int[]> lexicographicalComparator() {
451    return LexicographicalComparator.INSTANCE;
452  }
453
454  private enum LexicographicalComparator implements Comparator<int[]> {
455    INSTANCE;
456
457    @Override
458    public int compare(int[] left, int[] right) {
459      int minLength = Math.min(left.length, right.length);
460      for (int i = 0; i < minLength; i++) {
461        int result = Ints.compare(left[i], right[i]);
462        if (result != 0) {
463          return result;
464        }
465      }
466      return left.length - right.length;
467    }
468  }
469
470  /**
471   * Returns an array containing each value of {@code collection}, converted to
472   * a {@code int} value in the manner of {@link Number#intValue}.
473   *
474   * <p>Elements are copied from the argument collection as if by {@code
475   * collection.toArray()}.  Calling this method is as thread-safe as calling
476   * that method.
477   *
478   * @param collection a collection of {@code Number} instances
479   * @return an array containing the same values as {@code collection}, in the
480   *     same order, converted to primitives
481   * @throws NullPointerException if {@code collection} or any of its elements
482   *     is null
483   * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0)
484   */
485  public static int[] toArray(Collection<? extends Number> collection) {
486    if (collection instanceof IntArrayAsList) {
487      return ((IntArrayAsList) collection).toIntArray();
488    }
489
490    Object[] boxedArray = collection.toArray();
491    int len = boxedArray.length;
492    int[] array = new int[len];
493    for (int i = 0; i < len; i++) {
494      // checkNotNull for GWT (do not optimize)
495      array[i] = ((Number) checkNotNull(boxedArray[i])).intValue();
496    }
497    return array;
498  }
499
500  /**
501   * Returns a fixed-size list backed by the specified array, similar to {@link
502   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
503   * but any attempt to set a value to {@code null} will result in a {@link
504   * NullPointerException}.
505   *
506   * <p>The returned list maintains the values, but not the identities, of
507   * {@code Integer} objects written to or read from it.  For example, whether
508   * {@code list.get(0) == list.get(0)} is true for the returned list is
509   * unspecified.
510   *
511   * @param backingArray the array to back the list
512   * @return a list view of the array
513   */
514  public static List<Integer> asList(int... backingArray) {
515    if (backingArray.length == 0) {
516      return Collections.emptyList();
517    }
518    return new IntArrayAsList(backingArray);
519  }
520
521  @GwtCompatible
522  private static class IntArrayAsList extends AbstractList<Integer>
523      implements RandomAccess, Serializable {
524    final int[] array;
525    final int start;
526    final int end;
527
528    IntArrayAsList(int[] array) {
529      this(array, 0, array.length);
530    }
531
532    IntArrayAsList(int[] array, int start, int end) {
533      this.array = array;
534      this.start = start;
535      this.end = end;
536    }
537
538    @Override public int size() {
539      return end - start;
540    }
541
542    @Override public boolean isEmpty() {
543      return false;
544    }
545
546    @Override public Integer get(int index) {
547      checkElementIndex(index, size());
548      return array[start + index];
549    }
550
551    @Override public boolean contains(Object target) {
552      // Overridden to prevent a ton of boxing
553      return (target instanceof Integer)
554          && Ints.indexOf(array, (Integer) target, start, end) != -1;
555    }
556
557    @Override public int indexOf(Object target) {
558      // Overridden to prevent a ton of boxing
559      if (target instanceof Integer) {
560        int i = Ints.indexOf(array, (Integer) target, start, end);
561        if (i >= 0) {
562          return i - start;
563        }
564      }
565      return -1;
566    }
567
568    @Override public int lastIndexOf(Object target) {
569      // Overridden to prevent a ton of boxing
570      if (target instanceof Integer) {
571        int i = Ints.lastIndexOf(array, (Integer) target, start, end);
572        if (i >= 0) {
573          return i - start;
574        }
575      }
576      return -1;
577    }
578
579    @Override public Integer set(int index, Integer element) {
580      checkElementIndex(index, size());
581      int oldValue = array[start + index];
582      // checkNotNull for GWT (do not optimize)
583      array[start + index] = checkNotNull(element);
584      return oldValue;
585    }
586
587    @Override public List<Integer> subList(int fromIndex, int toIndex) {
588      int size = size();
589      checkPositionIndexes(fromIndex, toIndex, size);
590      if (fromIndex == toIndex) {
591        return Collections.emptyList();
592      }
593      return new IntArrayAsList(array, start + fromIndex, start + toIndex);
594    }
595
596    @Override public boolean equals(Object object) {
597      if (object == this) {
598        return true;
599      }
600      if (object instanceof IntArrayAsList) {
601        IntArrayAsList that = (IntArrayAsList) object;
602        int size = size();
603        if (that.size() != size) {
604          return false;
605        }
606        for (int i = 0; i < size; i++) {
607          if (array[start + i] != that.array[that.start + i]) {
608            return false;
609          }
610        }
611        return true;
612      }
613      return super.equals(object);
614    }
615
616    @Override public int hashCode() {
617      int result = 1;
618      for (int i = start; i < end; i++) {
619        result = 31 * result + Ints.hashCode(array[i]);
620      }
621      return result;
622    }
623
624    @Override public String toString() {
625      StringBuilder builder = new StringBuilder(size() * 5);
626      builder.append('[').append(array[start]);
627      for (int i = start + 1; i < end; i++) {
628        builder.append(", ").append(array[i]);
629      }
630      return builder.append(']').toString();
631    }
632
633    int[] toIntArray() {
634      // Arrays.copyOfRange() is not available under GWT
635      int size = size();
636      int[] result = new int[size];
637      System.arraycopy(array, start, result, 0, size);
638      return result;
639    }
640
641    private static final long serialVersionUID = 0;
642  }
643
644  /**
645   * Parses the specified string as a signed decimal integer value. The ASCII
646   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the
647   * minus sign.
648   *
649   * <p>Unlike {@link Integer#parseInt(String)}, this method returns
650   * {@code null} instead of throwing an exception if parsing fails.
651   *
652   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even
653   * under JDK 7, despite the change to {@link Integer#parseInt(String)} for
654   * that version.
655   *
656   * @param string the string representation of an integer value
657   * @return the integer value represented by {@code string}, or {@code null} if
658   *     {@code string} has a length of zero or cannot be parsed as an integer
659   *     value
660   * @since 11.0
661   */
662  @Beta
663  @CheckForNull
664  @GwtIncompatible("TODO")
665  public static Integer tryParse(String string) {
666    return AndroidInteger.tryParse(string, 10);
667  }
668}