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;
039import javax.annotation.CheckReturnValue;
040import javax.annotation.Nullable;
041
042/**
043 * Static utility methods pertaining to {@code int} primitives, that are not
044 * already found in either {@link Integer} or {@link Arrays}.
045 *
046 * <p>See the Guava User Guide article on <a href=
047 * "https://github.com/google/guava/wiki/PrimitivesExplained">
048 * primitive utilities</a>.
049 *
050 * @author Kevin Bourrillion
051 * @since 1.0
052 */
053@CheckReturnValue
054@GwtCompatible(emulated = true)
055public final class Ints {
056  private Ints() {}
057
058  /**
059   * The number of bytes required to represent a primitive {@code int}
060   * value.
061   */
062  public static final int BYTES = Integer.SIZE / Byte.SIZE;
063
064  /**
065   * The largest power of two that can be represented as an {@code int}.
066   *
067   * @since 10.0
068   */
069  public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
070
071  /**
072   * Returns a hash code for {@code value}; equal to the result of invoking
073   * {@code ((Integer) value).hashCode()}.
074   *
075   * @param value a primitive {@code int} value
076   * @return a hash code for the value
077   */
078  public static int hashCode(int value) {
079    return value;
080  }
081
082  /**
083   * Returns the {@code int} value that is equal to {@code value}, if possible.
084   *
085   * @param value any value in the range of the {@code int} type
086   * @return the {@code int} value that equals {@code value}
087   * @throws IllegalArgumentException if {@code value} is greater than {@link
088   *     Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE}
089   */
090  public static int checkedCast(long value) {
091    int result = (int) value;
092    if (result != value) {
093      // don't use checkArgument here, to avoid boxing
094      throw new IllegalArgumentException("Out of range: " + value);
095    }
096    return result;
097  }
098
099  /**
100   * Returns the {@code int} nearest in value to {@code value}.
101   *
102   * @param value any {@code long} value
103   * @return the same value cast to {@code int} if it is in the range of the
104   *     {@code int} type, {@link Integer#MAX_VALUE} if it is too large,
105   *     or {@link Integer#MIN_VALUE} if it is too small
106   */
107  public static int saturatedCast(long value) {
108    if (value > Integer.MAX_VALUE) {
109      return Integer.MAX_VALUE;
110    }
111    if (value < Integer.MIN_VALUE) {
112      return Integer.MIN_VALUE;
113    }
114    return (int) value;
115  }
116
117  /**
118   * Compares the two specified {@code int} values. The sign of the value
119   * returned is the same as that of {@code ((Integer) a).compareTo(b)}.
120   *
121   * <p><b>Note for Java 7 and later:</b> this method should be treated as
122   * deprecated; use the equivalent {@link Integer#compare} method instead.
123   *
124   * @param a the first {@code int} to compare
125   * @param b the second {@code int} to compare
126   * @return a negative value if {@code a} is less than {@code b}; a positive
127   *     value if {@code a} is greater than {@code b}; or zero if they are equal
128   */
129  public static int compare(int a, int b) {
130    return (a < b) ? -1 : ((a > b) ? 1 : 0);
131  }
132
133  /**
134   * Returns {@code true} if {@code target} is present as an element anywhere in
135   * {@code array}.
136   *
137   * @param array an array of {@code int} values, possibly empty
138   * @param target a primitive {@code int} value
139   * @return {@code true} if {@code array[i] == target} for some value of {@code
140   *     i}
141   */
142  public static boolean contains(int[] array, int target) {
143    for (int value : array) {
144      if (value == target) {
145        return true;
146      }
147    }
148    return false;
149  }
150
151  /**
152   * Returns the index of the first appearance of the value {@code target} in
153   * {@code array}.
154   *
155   * @param array an array of {@code int} values, possibly empty
156   * @param target a primitive {@code int} value
157   * @return the least index {@code i} for which {@code array[i] == target}, or
158   *     {@code -1} if no such index exists.
159   */
160  public static int indexOf(int[] array, int target) {
161    return indexOf(array, target, 0, array.length);
162  }
163
164  // TODO(kevinb): consider making this public
165  private static int indexOf(int[] array, int target, int start, int end) {
166    for (int i = start; i < end; i++) {
167      if (array[i] == target) {
168        return i;
169      }
170    }
171    return -1;
172  }
173
174  /**
175   * Returns the start position of the first occurrence of the specified {@code
176   * target} within {@code array}, or {@code -1} if there is no such occurrence.
177   *
178   * <p>More formally, returns the lowest index {@code i} such that {@code
179   * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
180   * the same elements as {@code target}.
181   *
182   * @param array the array to search for the sequence {@code target}
183   * @param target the array to search for as a sub-sequence of {@code array}
184   */
185  public static int indexOf(int[] array, int[] target) {
186    checkNotNull(array, "array");
187    checkNotNull(target, "target");
188    if (target.length == 0) {
189      return 0;
190    }
191
192    outer:
193    for (int i = 0; i < array.length - target.length + 1; i++) {
194      for (int j = 0; j < target.length; j++) {
195        if (array[i + j] != target[j]) {
196          continue outer;
197        }
198      }
199      return i;
200    }
201    return -1;
202  }
203
204  /**
205   * Returns the index of the last appearance of the value {@code target} in
206   * {@code array}.
207   *
208   * @param array an array of {@code int} values, possibly empty
209   * @param target a primitive {@code int} value
210   * @return the greatest index {@code i} for which {@code array[i] == target},
211   *     or {@code -1} if no such index exists.
212   */
213  public static int lastIndexOf(int[] array, int target) {
214    return lastIndexOf(array, target, 0, array.length);
215  }
216
217  // TODO(kevinb): consider making this public
218  private static int lastIndexOf(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  /**
310   * Returns the {@code int} value whose big-endian representation is stored in
311   * the first 4 bytes of {@code bytes}; equivalent to {@code
312   * ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array {@code
313   * {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code
314   * 0x12131415}.
315   *
316   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
317   * library exposes much more flexibility at little cost in readability.
318   *
319   * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements
320   */
321  @GwtIncompatible("doesn't work")
322  public static int fromByteArray(byte[] bytes) {
323    checkArgument(bytes.length >= BYTES, "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 extends Converter<String, Integer>
340      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
362    private static final long serialVersionUID = 1;
363  }
364
365  /**
366   * Returns a serializable converter object that converts between strings and
367   * integers using {@link Integer#decode} and {@link Integer#toString()}.
368   *
369   * @since 16.0
370   */
371  @Beta
372  public static Converter<String, Integer> stringConverter() {
373    return IntConverter.INSTANCE;
374  }
375
376  /**
377   * Returns an array containing the same values as {@code array}, but
378   * guaranteed to be of a specified minimum length. If {@code array} already
379   * has a length of at least {@code minLength}, it is returned directly.
380   * Otherwise, a new array of size {@code minLength + padding} is returned,
381   * containing the values of {@code array}, and zeroes in the remaining places.
382   *
383   * @param array the source array
384   * @param minLength the minimum length the returned array must guarantee
385   * @param padding an extra amount to "grow" the array by if growth is
386   *     necessary
387   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
388   *     negative
389   * @return an array containing the values of {@code array}, with guaranteed
390   *     minimum length {@code minLength}
391   */
392  public static int[] ensureCapacity(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
535    public int size() {
536      return end - start;
537    }
538
539    @Override
540    public boolean isEmpty() {
541      return false;
542    }
543
544    @Override
545    public Integer get(int index) {
546      checkElementIndex(index, size());
547      return array[start + index];
548    }
549
550    @Override
551    public boolean contains(Object target) {
552      // Overridden to prevent a ton of boxing
553      return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1;
554    }
555
556    @Override
557    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
569    public int lastIndexOf(Object target) {
570      // Overridden to prevent a ton of boxing
571      if (target instanceof Integer) {
572        int i = Ints.lastIndexOf(array, (Integer) target, start, end);
573        if (i >= 0) {
574          return i - start;
575        }
576      }
577      return -1;
578    }
579
580    @Override
581    public Integer set(int index, Integer element) {
582      checkElementIndex(index, size());
583      int oldValue = array[start + index];
584      // checkNotNull for GWT (do not optimize)
585      array[start + index] = checkNotNull(element);
586      return oldValue;
587    }
588
589    @Override
590    public List<Integer> subList(int fromIndex, int toIndex) {
591      int size = size();
592      checkPositionIndexes(fromIndex, toIndex, size);
593      if (fromIndex == toIndex) {
594        return Collections.emptyList();
595      }
596      return new IntArrayAsList(array, start + fromIndex, start + toIndex);
597    }
598
599    @Override
600    public boolean equals(@Nullable Object object) {
601      if (object == this) {
602        return true;
603      }
604      if (object instanceof IntArrayAsList) {
605        IntArrayAsList that = (IntArrayAsList) object;
606        int size = size();
607        if (that.size() != size) {
608          return false;
609        }
610        for (int i = 0; i < size; i++) {
611          if (array[start + i] != that.array[that.start + i]) {
612            return false;
613          }
614        }
615        return true;
616      }
617      return super.equals(object);
618    }
619
620    @Override
621    public int hashCode() {
622      int result = 1;
623      for (int i = start; i < end; i++) {
624        result = 31 * result + Ints.hashCode(array[i]);
625      }
626      return result;
627    }
628
629    @Override
630    public String toString() {
631      StringBuilder builder = new StringBuilder(size() * 5);
632      builder.append('[').append(array[start]);
633      for (int i = start + 1; i < end; i++) {
634        builder.append(", ").append(array[i]);
635      }
636      return builder.append(']').toString();
637    }
638
639    int[] toIntArray() {
640      // Arrays.copyOfRange() is not available under GWT
641      int size = size();
642      int[] result = new int[size];
643      System.arraycopy(array, start, result, 0, size);
644      return result;
645    }
646
647    private static final long serialVersionUID = 0;
648  }
649
650  /**
651   * Parses the specified string as a signed decimal integer value. The ASCII
652   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the
653   * minus sign.
654   *
655   * <p>Unlike {@link Integer#parseInt(String)}, this method returns
656   * {@code null} instead of throwing an exception if parsing fails.
657   * Additionally, this method only accepts ASCII digits, and returns
658   * {@code null} if non-ASCII digits are present in the string.
659   *
660   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even
661   * under JDK 7, despite the change to {@link Integer#parseInt(String)} for
662   * that version.
663   *
664   * @param string the string representation of an integer value
665   * @return the integer value represented by {@code string}, or {@code null} if
666   *     {@code string} has a length of zero or cannot be parsed as an integer
667   *     value
668   * @since 11.0
669   */
670  @Beta
671  @Nullable
672  @CheckForNull
673  public static Integer tryParse(String string) {
674    return tryParse(string, 10);
675  }
676
677  /**
678   * Parses the specified string as a signed integer value using the specified
679   * radix. The ASCII character {@code '-'} (<code>'&#92;u002D'</code>) is
680   * recognized as the minus sign.
681   *
682   * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns
683   * {@code null} instead of throwing an exception if parsing fails.
684   * Additionally, this method only accepts ASCII digits, and returns
685   * {@code null} if non-ASCII digits are present in the string.
686   *
687   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even
688   * under JDK 7, despite the change to {@link Integer#parseInt(String, int)}
689   * for that version.
690   *
691   * @param string the string representation of an integer value
692   * @param radix the radix to use when parsing
693   * @return the integer value represented by {@code string} using
694   *     {@code radix}, or {@code null} if {@code string} has a length of zero
695   *     or cannot be parsed as an integer value
696   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or
697   *     {@code radix > Character.MAX_RADIX}
698   * @since 19.0
699   */
700  @Beta
701  @Nullable
702  @CheckForNull
703  public static Integer tryParse(
704      String string, int radix) {
705    Long result = Longs.tryParse(string, radix);
706    if (result == null || result.longValue() != result.intValue()) {
707      return null;
708    } else {
709      return result.intValue();
710    }
711  }
712}