conga/ricci/common utils.cpp
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
ricci/common/utils.cpp +38 -8
@@ -23,8 +23,12 @@ #include "utils.h" #include "executils.h" -#include <openssl/md5.h> +#include <unistd.h> +#include <stdio.h> #include <stdlib.h> +#include <math.h> +#include <errno.h> +#include <openssl/md5.h> //#include <iostream>
@@ -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; }