This commit is contained in:
dcode
2019-03-14 05:11:03 +01:00
parent 6163a73ab5
commit a5e14a0eaa
24 changed files with 739 additions and 102 deletions

View File

@ -8,6 +8,7 @@ export function compareImpl(str1: string, index1: usize, str2: string, index2: u
return result;
}
// @ts-ignore: decorator
@inline export const enum CharCode {
PLUS = 0x2B,
MINUS = 0x2D,
@ -57,29 +58,35 @@ export function isWhiteSpaceOrLineTerminator(c: u16): bool {
/** Parses a string to an integer (usually), using the specified radix. */
export function parse<T>(str: string, radix: i32 = 0): T {
var len: i32 = str.length;
// @ts-ignore: type
if (!len) return <T>NaN;
var ptr = changetype<usize>(str) /* + HEAD -> offset */;
var code = <i32>load<u16>(ptr, HEADER_SIZE);
var code = <i32>load<u16>(ptr);
// determine sign
var sign: T;
if (code == CharCode.MINUS) {
// @ts-ignore: type
if (!--len) return <T>NaN;
code = <i32>load<u16>(ptr += 2, HEADER_SIZE);
code = <i32>load<u16>(ptr += 2);
// @ts-ignore: type
sign = -1;
} else if (code == CharCode.PLUS) {
// @ts-ignore: type
if (!--len) return <T>NaN;
code = <i32>load<u16>(ptr += 2, HEADER_SIZE);
code = <i32>load<u16>(ptr += 2);
// @ts-ignore: type
sign = 1;
} else {
// @ts-ignore: type
sign = 1;
}
// determine radix
if (!radix) {
if (code == CharCode._0 && len > 2) {
switch (<i32>load<u16>(ptr + 2, HEADER_SIZE)) {
switch (<i32>load<u16>(ptr + 2)) {
case CharCode.B:
case CharCode.b: {
ptr += 4; len -= 2;
@ -102,13 +109,15 @@ export function parse<T>(str: string, radix: i32 = 0): T {
}
} else radix = 10;
} else if (radix < 2 || radix > 36) {
// @ts-ignore: cast
return <T>NaN;
}
// calculate value
// @ts-ignore: type
var num: T = 0;
while (len--) {
code = <i32>load<u16>(ptr, HEADER_SIZE);
code = <i32>load<u16>(ptr);
if (code >= CharCode._0 && code <= CharCode._9) {
code -= CharCode._0;
} else if (code >= CharCode.A && code <= CharCode.Z) {
@ -117,8 +126,10 @@ export function parse<T>(str: string, radix: i32 = 0): T {
code -= CharCode.a - 10;
} else break;
if (code >= radix) break;
// @ts-ignore: type
num = (num * radix) + code;
ptr += 2;
}
// @ts-ignore: type
return sign * num;
}