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