/ src / common / version / helper.cpp
helper.cpp
 1  #include "helper.h"
 2  
 3  #include "../utils/string_utils.h"
 4  
 5  #include <algorithm>
 6  #include <sstream>
 7  
 8  VersionHelper::VersionHelper(const size_t major, const size_t minor, const size_t revision) :
 9      major{ major },
10      minor{ minor },
11      revision{ revision }
12  {
13  }
14  
15  template<typename CharT>
16  struct Constants;
17  
18  template<>
19  struct Constants<char>
20  {
21      static inline const char* LOWER_V = "v";
22      static inline const char* UPPER_V = "V";
23      static inline const char* DOT = ".";
24      static inline const char SPACE = ' ';
25  };
26  
27  template<>
28  struct Constants<wchar_t>
29  {
30      static inline const wchar_t* LOWER_V = L"v";
31      static inline const wchar_t* UPPER_V = L"V";
32      static inline const wchar_t* DOT = L".";
33      static inline const wchar_t SPACE = L' ';
34  };
35  
36  template<typename CharT>
37  std::optional<VersionHelper> fromString(std::basic_string_view<CharT> str)
38  {
39      try
40      {
41          str = left_trim<CharT>(trim<CharT>(str), Constants<CharT>::LOWER_V);
42          str = left_trim<CharT>(trim<CharT>(str), Constants<CharT>::UPPER_V);
43          std::basic_string<CharT> spacedStr{ str };
44          replace_chars<CharT>(spacedStr, Constants<CharT>::DOT, Constants<CharT>::SPACE);
45  
46          std::basic_istringstream<CharT> ss{ spacedStr };
47          VersionHelper result{ 0, 0, 0 };
48          ss >> result.major;
49          ss >> result.minor;
50          ss >> result.revision;
51          if (!ss.fail() && ss.eof())
52          {
53              return result;
54          }
55      }
56      catch (...)
57      {
58      }
59      return std::nullopt;
60  }
61  
62  std::optional<VersionHelper> VersionHelper::fromString(std::string_view s)
63  {
64      return ::fromString(s);
65  }
66  
67  std::optional<VersionHelper> VersionHelper::fromString(std::wstring_view s)
68  {
69      return ::fromString(s);
70  }
71  
72  std::wstring VersionHelper::toWstring() const
73  {
74      std::wstring result{ L"v" };
75      result += std::to_wstring(major);
76      result += L'.';
77      result += std::to_wstring(minor);
78      result += L'.';
79      result += std::to_wstring(revision);
80      return result;
81  }
82  
83  std::string VersionHelper::toString() const
84  {
85      std::string result{ "v" };
86      result += std::to_string(major);
87      result += '.';
88      result += std::to_string(minor);
89      result += '.';
90      result += std::to_string(revision);
91      return result;
92  }