From 20d08d8a4937f6cd6b9fbbb6ea67443b463fc802 Mon Sep 17 00:00:00 2001 From: Ace Jones Date: Mon, 8 Feb 2010 14:58:14 +0100 Subject: [PATCH] Add safe_atou32() and safe_atou64() --- src/misc.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/misc.h | 6 +++++ 2 files changed, 78 insertions(+) diff --git a/src/misc.c b/src/misc.c index 1621a075..f79821a0 100644 --- a/src/misc.c +++ b/src/misc.c @@ -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) { diff --git a/src/misc.h b/src/misc.h index 7ab5d039..4af535ba 100644 --- a/src/misc.h +++ b/src/misc.h @@ -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);