Add safe_atou32() and safe_atou64()

This commit is contained in:
Ace Jones 2010-02-08 14:58:14 +01:00 committed by Julien BLACHE
parent 0607e82a42
commit 20d08d8a49
2 changed files with 78 additions and 0 deletions

View File

@ -73,6 +73,42 @@ safe_atoi32(const char *str, int32_t *val)
return 0;
}
int
safe_atou32(const char *str, uint32_t *val)
{
char *end;
unsigned long intval;
errno = 0;
intval = strtoul(str, &end, 10);
if (((errno == ERANGE) && (intval == ULONG_MAX))
|| ((errno != 0) && (intval == 0)))
{
DPRINTF(E_DBG, L_MISC, "Invalid integer in string (%s): %s\n", str, strerror(errno));
return -1;
}
if (end == str)
{
DPRINTF(E_DBG, L_MISC, "No integer found in string (%s)\n", str);
return -1;
}
if (intval > UINT32_MAX)
{
DPRINTF(E_DBG, L_MISC, "Integer value too large (%s)\n", str);
return -1;
}
*val = (uint32_t)intval;
return 0;
}
int
safe_atoi64(const char *str, int64_t *val)
{
@ -109,6 +145,42 @@ safe_atoi64(const char *str, int64_t *val)
return 0;
}
int
safe_atou64(const char *str, uint64_t *val)
{
char *end;
unsigned long long intval;
errno = 0;
intval = strtoull(str, &end, 10);
if (((errno == ERANGE) && (intval == ULLONG_MAX))
|| ((errno != 0) && (intval == 0)))
{
DPRINTF(E_DBG, L_MISC, "Invalid integer in string (%s): %s\n", str, strerror(errno));
return -1;
}
if (end == str)
{
DPRINTF(E_DBG, L_MISC, "No integer found in string (%s)\n", str);
return -1;
}
if (intval > UINT64_MAX)
{
DPRINTF(E_DBG, L_MISC, "Integer value too large (%s)\n", str);
return -1;
}
*val = (uint64_t)intval;
return 0;
}
char *
m_realpath(const char *pathname)
{

View File

@ -7,9 +7,15 @@
int
safe_atoi32(const char *str, int32_t *val);
int
safe_atou32(const char *str, uint32_t *val);
int
safe_atoi64(const char *str, int64_t *val);
int
safe_atou64(const char *str, uint64_t *val);
char *
m_realpath(const char *pathname);