| Original |
|---|
1 @Beta
2 @Nullable
3 @CheckForNull
4 public static Long tryParse(String string) {
5 if (checkNotNull(string).isEmpty()) {
6 return null;
7 }
8 boolean negative = string.charAt(0) == '-';
9 int index = negative ? 1 : 0;
10 if (index == string.length()) {
11 return null;
12 }
13 int digit = string.charAt(index++) - '0';
14 if (digit < 0 || digit > 9) {
15 return null;
16 }
17 long accum = -digit;
18 while (index < string.length()) {
19 digit = string.charAt(index++) - '0';
20 if (digit < 0 || digit > 9 || accum < Long.MIN_VALUE / 10) {
21 return null;
22 }
23 accum *= 10;
24 if (accum < Long.MIN_VALUE + digit) {
25 return null;
26 }
27 accum -= digit;
28 }
29
30 if (negative) {
31 return accum;
32 } else if (accum == Long.MIN_VALUE) {
33 return null;
34 } else {
35 return -accum;
36 }
37 }
38
|
| | Modified |
|---|
1 @Beta
2 @Nullable
3 @CheckForNull
4 public static Long tryParse(String string, int radix) {
5 if (checkNotNull(string).isEmpty()) {
6 return null;
7 }
8 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
9 throw new IllegalArgumentException(
10 "radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
11 }
12 boolean negative = string.charAt(0) == '-';
13 int index = negative ? 1 : 0;
14 if (index == string.length()) {
15 return null;
16 }
17 int digit = digit(string.charAt(index++)) ;
18 if (digit < 0 || digit >= radix) {
19 return null;
20 }
21 long accum = -digit;
22
23 long cap = Long.MIN_VALUE / radix;
24
25 while (index < string.length()) {
26 digit = digit(string.charAt(index++));
27 if (digit < 0 || digit >= radix || accum < cap) {
28 return null;
29 }
30 accum *= radix;
31 if (accum < Long.MIN_VALUE + digit) {
32 return null;
33 }
34 accum -= digit;
35 }
36
37 if (negative) {
38 return accum;
39 } else if (accum == Long.MIN_VALUE) {
40 return null;
41 } else {
42 return -accum;
43 }
44 }
45
|
|