From mboxrd@z Thu Jan 1 00:00:00 1970 From: rmccabe@sourceware.org Date: 5 Feb 2008 18:29:05 -0000 Subject: [Cluster-devel] conga/ricci/common utils.cpp Message-ID: <20080205182905.22399.qmail@sourceware.org> List-Id: To: cluster-devel.redhat.com MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit CVSROOT: /cvs/cluster Module name: conga Changes by: rmccabe at sourceware.org 2008-02-05 18:29:05 Modified files: ricci/common : utils.cpp Log message: Better string to num conversion Patches: http://sourceware.org/cgi-bin/cvsweb.cgi/conga/ricci/common/utils.cpp.diff?cvsroot=cluster&r1=1.12&r2=1.13 --- conga/ricci/common/utils.cpp 2008/01/02 20:47:34 1.12 +++ conga/ricci/common/utils.cpp 2008/02/05 18:29:05 1.13 @@ -23,8 +23,12 @@ #include "utils.h" #include "executils.h" -#include +#include +#include #include +#include +#include +#include //#include @@ -201,24 +205,44 @@ long long utils::to_long(const String& str) { - return atoll(str.c_str()); + char *p = NULL; + long long ret; + ret = strtoll(strip(str).c_str(), &p, 10); + if (p != NULL && *p != '\0') + throw String("Not a number: ") + str; + if (ret == LLONG_MIN && errno == ERANGE) + throw String("Numeric underflow: ") + str; + if (ret == LLONG_MAX && errno == ERANGE) + throw String("Numeric overflow: ") + str; + return ret; } float utils::to_float(const String& str) { - float num = 0; + char *p = NULL; + float ret; - sscanf(strip(str).c_str(), "%f", &num); - return num; + ret = strtof(strip(str).c_str(), &p); + if (p != NULL && *p == '\0') + throw String("Invalid floating point number: ") + str; + if (ret == 0 && errno == ERANGE) + throw String("Floating point underflow: ") + str; + if ((ret == HUGE_VALF || ret == HUGE_VALL) && errno == ERANGE) + throw String("Floating point overflow: ") + str; + + return ret; } String utils::to_string(int value) { char tmp[64]; + int ret; - sprintf(tmp, "%d", value); + ret = snprintf(tmp, sizeof(tmp), "%d", value); + if (ret < 0 || (size_t) ret >= sizeof(tmp)) + throw String("Invalid integer"); return tmp; } @@ -226,8 +250,11 @@ utils::to_string(long value) { char tmp[64]; + int ret; - sprintf(tmp, "%ld", value); + ret = snprintf(tmp, sizeof(tmp), "%ld", value); + if (ret < 0 || (size_t) ret >= sizeof(tmp)) + throw String("Invalid long integer"); return tmp; } @@ -235,8 +262,11 @@ utils::to_string(long long value) { char tmp[64]; + int ret; - sprintf(tmp, "%lld", value); + ret = snprintf(tmp, sizeof(tmp), "%lld", value); + if (ret < 0 || (size_t) ret >= sizeof(tmp)) + throw String("Invalid long long integer"); return tmp; }