Chromium Code Reviews| Index: runtime/lib/integers_patch.dart |
| =================================================================== |
| --- runtime/lib/integers_patch.dart (revision 21982) |
| +++ runtime/lib/integers_patch.dart (working copy) |
| @@ -6,8 +6,65 @@ |
| // VM implementation of int. |
| patch class int { |
| - static int _parse(String str) native "Integer_parse"; |
| + static bool _isWhitespace(int codePoint) { |
| + return |
| + (codePoint == 32) || // Space. |
| + ((9 <= codePoint) && (codePoint <= 13)); // CR, LF, TAB, etc. |
| + } |
| + |
| + static int _tryParseSmi(String str) { |
| + if (str.isEmpty) return null; |
| + var ix = 0; |
| + var endIx = str.length - 1; |
| + // Find first and last non-whitespace. |
| + while (ix <= endIx) { |
| + if (!_isWhitespace(str.codeUnitAt(ix))) break; |
| + ix++; |
| + } |
| + if (endIx < ix) { |
| + return null; // Empty. |
| + } |
| + while (ix > endIx) { |
|
siva
2013/04/24 23:59:00
This check seems inverted here, did you mean
while
srdjan
2013/04/25 17:30:07
Yes, thanks.
|
| + if (!_isWhitespace(str.codeUnitAt(endIx))) break; |
| + endIx--; |
| + } |
|
siva
2013/04/24 23:59:00
Why not use trim() here to remove the leading and
srdjan
2013/04/25 17:30:07
trim creates a new String if needed. This leads to
|
| + |
| + bool isNegative = false; |
| + var c = str.codeUnitAt(ix); |
| + // Check for leading '+' or '-'. |
| + if ((c == 0x2b) || (c == 0x2d)) { |
| + ix++; |
| + isNegative = (c == 0x2d); |
| + if (ix > endIx) { |
| + return null; // Empty. |
| + } |
| + } |
| + if ((endIx - ix) >= 9) { |
| + return null; // May not fit into a Smi. |
| + } |
| + |
| + int result = 0; |
|
siva
2013/04/24 23:59:00
var result = 0; ?
Here and above for IsNegative a
|
| + for (int i = ix; i <= endIx; i++) { |
| + var c = str.codeUnitAt(i) - 0x30; |
| + if ((c > 9) || (c < 0)) { |
| + return null; |
| + } |
| + result = result * 10 + c; |
| + } |
| + return isNegative ? -result : result; |
| + } |
| + |
| + static int _parse(String str) { |
| + int res = _tryParseSmi(str); |
| + if (res == null) { |
| + res = _native_parse(str); |
| + } |
| + return res; |
| + } |
| + |
| + static int _native_parse(String str) native "Integer_parse"; |
| + |
| static int _throwFormatException(String source) { |
| throw new FormatException(source); |
| } |