Commit 01ba041c authored by Steven Murray's avatar Steven Murray
Browse files

Added utils::toUint8()

parent 668ff0b6
......@@ -276,6 +276,51 @@ TEST_F(cta_UtilsTest, errnoToString_EACCESS) {
ASSERT_EQ(std::string("Permission denied"), str);
}
TEST_F(cta_UtilsTest, toUint8_123) {
using namespace cta;
uint8_t i = 0;
ASSERT_NO_THROW(i = utils::toUint8("123"));
ASSERT_EQ((uint8_t)123, i);
}
TEST_F(cta_UtilsTest, toUint8_zero) {
using namespace cta;
uint8_t i = 0;
ASSERT_NO_THROW(i = utils::toUint8("0"));
ASSERT_EQ((uint8_t)0, i);
}
TEST_F(cta_UtilsTest, toUint8_255) {
using namespace cta;
uint8_t i = 0;
ASSERT_NO_THROW(i = utils::toUint8("255"));
ASSERT_EQ((uint8_t)255, i);
}
TEST_F(cta_UtilsTest, toUint8_empty_string) {
using namespace cta;
ASSERT_THROW(utils::toUint8(""), std::exception);
}
TEST_F(cta_UtilsTest, toUint8_negative) {
using namespace cta;
ASSERT_THROW(utils::toUint8("-123"), std::exception);
}
TEST_F(cta_UtilsTest, toUint8_too_big) {
using namespace cta;
ASSERT_THROW(utils::toUint8("256"), std::exception);
}
TEST_F(cta_UtilsTest, toUint16_12345) {
using namespace cta;
......
......@@ -487,6 +487,41 @@ std::string errnoToString(const int errnoValue) {
}
}
//------------------------------------------------------------------------------
// toUint8
//------------------------------------------------------------------------------
uint8_t toUint8(const std::string &str) {
if(str.empty()) {
std::ostringstream msg;
msg << "Failed to convert empty string to uint8_t: An empty string is not"
" a valid unsigned integer";
throw exception::Exception(msg.str());
}
errno = 0;
const long int value = strtol(str.c_str(), (char **) NULL, 10);
const int savedErrno = errno;
if(savedErrno) {
std::ostringstream msg;
msg << "Failed to convert \'" << str << "' to uint8_t: " <<
errnoToString(savedErrno);
throw exception::Exception(msg.str());
}
if(0 > value) {
std::ostringstream msg;
msg << "Failed to convert \'" << str << "' to uint8_t: Negative number";
throw exception::Exception(msg.str());
}
if(255 < value) {
std::ostringstream msg;
msg << "Failed to convert \'" << str << "' to uint8_t: Number too big";
throw exception::Exception(msg.str());
}
return value;
}
//------------------------------------------------------------------------------
// toUint16
......
......@@ -239,6 +239,14 @@ namespace utils {
*/
std::string errnoToString(const int errnoValue);
/**
* Converts the specified string to an unsigned integer.
*
* @param str The string.
* @return The unisgned integer.
*/
uint8_t toUint8(const std::string &str);
/**
* Converts the specified string to an unsigned integer.
*
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment