added methods parseBool() and tryParseBool() to Poco::NumberParser + test unit

This commit is contained in:
Marian Krivos
2009-03-16 17:59:38 +00:00
parent 582d3853db
commit 02161a9f46
3 changed files with 80 additions and 0 deletions

View File

@@ -115,6 +115,21 @@ public:
/// from the given string.
/// Returns true if a valid floating point number has been found,
/// false otherwise.
static bool parseBool(const std::string& s);
/// Parses a bool value in decimal or string notation
/// from the given string.
/// Valid forms are: "0", "1", "true", "on", false", "yes", "no", "off".
/// String forms are NOT case sensitive.
/// Throws a SyntaxException if the string does not hold a valid bool number
static bool tryParseBool(const std::string& s, bool& value);
/// Parses a bool value in decimal or string notation
/// from the given string.
/// Valid forms are: "0", "1", "true", "on", false", "yes", "no", "off".
/// String forms are NOT case sensitive.
/// Returns true if a valid bool number has been found,
/// false otherwise.
};

View File

@@ -36,6 +36,7 @@
#include "Poco/NumberParser.h"
#include "Poco/Exception.h"
#include "Poco/String.h"
#include <cstdio>
#include <cctype>
@@ -177,4 +178,59 @@ bool NumberParser::tryParseFloat(const std::string& s, double& value)
}
bool NumberParser::parseBool(const std::string& s)
{
bool result;
if (tryParseBool(s, result))
return result;
else
throw SyntaxException("Not a valid bool number", s);
}
bool NumberParser::tryParseBool(const std::string& s, bool& value)
{
int n;
if (NumberParser::tryParse(s, n))
{
value = (n != 0);
return true;
}
if (icompare(s, "true") == 0)
{
value = true;
return true;
}
else if (icompare(s, "yes") == 0)
{
value = true;
return true;
}
else if (icompare(s, "on") == 0)
{
value = true;
return true;
}
if (icompare(s, "false") == 0)
{
value = false;
return true;
}
else if (icompare(s, "no") == 0)
{
value = false;
return true;
}
else if (icompare(s, "off") == 0)
{
value = false;
return true;
}
return false;
}
} // namespace Poco

View File

@@ -58,6 +58,13 @@ void NumberParserTest::testParse()
assert (NumberParser::parseUnsigned("123") == 123);
assert (NumberParser::parseHex("12AB") == 0x12ab);
assert (NumberParser::parseBool("0") == false);
assert (NumberParser::parseBool("FALSE") == false);
assert (NumberParser::parseBool("no") == false);
assert (NumberParser::parseBool("1") == true);
assert (NumberParser::parseBool("True") == true);
assert (NumberParser::parseBool("YeS") == true);
#if defined(POCO_HAVE_INT64)
assert (NumberParser::parse64("123") == 123);
assert (NumberParser::parse64("-123") == -123);
@@ -73,6 +80,7 @@ void NumberParserTest::testParseError()
try
{
NumberParser::parse("");
NumberParser::parseBool("");
failmsg("must throw SyntaxException");
}
catch (SyntaxException&)
@@ -82,6 +90,7 @@ void NumberParserTest::testParseError()
try
{
NumberParser::parse("asd");
NumberParser::parseBool("asd");
failmsg("must throw SyntaxException");
}
catch (SyntaxException&)