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