From 9cdf5ab9a147f41262f522bd1afd1e797d733c3b Mon Sep 17 00:00:00 2001 From: James Turner Date: Mon, 17 Oct 2011 09:50:21 +0100 Subject: [PATCH] Add another helper to strutils, to compare version strings. --- simgear/misc/strutils.cxx | 20 ++++++++++++++++++++ simgear/misc/strutils.hxx | 8 ++++++++ simgear/misc/strutils_test.cxx | 10 ++++++++++ 3 files changed, 38 insertions(+) diff --git a/simgear/misc/strutils.cxx b/simgear/misc/strutils.cxx index 8bd33b7f..5a669a6b 100644 --- a/simgear/misc/strutils.cxx +++ b/simgear/misc/strutils.cxx @@ -259,6 +259,26 @@ namespace simgear { return result; } + int compare_versions(const string& v1, const string& v2) + { + vector v1parts(split(v1, ".")); + vector v2parts(split(v2, ".")); + + int lastPart = std::min(v1parts.size(), v2parts.size()); + for (int part=0; part < lastPart; ++part) { + int part1 = to_int(v1parts[part]); + int part2 = to_int(v2parts[part]); + + if (part1 != part2) { + return part1 - part2; + } + } // of parts iteration + + // reached end - longer wins + return v1parts.size() - v2parts.size(); + } + + } // end namespace strutils } // end namespace simgear diff --git a/simgear/misc/strutils.hxx b/simgear/misc/strutils.hxx index 1a0859d5..091ba823 100644 --- a/simgear/misc/strutils.hxx +++ b/simgear/misc/strutils.hxx @@ -127,6 +127,14 @@ namespace simgear { * convert a string representing a decimal number, to an int */ int to_int(const std::string& s, int base = 10); + + /** + * Like strcmp(), but for dotted versions strings NN.NN.NN + * any number of terms are support. + * @return 0 if versions match, -ve number if v1 is lower, +ve if v1 + * is greater + */ + int compare_versions(const std::string& v1, const std::string& v2); } // end namespace strutils } // end namespace simgear diff --git a/simgear/misc/strutils_test.cxx b/simgear/misc/strutils_test.cxx index f6e08e08..8369f4ea 100644 --- a/simgear/misc/strutils_test.cxx +++ b/simgear/misc/strutils_test.cxx @@ -53,6 +53,16 @@ int main (int ac, char ** av) COMPARE(to_int("0000000"), 0); COMPARE(to_int("-10000"), -10000); + VERIFY(compare_versions("1.0.12", "1.1") < 0); + VERIFY(compare_versions("1.1", "1.0.12") > 0); + VERIFY(compare_versions("10.6.7", "10.6.7") == 0); + VERIFY(compare_versions("2.0", "2.0.99") < 0); + VERIFY(compare_versions("99", "99") == 0); + VERIFY(compare_versions("99", "98") > 0); + +// since we compare numerically, leasing zeros shouldn't matter + VERIFY(compare_versions("0.06.7", "0.6.07") == 0); + cout << "all tests passed successfully!" << endl; return 0; } -- 2.39.5