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 java.util.Spliterator;
034import java.util.Spliterators;
035import javax.annotation.CheckForNull;
036import javax.annotation.Nullable;
037
038/**
039 * Static utility methods pertaining to {@code int} primitives, that are not already found in either
040 * {@link Integer} or {@link Arrays}.
041 *
042 * <p>See the Guava User Guide article on
043 * <a href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
044 *
045 * @author Kevin Bourrillion
046 * @since 1.0
047 */
048@GwtCompatible
049public final class Ints {
050  private Ints() {}
051
052  /**
053   * The number of bytes required to represent a primitive {@code int} value.
054   *
055   * <p><b>Java 8 users:</b> use {@link Integer#BYTES} instead.
056   */
057  public static final int BYTES = Integer.SIZE / Byte.SIZE;
058
059  /**
060   * The largest power of two that can be represented as an {@code int}.
061   *
062   * @since 10.0
063   */
064  public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
065
066  /**
067   * Returns a hash code for {@code value}; equal to the result of invoking
068   * {@code ((Integer) value).hashCode()}.
069   *
070   * <p><b>Java 8 users:</b> use {@link Integer#hashCode(int)} instead.
071   *
072   * @param value a primitive {@code int} value
073   * @return a hash code for the value
074   */
075  public static int hashCode(int value) {
076    return value;
077  }
078
079  /**
080   * Returns the {@code int} value that is equal to {@code value}, if possible.
081   *
082   * @param value any value in the range of the {@code int} type
083   * @return the {@code int} value that equals {@code value}
084   * @throws IllegalArgumentException if {@code value} is greater than {@link Integer#MAX_VALUE} or
085   *     less than {@link Integer#MIN_VALUE}
086   */
087  public static int checkedCast(long value) {
088    int result = (int) value;
089    checkArgument(result == value, "Out of range: %s", value);
090    return result;
091  }
092
093  /**
094   * Returns the {@code int} nearest in value to {@code value}.
095   *
096   * @param value any {@code long} value
097   * @return the same value cast to {@code int} if it is in the range of the {@code int} type,
098   *     {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too
099   *     small
100   */
101  public static int saturatedCast(long value) {
102    if (value > Integer.MAX_VALUE) {
103      return Integer.MAX_VALUE;
104    }
105    if (value < Integer.MIN_VALUE) {
106      return Integer.MIN_VALUE;
107    }
108    return (int) value;
109  }
110
111  /**
112   * Compares the two specified {@code int} values. The sign of the value returned is the same as
113   * that of {@code ((Integer) a).compareTo(b)}.
114   *
115   * <p><b>Note for Java 7 and later:</b> this method should be treated as deprecated; use the
116   * equivalent {@link Integer#compare} method instead.
117   *
118   * @param a the first {@code int} to compare
119   * @param b the second {@code int} to compare
120   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
121   *     greater than {@code b}; or zero if they are equal
122   */
123  public static int compare(int a, int b) {
124    return (a < b) ? -1 : ((a > b) ? 1 : 0);
125  }
126
127  /**
128   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
129   *
130   * @param array an array of {@code int} values, possibly empty
131   * @param target a primitive {@code int} value
132   * @return {@code true} if {@code array[i] == target} for some value of {@code
133   *     i}
134   */
135  public static boolean contains(int[] array, int target) {
136    for (int value : array) {
137      if (value == target) {
138        return true;
139      }
140    }
141    return false;
142  }
143
144  /**
145   * Returns the index of the first appearance of the value {@code target} in {@code array}.
146   *
147   * @param array an array of {@code int} values, possibly empty
148   * @param target a primitive {@code int} value
149   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
150   *     such index exists.
151   */
152  public static int indexOf(int[] array, int target) {
153    return indexOf(array, target, 0, array.length);
154  }
155
156  // TODO(kevinb): consider making this public
157  private static int indexOf(int[] array, int target, int start, int end) {
158    for (int i = start; i < end; i++) {
159      if (array[i] == target) {
160        return i;
161      }
162    }
163    return -1;
164  }
165
166  /**
167   * Returns the start position of the first occurrence of the specified {@code
168   * target} within {@code array}, or {@code -1} if there is no such occurrence.
169   *
170   * <p>More formally, returns the lowest index {@code i} such that
171   * {@code Arrays.copyOfRange(array, i, i + target.length)} contains exactly the same elements as
172   * {@code target}.
173   *
174   * @param array the array to search for the sequence {@code target}
175   * @param target the array to search for as a sub-sequence of {@code array}
176   */
177  public static int indexOf(int[] array, int[] target) {
178    checkNotNull(array, "array");
179    checkNotNull(target, "target");
180    if (target.length == 0) {
181      return 0;
182    }
183
184    outer:
185    for (int i = 0; i < array.length - target.length + 1; i++) {
186      for (int j = 0; j < target.length; j++) {
187        if (array[i + j] != target[j]) {
188          continue outer;
189        }
190      }
191      return i;
192    }
193    return -1;
194  }
195
196  /**
197   * Returns the index of the last appearance of the value {@code target} in {@code array}.
198   *
199   * @param array an array of {@code int} values, possibly empty
200   * @param target a primitive {@code int} value
201   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
202   *     such index exists.
203   */
204  public static int lastIndexOf(int[] array, int target) {
205    return lastIndexOf(array, target, 0, array.length);
206  }
207
208  // TODO(kevinb): consider making this public
209  private static int lastIndexOf(int[] array, int target, int start, int end) {
210    for (int i = end - 1; i >= start; i--) {
211      if (array[i] == target) {
212        return i;
213      }
214    }
215    return -1;
216  }
217
218  /**
219   * Returns the least value present in {@code array}.
220   *
221   * @param array a <i>nonempty</i> array of {@code int} values
222   * @return the value present in {@code array} that is less than or equal to every other value in
223   *     the array
224   * @throws IllegalArgumentException if {@code array} is empty
225   */
226  public static int min(int... array) {
227    checkArgument(array.length > 0);
228    int min = array[0];
229    for (int i = 1; i < array.length; i++) {
230      if (array[i] < min) {
231        min = array[i];
232      }
233    }
234    return min;
235  }
236
237  /**
238   * Returns the greatest value present in {@code array}.
239   *
240   * @param array a <i>nonempty</i> array of {@code int} values
241   * @return the value present in {@code array} that is greater than or equal to every other value
242   *     in the array
243   * @throws IllegalArgumentException if {@code array} is empty
244   */
245  public static int max(int... array) {
246    checkArgument(array.length > 0);
247    int max = array[0];
248    for (int i = 1; i < array.length; i++) {
249      if (array[i] > max) {
250        max = array[i];
251      }
252    }
253    return max;
254  }
255
256  /**
257   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
258   *
259   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
260   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if
261   * {@code value} is greater than {@code max}, {@code max} is returned.
262   *
263   * @param value the {@code int} value to constrain
264   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
265   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
266   * @throws IllegalArgumentException if {@code min > max}
267   * @since 21.0
268   */
269  @Beta
270  public static int constrainToRange(int value, int min, int max) {
271    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
272    return Math.min(Math.max(value, min), max);
273  }
274
275  /**
276   * Returns the values from each provided array combined into a single array. For example,
277   * {@code concat(new int[] {a, b}, new int[] {}, new int[] {c}} returns the array {@code {a, b,
278   * 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
300   * {@code 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
304   * {@link 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
316   * {@code 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
366   * {@link Integer#decode} and {@link Integer#toString()}. The returned converter throws
367   * {@link 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
391   *     {@code 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
518   * collection.toArray()}. 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 Spliterator.OfInt spliterator() {
598      return Spliterators.spliterator(array, start, end, 0);
599    }
600
601    @Override
602    public boolean contains(Object target) {
603      // Overridden to prevent a ton of boxing
604      return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1;
605    }
606
607    @Override
608    public int indexOf(Object target) {
609      // Overridden to prevent a ton of boxing
610      if (target instanceof Integer) {
611        int i = Ints.indexOf(array, (Integer) target, start, end);
612        if (i >= 0) {
613          return i - start;
614        }
615      }
616      return -1;
617    }
618
619    @Override
620    public int lastIndexOf(Object target) {
621      // Overridden to prevent a ton of boxing
622      if (target instanceof Integer) {
623        int i = Ints.lastIndexOf(array, (Integer) target, start, end);
624        if (i >= 0) {
625          return i - start;
626        }
627      }
628      return -1;
629    }
630
631    @Override
632    public Integer set(int index, Integer element) {
633      checkElementIndex(index, size());
634      int oldValue = array[start + index];
635      // checkNotNull for GWT (do not optimize)
636      array[start + index] = checkNotNull(element);
637      return oldValue;
638    }
639
640    @Override
641    public List<Integer> subList(int fromIndex, int toIndex) {
642      int size = size();
643      checkPositionIndexes(fromIndex, toIndex, size);
644      if (fromIndex == toIndex) {
645        return Collections.emptyList();
646      }
647      return new IntArrayAsList(array, start + fromIndex, start + toIndex);
648    }
649
650    @Override
651    public boolean equals(@Nullable Object object) {
652      if (object == this) {
653        return true;
654      }
655      if (object instanceof IntArrayAsList) {
656        IntArrayAsList that = (IntArrayAsList) object;
657        int size = size();
658        if (that.size() != size) {
659          return false;
660        }
661        for (int i = 0; i < size; i++) {
662          if (array[start + i] != that.array[that.start + i]) {
663            return false;
664          }
665        }
666        return true;
667      }
668      return super.equals(object);
669    }
670
671    @Override
672    public int hashCode() {
673      int result = 1;
674      for (int i = start; i < end; i++) {
675        result = 31 * result + Ints.hashCode(array[i]);
676      }
677      return result;
678    }
679
680    @Override
681    public String toString() {
682      StringBuilder builder = new StringBuilder(size() * 5);
683      builder.append('[').append(array[start]);
684      for (int i = start + 1; i < end; i++) {
685        builder.append(", ").append(array[i]);
686      }
687      return builder.append(']').toString();
688    }
689
690    int[] toIntArray() {
691      return Arrays.copyOfRange(array, start, end);
692    }
693
694    private static final long serialVersionUID = 0;
695  }
696
697  /**
698   * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'}
699   * (<code>'&#92;u002D'</code>) is recognized as the minus sign.
700   *
701   * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of
702   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
703   * and returns {@code null} if non-ASCII digits are present in the string.
704   *
705   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
706   * the change to {@link Integer#parseInt(String)} for that version.
707   *
708   * @param string the string representation of an integer value
709   * @return the integer value represented by {@code string}, or {@code null} if {@code string} has
710   *     a length of zero or cannot be parsed as an integer value
711   * @since 11.0
712   */
713  @Beta
714  @Nullable
715  @CheckForNull
716  public static Integer tryParse(String string) {
717    return tryParse(string, 10);
718  }
719
720  /**
721   * Parses the specified string as a signed integer value using the specified radix. The ASCII
722   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
723   *
724   * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns {@code null} instead of
725   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
726   * and returns {@code null} if non-ASCII digits are present in the string.
727   *
728   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
729   * the change to {@link Integer#parseInt(String, int)} for that version.
730   *
731   * @param string the string representation of an integer value
732   * @param radix the radix to use when parsing
733   * @return the integer value represented by {@code string} using {@code radix}, or {@code null} if
734   *     {@code string} has a length of zero or cannot be parsed as an integer value
735   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or
736   *     {@code radix > Character.MAX_RADIX}
737   * @since 19.0
738   */
739  @Beta
740  @Nullable
741  @CheckForNull
742  public static Integer tryParse(String string, int radix) {
743    Long result = Longs.tryParse(string, radix);
744    if (result == null || result.longValue() != result.intValue()) {
745      return null;
746    } else {
747      return result.intValue();
748    }
749  }
750}