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