original.java
@Beta
@Nullable
@CheckForNull
public static Long tryParse(String string) {
if (checkNotNull(string).isEmpty()) {
return null;
}
boolean negative = string.charAt(0) == '-';
int index = negative ? 1 : 0;
if (index == string.length()) {
return null;
}
int digit = string.charAt(index++) - '0';
if (digit < 0 || digit > 9) {
return null;
}
long accum = -digit;
while (index < string.length()) {
digit = string.charAt(index++) - '0';
if (digit < 0 || digit > 9 || accum < Long.MIN_VALUE / 10) {
return null;
}
accum *= 10;
if (accum < Long.MIN_VALUE + digit) {
return null;
}
accum -= digit;
}
if (negative) {
return accum;
} else if (accum == Long.MIN_VALUE) {
return null;
} else {
return -accum;
}
}
modified.java
@Beta
@Nullable
@CheckForNull
public static Long tryParse(String string, int radix) {
if (checkNotNull(string).isEmpty()) {
return null;
}
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new IllegalArgumentException(
"radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
}
boolean negative = string.charAt(0) == '-';
int index = negative ? 1 : 0;
if (index == string.length()) {
return null;
}
int digit = digit(string.charAt(index++));
if (digit < 0 || digit >= radix) {
return null;
}
long accum = -digit;
long cap = Long.MIN_VALUE / radix;
while (index < string.length()) {
digit = digit(string.charAt(index++));
if (digit < 0 || digit >= radix || accum < cap) {
return null;
}
accum *= radix;
if (accum < Long.MIN_VALUE + digit) {
return null;
}
accum -= digit;
}
if (negative) {
return accum;
} else if (accum == Long.MIN_VALUE) {
return null;
} else {
return -accum;
}
}