Skip to content

Commit

Permalink
Add docopt::value::asBoolOr(bool) function
Browse files Browse the repository at this point in the history
Add docopt::value::asStringOr(string) function
Add docopt::value::asLongOr(long) function
Add docopt::value::asStringList(StringList) function
  • Loading branch information
Dadie committed Jun 21, 2022
1 parent 41f9b84 commit c9fe809
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions docopt_value.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
#include <functional> // std::hash
#include <iosfwd>
#include <stdexcept>
#include <cstdlib> // std::strtol
#include <cerrno> // errno, ERANGE

namespace docopt {

Expand Down Expand Up @@ -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<std::string> const& asStringList() const;
std::vector<std::string> const& asStringListOr(std::vector<std::string> const& value) const noexcept;

size_t hash() const noexcept;

Expand Down Expand Up @@ -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
{
Expand All @@ -292,20 +308,68 @@ 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
{
throwIfNotKind(Kind::String);
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<std::string> const& value::asStringList() const
{
throwIfNotKind(Kind::StringList);
return variant_.strList;
}

inline
std::vector<std::string> const& value::asStringListOr(std::vector<std::string> const& value) const noexcept
{
if(!isStringList())
{
return value;
}
return variant_.strList;
}

inline
bool operator==(value const& v1, value const& v2)
{
Expand Down

0 comments on commit c9fe809

Please sign in to comment.