Skip to content

Commit

Permalink
Add utility for splitting version string into integer parts
Browse files Browse the repository at this point in the history
  • Loading branch information
danngreen committed Sep 17, 2024
1 parent 185e37d commit 20e44c5
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
46 changes: 46 additions & 0 deletions tests/version_tools_tests.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include "doctest.h"
#include "util/version_tools.hh"

TEST_CASE("parse") {
{
auto vers = VersionUtil::parse_version("1.2.16");
CHECK(vers.major == 1);
CHECK(vers.minor == 2);
CHECK(vers.revision == 16);
}

{
auto vers = VersionUtil::parse_version("9.1");
CHECK(vers.major == 9);
CHECK(vers.minor == 1);
CHECK(vers.revision == 0);
}

{
auto vers = VersionUtil::parse_version("2.0.99");
CHECK(vers.major == 2);
CHECK(vers.minor == 0);
CHECK(vers.revision == 99);
}

{
auto vers = VersionUtil::parse_version("2099");
CHECK(vers.major == 2099);
CHECK(vers.minor == 0);
CHECK(vers.revision == 0);
}

{
auto vers = VersionUtil::parse_version("garbage");
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);
// }
}
}
45 changes: 45 additions & 0 deletions util/version_tools.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#pragma once
#include <ranges>
#include <string_view>

namespace VersionUtil
{

struct Version {
unsigned major;
unsigned minor;
unsigned revision;

void set_field(unsigned index, unsigned val) {
if (index == 0)
major = val;
if (index == 1)
minor = val;
if (index == 2)
revision = val;
}
};

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));
});
return tokens;
}

Version parse_version(std::string_view vers) {
auto tokens = split(vers, ".");
Version version{};

for (unsigned i = 0; auto &&token : tokens) {
auto num = strtoul(token.data(), nullptr, 10);

version.set_field(i, num);

if (++i >= 3)
break;
}
return version;
}

} // namespace VersionUtil

0 comments on commit 20e44c5

Please sign in to comment.