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