This file is an update to the "robert_2.c" file located here: https://github.com/regehr/str2long_contest This is a contest for parsing integers with no integer overflows. The performance tests use mostly invalid input, which skews the performance results. My "robert_2.c" code is half as fast as the fastest "yang_2.c" code. That's because Yang in…
#include "str2long.h" | |
long str2long_robert_3(const char *str) | |
{ | |
long result = 0; | |
int i; | |
if (str[0] == '-') { | |
if (str[1] == '\0') | |
error = 1; | |
for (i=1; str[i]=='0'; i++) | |
; | |
for (; str[i]; i++) { | |
int c = str[i]; | |
if (c < '0' || '9' < c) { | |
error = 1; | |
return 0; | |
} else if (result < LONG_MIN/10) { | |
error = 1; | |
return 0; | |
} else if (result * 10 < (LONG_MIN + (c - '0'))) { | |
error = 1; | |
return 0; | |
} else | |
result = result * 10 - (c - '0'); | |
} | |
} else { | |
if (str[0] == '\0') | |
error = 1; | |
for (i=0; str[i]=='0'; i++) | |
; | |
for (; str[i]; i++) { | |
int c = str[i]; | |
if (c < '0' || '9' < c) { | |
error = 1; | |
return 0; | |
} else if (result > LONG_MAX/10) { | |
error = 1; | |
return 0; | |
} else if (result * 10 > (LONG_MAX - (c - '0'))) { | |
error = 1; | |
return 0; | |
} else | |
result = result * 10 + (c - '0'); | |
} | |
} | |
return result; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment