Skip to content

Instantly share code, notes, and snippets.

@tomcatzh
Created June 15, 2019 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomcatzh/2f03735124d10b77f4145022aafb5c08 to your computer and use it in GitHub Desktop.
Save tomcatzh/2f03735124d10b77f4145022aafb5c08 to your computer and use it in GitHub Desktop.
parseHumanSize #c #atoi
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