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