From ae0a27beaf526d5507816f2577290ad4789bdd6f Mon Sep 17 00:00:00 2001 From: Dan Green Date: Wed, 18 Sep 2024 08:36:48 -0700 Subject: [PATCH] Fix VersionUtils to work with clang < 17 ranges support --- tests/version_tools_tests.cc | 21 ++++++++++++++------- util/version_tools.hh | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/tests/version_tools_tests.cc b/tests/version_tools_tests.cc index 03c587a..f7408b7 100644 --- a/tests/version_tools_tests.cc +++ b/tests/version_tools_tests.cc @@ -35,12 +35,19 @@ TEST_CASE("parse") { CHECK(vers.major == 0); CHECK(vers.minor == 0); CHECK(vers.revision == 0); - // try { - // auto vers = VersionUtil::parse_version("garbage"); - // (void)vers; - // CHECK(false); - // } catch (std::exception) { - // CHECK(true); - // } + } + + { + auto vers = VersionUtil::parse_version("678.BAD.123"); + CHECK(vers.major == 678); + CHECK(vers.minor == 0); + CHECK(vers.revision == 123); + } + + { + auto vers = VersionUtil::parse_version("777.-22.333"); + CHECK(vers.major == 777); + CHECK(vers.minor == 0); + CHECK(vers.revision == 333); } } diff --git a/util/version_tools.hh b/util/version_tools.hh index d75bbd4..e90feea 100644 --- a/util/version_tools.hh +++ b/util/version_tools.hh @@ -11,6 +11,10 @@ struct Version { unsigned revision; void set_field(unsigned index, unsigned val) { + //sanity check: + if (val > 9999) + return; + if (index == 0) major = val; if (index == 1) @@ -20,6 +24,32 @@ struct Version { } }; +#if !defined(__cpp_lib_ranges) || (__cpp_lib_ranges < 202211L) + +Version parse_version(std::string_view vers) { + Version version{}; + const std::string_view delim = "."; + + unsigned i = 0; + while (true) { + auto token = vers; + const auto pos = vers.find_first_of(delim); + if (pos != std::string_view::npos) { + token = vers.substr(0, pos); + vers = vers.substr(pos + 1); + } + + auto num = strtol(token.data(), nullptr, 10); + version.set_field(i++, num); + + if (pos == std::string_view::npos) + break; + } + return version; +} + +#else + auto split(std::string_view str, std::string_view delim) { auto tokens = str | std::ranges::views::split(delim) | std::ranges::views::transform([](auto &&str) { return std::string_view(&*str.begin(), std::ranges::distance(str)); @@ -41,5 +71,6 @@ Version parse_version(std::string_view vers) { } return version; } +#endif } // namespace VersionUtil