Small structure for parsing and comparing version numbers

This commit is contained in:
Moritz Bunkus 2010-12-22 23:07:51 +01:00
parent 0c8201523c
commit 5c26e8fc6d
2 changed files with 67 additions and 27 deletions

View File

@ -20,6 +20,59 @@
#define VERSIONNAME "Die Wiederkehr"
version_number_t::version_number_t()
: valid(false)
{
memset(parts, 0, 5 * sizeof(unsigned int));
}
version_number_t::version_number_t(const std::string &s)
: valid(false)
{
memset(parts, 0, 5 * sizeof(unsigned int));
static boost::regex s_version_number_re("^(\\d+)\\.(\\d+)\\.(\\d+)\(?:\\.(\\d+))?", boost::regex::perl);
boost::match_results<std::string::const_iterator> matches;
if (!boost::regex_search(s, matches, s_version_number_re))
return;
size_t idx;
for (idx = 1; 4 >= idx; ++idx) {
if (!matches[idx].str().empty())
parse_uint(matches[idx].str(), parts[idx - 1]);
else
parts[idx - 1] = 0;
}
valid = true;
}
version_number_t::version_number_t(const version_number_t &v) {
memcpy(parts, v.parts, 5 * sizeof(unsigned int));
valid = v.valid;
}
int
version_number_t::compare(const version_number_t &cmp)
const
{
size_t idx;
for (idx = 0; 5 > idx; ++idx)
if (parts[idx] < cmp.parts[idx])
return -1;
else if (parts[idx] > cmp.parts[idx])
return 1;
return 0;
}
bool
version_number_t::operator <(const version_number_t &cmp)
const
{
return compare(cmp) == -1;
}
std::string
get_version_info(const std::string &program,
bool full) {
@ -34,33 +87,7 @@ get_version_info(const std::string &program,
#endif // !defined(HAVE_BUILD_TIMESTAMP)
}
static unsigned int
_parse_version_number(const std::string &version_str) {
static boost::regex s_version_number_re("(\\d+)\\.(\\d+)\\.(\\d+)\(?:\\.(\\d+))?", boost::regex::perl);
boost::match_results<std::string::const_iterator> matches;
if (!boost::regex_search(version_str, matches, s_version_number_re))
return 0;
unsigned int version = 0, idx;
for (idx = 1; 4 >= idx; ++idx) {
version <<= 8;
if (!matches[idx].str().empty()) {
uint32_t number = 0;
parse_uint(matches[idx].str(), number);
version += number;
}
}
return version;
}
int
compare_current_version_to(const std::string &other_version_str) {
unsigned int my_version = _parse_version_number(VERSION);
unsigned int other_version = _parse_version_number(other_version_str);
return my_version < other_version ? -1
: my_version > other_version ? +1
: 0;
return version_number_t(VERSION).compare(version_number_t(other_version_str));
}

View File

@ -16,7 +16,20 @@
#include <string>
struct version_number_t {
unsigned int parts[5];
bool valid;
version_number_t();
version_number_t(const std::string &s);
version_number_t(const version_number_t &v);
bool operator <(const version_number_t &cmp) const;
int compare(const version_number_t &cmp) const;
};
std::string MTX_DLL_API get_version_info(const std::string &program, bool full = false);
int MTX_DLL_API compare_current_version_to(const std::string &other_version_str);
version_number_t MTX_DLL_API get_current_version();
#endif // __MTX_COMMON_VERSION_H