From f38ff924d7d49933e3f577fe9addaef963ffd7ce Mon Sep 17 00:00:00 2001 From: Julien BLACHE Date: Wed, 5 May 2010 19:03:53 +0200 Subject: [PATCH] Add safe_hextou32() --- src/misc.c | 36 ++++++++++++++++++++++++++++++++++++ src/misc.h | 3 +++ 2 files changed, 39 insertions(+) diff --git a/src/misc.c b/src/misc.c index 0665d385..ba17e476 100644 --- a/src/misc.c +++ b/src/misc.c @@ -109,6 +109,42 @@ safe_atou32(const char *str, uint32_t *val) return 0; } +int +safe_hextou32(const char *str, uint32_t *val) +{ + char *end; + unsigned long intval; + + errno = 0; + intval = strtoul(str, &end, 16); + + 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) { diff --git a/src/misc.h b/src/misc.h index d99665fb..0e821dff 100644 --- a/src/misc.h +++ b/src/misc.h @@ -10,6 +10,9 @@ safe_atoi32(const char *str, int32_t *val); int safe_atou32(const char *str, uint32_t *val); +int +safe_hextou32(const char *str, uint32_t *val); + int safe_atoi64(const char *str, int64_t *val);