From 180bf8a3faed4cce40347832ccd91af5db33e106 Mon Sep 17 00:00:00 2001 From: "Korner, Daniel" Date: Tue, 22 Sep 2020 11:21:49 +0200 Subject: [PATCH] Add docopt::value::asBoolOr(bool) function Add docopt::value::asStringOr(string) function Add docopt::value::asLongOr(long) function Add docopt::value::asStringList(StringList) function --- docopt_value.h | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/docopt_value.h b/docopt_value.h index 441054d..9cab4eb 100644 --- a/docopt_value.h +++ b/docopt_value.h @@ -14,6 +14,8 @@ #include // std::hash #include #include +#include // std::strtol +#include // errno, ERANGE namespace docopt { @@ -58,9 +60,13 @@ namespace docopt { // Throws std::invalid_argument if the type does not match bool asBool() const; + bool asBoolOr(const bool value) const noexcept; long asLong() const; + long asLongOr(const long value) const noexcept; std::string const& asString() const; + std::string const& asStringOr(std::string const& value) const noexcept; std::vector const& asStringList() const; + std::vector const& asStringListOr(std::vector const& value) const noexcept; size_t hash() const noexcept; @@ -274,6 +280,16 @@ namespace docopt { return variant_.boolValue; } + inline + bool value::asBoolOr(const bool value) const noexcept + { + if(!isBool()) + { + return value; + } + return variant_.boolValue; + } + inline long value::asLong() const { @@ -292,6 +308,33 @@ namespace docopt { return variant_.longValue; } + inline + long value::asLongOr(const long value) const noexcept + { + // Attempt to convert a string to a long + if (isString()) { + const std::string& str = variant_.strValue; + char * str_end; + const long ret = std::strtol(str.c_str(), &str_end, 10); + // Case 1: No Conversion was possible, return given default value + if(str_end == str.c_str() && ret == 0) + { + return value; + } + // Case 2: Parsed value is out of range, return given default value + if (errno == ERANGE) { + return value; + } + // Case 3: Everything is fine, return parsed value + return ret; + } + if (!isLong()) + { + return value; + } + return variant_.longValue; + } + inline std::string const& value::asString() const { @@ -299,6 +342,17 @@ namespace docopt { return variant_.strValue; } + inline + std::string const& value::asStringOr(std::string const& value) const noexcept + { + if(!isString()) + { + return value; + } + return variant_.strValue; + } + + inline std::vector const& value::asStringList() const { @@ -306,6 +360,16 @@ namespace docopt { return variant_.strList; } + inline + std::vector const& value::asStringListOr(std::vector const& value) const noexcept + { + if(!isStringList()) + { + return value; + } + return variant_.strList; + } + inline bool operator==(value const& v1, value const& v2) {