parse/value: add bool specialisation

This commit is contained in:
Danny Robson 2019-05-30 10:42:25 +10:00
parent cdb3ded3df
commit e4ce92454c
2 changed files with 34 additions and 0 deletions

View File

@ -152,3 +152,34 @@ C_PARSE_WITH_CAST(short, long)
C_PARSE_WITH_CAST(int, long)
C_PARSE_WITH_CAST(unsigned short, unsigned long)
C_PARSE_WITH_CAST(unsigned int, unsigned long)
///////////////////////////////////////////////////////////////////////////////
template <>
bool
cruft::parse::value<bool> (cruft::view<char const*> &str)
{
static constexpr struct {
char const *str;
bool res;
} VALUES[] = {
{ "yes", true },
{ "y", true },
{ "true",true },
{ "t", true },
{ "no", false, },
{ "n", false, },
{ "false", false, },
{ "f", false, },
};
for (auto [key,val]: VALUES) {
if (equal (key, str)) {
str = str.consume (strlen (key));
return val;
}
}
throw std::invalid_argument ("invalid boolean string");
}

View File

@ -14,5 +14,8 @@ main (void)
tap.expect_eq (cruft::parse::from_string<float> ("1"), 1.f, "parsing float '1'");
tap.expect_throw<std::invalid_argument> ([] () { cruft::parse::from_string<float> ("a"); }, "parsing float 'a'");
tap.expect_eq (cruft::parse::from_string<bool> ("true"), true, "parsing true");
tap.expect_eq (cruft::parse::from_string<bool> ("false"), false, "parsing false");
return tap.status ();
}