Skip to content

Commit

Permalink
Fix VersionUtils to work with clang < 17 ranges support
Browse files Browse the repository at this point in the history
  • Loading branch information
danngreen committed Sep 18, 2024
1 parent 20e44c5 commit ae0a27b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
21 changes: 14 additions & 7 deletions tests/version_tools_tests.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
31 changes: 31 additions & 0 deletions util/version_tools.hh
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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));
Expand All @@ -41,5 +71,6 @@ Version parse_version(std::string_view vers) {
}
return version;
}
#endif

} // namespace VersionUtil

0 comments on commit ae0a27b

Please sign in to comment.