yaml-cpp/src/convert.cpp

73 lines
1.9 KiB
C++
Raw Normal View History

#include <algorithm>
2014-03-23 08:14:48 +04:00
#include "yaml-cpp/node/convert.h"
2014-03-22 22:05:03 +04:00
namespace {
// we're not gonna mess with the mess that is all the isupper/etc. functions
bool IsLower(char ch) { return 'a' <= ch && ch <= 'z'; }
bool IsUpper(char ch) { return 'A' <= ch && ch <= 'Z'; }
char ToLower(char ch) { return IsUpper(ch) ? ch + 'a' - 'A' : ch; }
std::string tolower(const std::string& str) {
std::string s(str);
std::transform(s.begin(), s.end(), s.begin(), ToLower);
return s;
}
template <typename T>
bool IsEntirely(const std::string& str, T func) {
return std::all_of(str.begin(), str.end(), [=](char ch) { return func(ch); });
}
2014-03-22 22:05:03 +04:00
// IsFlexibleCase
// . Returns true if 'str' is:
// . UPPERCASE
// . lowercase
// . Capitalized
bool IsFlexibleCase(const std::string& str) {
if (str.empty())
return true;
if (IsEntirely(str, IsLower))
return true;
bool firstcaps = IsUpper(str[0]);
std::string rest = str.substr(1);
return firstcaps && (IsEntirely(rest, IsLower) || IsEntirely(rest, IsUpper));
}
} // namespace
2014-03-22 22:05:03 +04:00
namespace YAML {
std::pair<bool, bool> convert<bool>::decode(const Node& node) {
2014-03-22 22:05:03 +04:00
if (!node.IsScalar())
throw conversion::DecodeException("");
2014-03-22 22:05:03 +04:00
// we can't use iostream bool extraction operators as they don't
// recognize all possible values in the table below (taken from
// http://yaml.org/type/bool.html)
static const struct {
std::string truename, falsename;
2015-01-24 22:11:43 +03:00
} names[] = {
{"y", "n"},
{"yes", "no"},
{"true", "false"},
{"on", "off"},
2015-03-30 05:27:20 +03:00
};
2014-03-22 22:05:03 +04:00
if (!IsFlexibleCase(node.Scalar()))
throw conversion::DecodeException("");
2014-03-22 22:05:03 +04:00
for (const auto& name : names) {
if (name.truename == tolower(node.Scalar())) {
return std::make_pair(true, true);
2014-03-22 22:05:03 +04:00
}
if (name.falsename == tolower(node.Scalar())) {
return std::make_pair(true, false);
2014-03-22 22:05:03 +04:00
}
}
throw conversion::DecodeException("");
2014-03-22 22:05:03 +04:00
}
} // namespace YAML