From fd34cc30b8ef0d61d0763cf44eec534dfa02686e Mon Sep 17 00:00:00 2001 From: James Turner Date: Thu, 5 Jan 2017 10:52:48 +0000 Subject: [PATCH] compare_versions: limit how many parts are checked. This can be used to only check the first one or two parts of a version, to ensure only the major, or major+minor parts match. --- simgear/misc/strutils.cxx | 6 +++++- simgear/misc/strutils.hxx | 4 +++- simgear/misc/strutils_test.cxx | 5 +++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/simgear/misc/strutils.cxx b/simgear/misc/strutils.cxx index ef911230..ebe83e38 100644 --- a/simgear/misc/strutils.cxx +++ b/simgear/misc/strutils.cxx @@ -372,12 +372,16 @@ namespace simgear { return result; } - int compare_versions(const string& v1, const string& v2) + int compare_versions(const string& v1, const string& v2, int maxComponents) { vector v1parts(split(v1, ".")); vector v2parts(split(v2, ".")); int lastPart = std::min(v1parts.size(), v2parts.size()); + if (maxComponents > 0) { + lastPart = std::min(lastPart, maxComponents); + } + for (int part=0; part < lastPart; ++part) { int part1 = to_int(v1parts[part]); int part2 = to_int(v2parts[part]); diff --git a/simgear/misc/strutils.hxx b/simgear/misc/strutils.hxx index 94008afe..3ab3001f 100644 --- a/simgear/misc/strutils.hxx +++ b/simgear/misc/strutils.hxx @@ -174,8 +174,10 @@ namespace simgear { * any number of terms are supported. * @return 0 if versions match, -ve number if v1 is lower, +ve if v1 * is greater + * @param maxComponents is the maximum number of components to look at. + * This can be used to ignore (say) the patch level by setting it to 2 */ - int compare_versions(const std::string& v1, const std::string& v2); + int compare_versions(const std::string& v1, const std::string& v2, int maxComponents = 0); /** * Convert a string to upper case. diff --git a/simgear/misc/strutils_test.cxx b/simgear/misc/strutils_test.cxx index 81d12a2d..3d2ebdb5 100644 --- a/simgear/misc/strutils_test.cxx +++ b/simgear/misc/strutils_test.cxx @@ -155,6 +155,11 @@ void test_compare_versions() // Since we compare numerically, leading zeros shouldn't matter SG_CHECK_EQUAL(strutils::compare_versions("0.06.7", "0.6.07"), 0); + + + SG_CHECK_EQUAL(strutils::compare_versions("10.6.7", "10.6.8", 2), 0); + SG_CHECK_GT(strutils::compare_versions("10.7.7", "10.6.8", 2), 0); + SG_CHECK_EQUAL(strutils::compare_versions("10.8.7", "10.6.8", 1), 0); } void test_md5_hex()