Created
June 15, 2019 10:05
-
-
Save tomcatzh/2f03735124d10b77f4145022aafb5c08 to your computer and use it in GitHub Desktop.
parseHumanSize #c #atoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uintmax_t parseHumanSize (const char* s) { | |
char *endp = (char *)s; | |
int sh; | |
errno = 0; | |
uintmax_t x = strtoumax(s, &endp, 10); | |
if (errno || endp == s) { | |
errno = EINVAL; | |
goto ERROR; | |
} | |
switch (*endp) { | |
case 'k': | |
case 'K': | |
sh = 10; | |
break; | |
case 'M': | |
case 'm': | |
sh = 20; | |
break; | |
case 'g': | |
case 'G': | |
sh = 30; | |
break; | |
case 0: | |
sh = 0; | |
break; | |
default: | |
goto ERROR; | |
} | |
if (sh && endp[1]) { | |
errno = EINVAL; | |
goto ERROR; | |
} | |
if (x > SIZE_MAX>>sh) { | |
errno = ERANGE; | |
goto ERROR; | |
} | |
x <<= sh; | |
return x; | |
ERROR: | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment